babylon.viewer.max.js 5.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139
  1. (function universalModuleDefinition(root, factory) {
  2. if(typeof exports === 'object' && typeof module === 'object')
  3. module.exports = factory();
  4. else if(typeof define === 'function' && define.amd)
  5. define("babylonjs-viewer", [], factory);
  6. else if(typeof exports === 'object')
  7. exports["babylonjs-viewer"] = factory();
  8. else {
  9. root["BabylonViewer"] = factory(root["BABYLON"]);
  10. }
  11. })(this, function() {
  12. var BabylonViewer =
  13. /******/ (function(modules) { // webpackBootstrap
  14. /******/ // The module cache
  15. /******/ var installedModules = {};
  16. /******/
  17. /******/ // The require function
  18. /******/ function __webpack_require__(moduleId) {
  19. /******/
  20. /******/ // Check if module is in cache
  21. /******/ if(installedModules[moduleId]) {
  22. /******/ return installedModules[moduleId].exports;
  23. /******/ }
  24. /******/ // Create a new module (and put it into the cache)
  25. /******/ var module = installedModules[moduleId] = {
  26. /******/ i: moduleId,
  27. /******/ l: false,
  28. /******/ exports: {}
  29. /******/ };
  30. /******/
  31. /******/ // Execute the module function
  32. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  33. /******/
  34. /******/ // Flag the module as loaded
  35. /******/ module.l = true;
  36. /******/
  37. /******/ // Return the exports of the module
  38. /******/ return module.exports;
  39. /******/ }
  40. /******/
  41. /******/
  42. /******/ // expose the modules object (__webpack_modules__)
  43. /******/ __webpack_require__.m = modules;
  44. /******/
  45. /******/ // expose the module cache
  46. /******/ __webpack_require__.c = installedModules;
  47. /******/
  48. /******/ // define getter function for harmony exports
  49. /******/ __webpack_require__.d = function(exports, name, getter) {
  50. /******/ if(!__webpack_require__.o(exports, name)) {
  51. /******/ Object.defineProperty(exports, name, {
  52. /******/ configurable: false,
  53. /******/ enumerable: true,
  54. /******/ get: getter
  55. /******/ });
  56. /******/ }
  57. /******/ };
  58. /******/
  59. /******/ // getDefaultExport function for compatibility with non-harmony modules
  60. /******/ __webpack_require__.n = function(module) {
  61. /******/ var getter = module && module.__esModule ?
  62. /******/ function getDefault() { return module['default']; } :
  63. /******/ function getModuleExports() { return module; };
  64. /******/ __webpack_require__.d(getter, 'a', getter);
  65. /******/ return getter;
  66. /******/ };
  67. /******/
  68. /******/ // Object.prototype.hasOwnProperty.call
  69. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  70. /******/
  71. /******/ // __webpack_public_path__
  72. /******/ __webpack_require__.p = "";
  73. /******/
  74. /******/ // Load entry module and return exports
  75. /******/ return __webpack_require__(__webpack_require__.s = 14);
  76. /******/ })
  77. /************************************************************************/
  78. /******/ ([
  79. /* 0 */
  80. /***/ (function(module, exports, __webpack_require__) {
  81. /* WEBPACK VAR INJECTION */(function(global) {var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  82. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  83. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  84. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  85. return c > 3 && r && Object.defineProperty(target, key, r), r;
  86. };
  87. var __extends = (this && this.__extends) || (function () {
  88. var extendStatics = Object.setPrototypeOf ||
  89. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  90. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  91. return function (d, b) {
  92. extendStatics(d, b);
  93. function __() { this.constructor = d; }
  94. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  95. };
  96. })();
  97. (function universalModuleDefinition(root, factory) {
  98. if(true)
  99. module.exports = factory();
  100. else if(typeof define === 'function' && define.amd)
  101. define("babylonjs", [], factory);
  102. else if(typeof exports === 'object')
  103. exports["babylonjs"] = factory();
  104. else {
  105. root["BABYLON"] = factory(root["BABYLON"]);
  106. }
  107. })(this, function() {
  108. var BABYLON;
  109. (function (BABYLON) {
  110. /**
  111. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  112. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  113. */
  114. var EffectFallbacks = /** @class */ (function () {
  115. function EffectFallbacks() {
  116. this._defines = {};
  117. this._currentRank = 32;
  118. this._maxRank = -1;
  119. }
  120. /**
  121. * Removes the fallback from the bound mesh.
  122. */
  123. EffectFallbacks.prototype.unBindMesh = function () {
  124. this._mesh = null;
  125. };
  126. /**
  127. * Adds a fallback on the specified property.
  128. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  129. * @param define The name of the define in the shader
  130. */
  131. EffectFallbacks.prototype.addFallback = function (rank, define) {
  132. if (!this._defines[rank]) {
  133. if (rank < this._currentRank) {
  134. this._currentRank = rank;
  135. }
  136. if (rank > this._maxRank) {
  137. this._maxRank = rank;
  138. }
  139. this._defines[rank] = new Array();
  140. }
  141. this._defines[rank].push(define);
  142. };
  143. /**
  144. * Sets the mesh to use CPU skinning when needing to fallback.
  145. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  146. * @param mesh The mesh to use the fallbacks.
  147. */
  148. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  149. this._mesh = mesh;
  150. if (rank < this._currentRank) {
  151. this._currentRank = rank;
  152. }
  153. if (rank > this._maxRank) {
  154. this._maxRank = rank;
  155. }
  156. };
  157. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  158. /**
  159. * Checks to see if more fallbacks are still availible.
  160. */
  161. get: function () {
  162. return this._currentRank <= this._maxRank;
  163. },
  164. enumerable: true,
  165. configurable: true
  166. });
  167. /**
  168. * Removes the defines that shoould be removed when falling back.
  169. * @param currentDefines defines the current define statements for the shader.
  170. * @param effect defines the current effect we try to compile
  171. * @returns The resulting defines with defines of the current rank removed.
  172. */
  173. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  174. // First we try to switch to CPU skinning
  175. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  176. this._mesh.computeBonesUsingShaders = false;
  177. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  178. var scene = this._mesh.getScene();
  179. for (var index = 0; index < scene.meshes.length; index++) {
  180. var otherMesh = scene.meshes[index];
  181. if (!otherMesh.material) {
  182. continue;
  183. }
  184. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  185. continue;
  186. }
  187. if (otherMesh.material.getEffect() === effect) {
  188. otherMesh.computeBonesUsingShaders = false;
  189. }
  190. else {
  191. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  192. var subMesh = _a[_i];
  193. var subMeshEffect = subMesh.effect;
  194. if (subMeshEffect === effect) {
  195. otherMesh.computeBonesUsingShaders = false;
  196. break;
  197. }
  198. }
  199. }
  200. }
  201. }
  202. else {
  203. var currentFallbacks = this._defines[this._currentRank];
  204. if (currentFallbacks) {
  205. for (var index = 0; index < currentFallbacks.length; index++) {
  206. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  207. }
  208. }
  209. this._currentRank++;
  210. }
  211. return currentDefines;
  212. };
  213. return EffectFallbacks;
  214. }());
  215. BABYLON.EffectFallbacks = EffectFallbacks;
  216. /**
  217. * Options to be used when creating an effect.
  218. */
  219. var EffectCreationOptions = /** @class */ (function () {
  220. function EffectCreationOptions() {
  221. }
  222. return EffectCreationOptions;
  223. }());
  224. BABYLON.EffectCreationOptions = EffectCreationOptions;
  225. /**
  226. * Effect containing vertex and fragment shader that can be executed on an object.
  227. */
  228. var Effect = /** @class */ (function () {
  229. /**
  230. * Instantiates an effect.
  231. * An effect can be used to create/manage/execute vertex and fragment shaders.
  232. * @param baseName Name of the effect.
  233. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  234. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  235. * @param samplers List of sampler variables that will be passed to the shader.
  236. * @param engine Engine to be used to render the effect
  237. * @param defines Define statements to be added to the shader.
  238. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  239. * @param onCompiled Callback that will be called when the shader is compiled.
  240. * @param onError Callback that will be called if an error occurs during shader compilation.
  241. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  242. */
  243. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  244. if (samplers === void 0) { samplers = null; }
  245. if (defines === void 0) { defines = null; }
  246. if (fallbacks === void 0) { fallbacks = null; }
  247. if (onCompiled === void 0) { onCompiled = null; }
  248. if (onError === void 0) { onError = null; }
  249. var _this = this;
  250. /**
  251. * Unique ID of the effect.
  252. */
  253. this.uniqueId = 0;
  254. /**
  255. * Observable that will be called when the shader is compiled.
  256. */
  257. this.onCompileObservable = new BABYLON.Observable();
  258. /**
  259. * Observable that will be called if an error occurs during shader compilation.
  260. */
  261. this.onErrorObservable = new BABYLON.Observable();
  262. /**
  263. * Observable that will be called when effect is bound.
  264. */
  265. this.onBindObservable = new BABYLON.Observable();
  266. this._uniformBuffersNames = {};
  267. this._isReady = false;
  268. this._compilationError = "";
  269. this.name = baseName;
  270. if (attributesNamesOrOptions.attributes) {
  271. var options = attributesNamesOrOptions;
  272. this._engine = uniformsNamesOrEngine;
  273. this._attributesNames = options.attributes;
  274. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  275. this._samplers = options.samplers;
  276. this.defines = options.defines;
  277. this.onError = options.onError;
  278. this.onCompiled = options.onCompiled;
  279. this._fallbacks = options.fallbacks;
  280. this._indexParameters = options.indexParameters;
  281. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  282. if (options.uniformBuffersNames) {
  283. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  284. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  285. }
  286. }
  287. }
  288. else {
  289. this._engine = engine;
  290. this.defines = defines;
  291. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  292. this._samplers = samplers;
  293. this._attributesNames = attributesNamesOrOptions;
  294. this.onError = onError;
  295. this.onCompiled = onCompiled;
  296. this._indexParameters = indexParameters;
  297. this._fallbacks = fallbacks;
  298. }
  299. this.uniqueId = Effect._uniqueIdSeed++;
  300. if (this._getFromCache(baseName)) {
  301. this._prepareEffect();
  302. return;
  303. }
  304. var vertexSource;
  305. var fragmentSource;
  306. if (baseName.vertexElement) {
  307. vertexSource = document.getElementById(baseName.vertexElement);
  308. if (!vertexSource) {
  309. vertexSource = baseName.vertexElement;
  310. }
  311. }
  312. else {
  313. vertexSource = baseName.vertex || baseName;
  314. }
  315. if (baseName.fragmentElement) {
  316. fragmentSource = document.getElementById(baseName.fragmentElement);
  317. if (!fragmentSource) {
  318. fragmentSource = baseName.fragmentElement;
  319. }
  320. }
  321. else {
  322. fragmentSource = baseName.fragment || baseName;
  323. }
  324. var finalVertexCode;
  325. this._loadVertexShaderAsync(vertexSource)
  326. .then(function (vertexCode) {
  327. return _this._processIncludesAsync(vertexCode);
  328. })
  329. .then(function (vertexCodeWithIncludes) {
  330. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  331. return _this._loadFragmentShaderAsync(fragmentSource);
  332. })
  333. .then(function (fragmentCode) {
  334. return _this._processIncludesAsync(fragmentCode);
  335. })
  336. .then(function (fragmentCodeWithIncludes) {
  337. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  338. if (baseName) {
  339. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  340. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  341. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  342. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  343. }
  344. else {
  345. _this._vertexSourceCode = finalVertexCode;
  346. _this._fragmentSourceCode = migratedFragmentCode;
  347. }
  348. _this._setInCache(baseName);
  349. _this._prepareEffect();
  350. });
  351. }
  352. Effect.prototype._getSourceCacheKey = function (baseName) {
  353. var cacheKey = baseName;
  354. if (this._indexParameters) {
  355. for (var key in this._indexParameters) {
  356. if (this._indexParameters.hasOwnProperty(key)) {
  357. cacheKey += "|";
  358. cacheKey += key;
  359. cacheKey += "_";
  360. cacheKey += this._indexParameters[key];
  361. }
  362. }
  363. }
  364. return cacheKey;
  365. };
  366. Effect.prototype._getFromCache = function (baseName) {
  367. if (typeof baseName !== "string") {
  368. return false;
  369. }
  370. var cacheKey = this._getSourceCacheKey(baseName);
  371. var sources = Effect._sourceCache[cacheKey];
  372. if (!sources) {
  373. return false;
  374. }
  375. this._vertexSourceCode = sources.vertex;
  376. this._fragmentSourceCode = sources.fragment;
  377. return true;
  378. };
  379. Effect.prototype._setInCache = function (baseName) {
  380. if (typeof baseName !== "string") {
  381. return;
  382. }
  383. var cacheKey = this._getSourceCacheKey(baseName);
  384. Effect._sourceCache[cacheKey] = {
  385. vertex: this._vertexSourceCode,
  386. fragment: this._fragmentSourceCode
  387. };
  388. };
  389. Object.defineProperty(Effect.prototype, "key", {
  390. /**
  391. * Unique key for this effect
  392. */
  393. get: function () {
  394. return this._key;
  395. },
  396. enumerable: true,
  397. configurable: true
  398. });
  399. /**
  400. * If the effect has been compiled and prepared.
  401. * @returns if the effect is compiled and prepared.
  402. */
  403. Effect.prototype.isReady = function () {
  404. return this._isReady;
  405. };
  406. /**
  407. * The engine the effect was initialized with.
  408. * @returns the engine.
  409. */
  410. Effect.prototype.getEngine = function () {
  411. return this._engine;
  412. };
  413. /**
  414. * The compiled webGL program for the effect
  415. * @returns the webGL program.
  416. */
  417. Effect.prototype.getProgram = function () {
  418. return this._program;
  419. };
  420. /**
  421. * The set of names of attribute variables for the shader.
  422. * @returns An array of attribute names.
  423. */
  424. Effect.prototype.getAttributesNames = function () {
  425. return this._attributesNames;
  426. };
  427. /**
  428. * Returns the attribute at the given index.
  429. * @param index The index of the attribute.
  430. * @returns The location of the attribute.
  431. */
  432. Effect.prototype.getAttributeLocation = function (index) {
  433. return this._attributes[index];
  434. };
  435. /**
  436. * Returns the attribute based on the name of the variable.
  437. * @param name of the attribute to look up.
  438. * @returns the attribute location.
  439. */
  440. Effect.prototype.getAttributeLocationByName = function (name) {
  441. var index = this._attributesNames.indexOf(name);
  442. return this._attributes[index];
  443. };
  444. /**
  445. * The number of attributes.
  446. * @returns the numnber of attributes.
  447. */
  448. Effect.prototype.getAttributesCount = function () {
  449. return this._attributes.length;
  450. };
  451. /**
  452. * Gets the index of a uniform variable.
  453. * @param uniformName of the uniform to look up.
  454. * @returns the index.
  455. */
  456. Effect.prototype.getUniformIndex = function (uniformName) {
  457. return this._uniformsNames.indexOf(uniformName);
  458. };
  459. /**
  460. * Returns the attribute based on the name of the variable.
  461. * @param uniformName of the uniform to look up.
  462. * @returns the location of the uniform.
  463. */
  464. Effect.prototype.getUniform = function (uniformName) {
  465. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  466. };
  467. /**
  468. * Returns an array of sampler variable names
  469. * @returns The array of sampler variable neames.
  470. */
  471. Effect.prototype.getSamplers = function () {
  472. return this._samplers;
  473. };
  474. /**
  475. * The error from the last compilation.
  476. * @returns the error string.
  477. */
  478. Effect.prototype.getCompilationError = function () {
  479. return this._compilationError;
  480. };
  481. /**
  482. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  483. * @param func The callback to be used.
  484. */
  485. Effect.prototype.executeWhenCompiled = function (func) {
  486. if (this.isReady()) {
  487. func(this);
  488. return;
  489. }
  490. this.onCompileObservable.add(function (effect) {
  491. func(effect);
  492. });
  493. };
  494. /** @ignore */
  495. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  496. if (BABYLON.Tools.IsWindowObjectExist()) {
  497. // DOM element ?
  498. if (vertex instanceof HTMLElement) {
  499. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  500. return Promise.resolve(vertexCode);
  501. }
  502. }
  503. // Base64 encoded ?
  504. if (vertex.substr(0, 7) === "base64:") {
  505. var vertexBinary = window.atob(vertex.substr(7));
  506. return Promise.resolve(vertexBinary);
  507. }
  508. // Is in local store ?
  509. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  510. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  511. }
  512. var vertexShaderUrl;
  513. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  514. vertexShaderUrl = vertex;
  515. }
  516. else {
  517. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  518. }
  519. // Vertex shader
  520. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  521. };
  522. /** @ignore */
  523. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  524. if (BABYLON.Tools.IsWindowObjectExist()) {
  525. // DOM element ?
  526. if (fragment instanceof HTMLElement) {
  527. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  528. return Promise.resolve(fragmentCode);
  529. }
  530. }
  531. // Base64 encoded ?
  532. if (fragment.substr(0, 7) === "base64:") {
  533. var fragmentBinary = window.atob(fragment.substr(7));
  534. return Promise.resolve(fragmentBinary);
  535. }
  536. // Is in local store ?
  537. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  538. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  539. }
  540. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  541. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  542. }
  543. var fragmentShaderUrl;
  544. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  545. fragmentShaderUrl = fragment;
  546. }
  547. else {
  548. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  549. }
  550. // Fragment shader
  551. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  552. };
  553. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  554. // Rebuild shaders source code
  555. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  556. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  557. vertexCode = prefix + vertexCode;
  558. fragmentCode = prefix + fragmentCode;
  559. // Number lines of shaders source code
  560. var i = 2;
  561. var regex = /\n/gm;
  562. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  563. i = 2;
  564. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  565. // Dump shaders name and formatted source code
  566. if (this.name.vertexElement) {
  567. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  568. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  569. }
  570. else if (this.name.vertex) {
  571. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  572. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  573. }
  574. else {
  575. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  576. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  577. }
  578. };
  579. ;
  580. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  581. var preparedSourceCode = this._processPrecision(sourceCode);
  582. if (this._engine.webGLVersion == 1) {
  583. return preparedSourceCode;
  584. }
  585. // Already converted
  586. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  587. return preparedSourceCode.replace("#version 300 es", "");
  588. }
  589. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  590. // Remove extensions
  591. // #extension GL_OES_standard_derivatives : enable
  592. // #extension GL_EXT_shader_texture_lod : enable
  593. // #extension GL_EXT_frag_depth : enable
  594. // #extension GL_EXT_draw_buffers : require
  595. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  596. var result = preparedSourceCode.replace(regex, "");
  597. // Migrate to GLSL v300
  598. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  599. result = result.replace(/attribute[ \t]/g, "in ");
  600. result = result.replace(/[ \t]attribute/g, " in");
  601. if (isFragment) {
  602. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  603. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  604. result = result.replace(/texture2D\s*\(/g, "texture(");
  605. result = result.replace(/textureCube\s*\(/g, "texture(");
  606. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  607. result = result.replace(/gl_FragColor/g, "glFragColor");
  608. result = result.replace(/gl_FragData/g, "glFragData");
  609. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  610. }
  611. return result;
  612. };
  613. Effect.prototype._processIncludesAsync = function (sourceCode) {
  614. var _this = this;
  615. return new Promise(function (resolve, reject) {
  616. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  617. var match = regex.exec(sourceCode);
  618. var returnValue = sourceCode;
  619. while (match != null) {
  620. var includeFile = match[1];
  621. // Uniform declaration
  622. if (includeFile.indexOf("__decl__") !== -1) {
  623. includeFile = includeFile.replace(/__decl__/, "");
  624. if (_this._engine.supportsUniformBuffers) {
  625. includeFile = includeFile.replace(/Vertex/, "Ubo");
  626. includeFile = includeFile.replace(/Fragment/, "Ubo");
  627. }
  628. includeFile = includeFile + "Declaration";
  629. }
  630. if (Effect.IncludesShadersStore[includeFile]) {
  631. // Substitution
  632. var includeContent = Effect.IncludesShadersStore[includeFile];
  633. if (match[2]) {
  634. var splits = match[3].split(",");
  635. for (var index = 0; index < splits.length; index += 2) {
  636. var source = new RegExp(splits[index], "g");
  637. var dest = splits[index + 1];
  638. includeContent = includeContent.replace(source, dest);
  639. }
  640. }
  641. if (match[4]) {
  642. var indexString = match[5];
  643. if (indexString.indexOf("..") !== -1) {
  644. var indexSplits = indexString.split("..");
  645. var minIndex = parseInt(indexSplits[0]);
  646. var maxIndex = parseInt(indexSplits[1]);
  647. var sourceIncludeContent = includeContent.slice(0);
  648. includeContent = "";
  649. if (isNaN(maxIndex)) {
  650. maxIndex = _this._indexParameters[indexSplits[1]];
  651. }
  652. for (var i = minIndex; i < maxIndex; i++) {
  653. if (!_this._engine.supportsUniformBuffers) {
  654. // Ubo replacement
  655. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  656. return p1 + "{X}";
  657. });
  658. }
  659. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  660. }
  661. }
  662. else {
  663. if (!_this._engine.supportsUniformBuffers) {
  664. // Ubo replacement
  665. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  666. return p1 + "{X}";
  667. });
  668. }
  669. includeContent = includeContent.replace(/\{X\}/g, indexString);
  670. }
  671. }
  672. // Replace
  673. returnValue = returnValue.replace(match[0], includeContent);
  674. }
  675. else {
  676. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  677. _this._engine._loadFileAsync(includeShaderUrl)
  678. .then(function (fileContent) {
  679. Effect.IncludesShadersStore[includeFile] = fileContent;
  680. return _this._processIncludesAsync(returnValue);
  681. })
  682. .then(function (returnValue) {
  683. resolve(returnValue);
  684. });
  685. return;
  686. }
  687. match = regex.exec(sourceCode);
  688. }
  689. resolve(returnValue);
  690. });
  691. };
  692. Effect.prototype._processPrecision = function (source) {
  693. if (source.indexOf("precision highp float") === -1) {
  694. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  695. source = "precision mediump float;\n" + source;
  696. }
  697. else {
  698. source = "precision highp float;\n" + source;
  699. }
  700. }
  701. else {
  702. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  703. source = source.replace("precision highp float", "precision mediump float");
  704. }
  705. }
  706. return source;
  707. };
  708. /**
  709. * Recompiles the webGL program
  710. * @param vertexSourceCode The source code for the vertex shader.
  711. * @param fragmentSourceCode The source code for the fragment shader.
  712. * @param onCompiled Callback called when completed.
  713. * @param onError Callback called on error.
  714. */
  715. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  716. var _this = this;
  717. this._isReady = false;
  718. this._vertexSourceCodeOverride = vertexSourceCode;
  719. this._fragmentSourceCodeOverride = fragmentSourceCode;
  720. this.onError = function (effect, error) {
  721. if (onError) {
  722. onError(error);
  723. }
  724. };
  725. this.onCompiled = function () {
  726. var scenes = _this.getEngine().scenes;
  727. for (var i = 0; i < scenes.length; i++) {
  728. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  729. }
  730. if (onCompiled) {
  731. onCompiled(_this._program);
  732. }
  733. };
  734. this._fallbacks = null;
  735. this._prepareEffect();
  736. };
  737. /**
  738. * Gets the uniform locations of the the specified variable names
  739. * @param names THe names of the variables to lookup.
  740. * @returns Array of locations in the same order as variable names.
  741. */
  742. Effect.prototype.getSpecificUniformLocations = function (names) {
  743. var engine = this._engine;
  744. return engine.getUniforms(this._program, names);
  745. };
  746. /**
  747. * Prepares the effect
  748. */
  749. Effect.prototype._prepareEffect = function () {
  750. var attributesNames = this._attributesNames;
  751. var defines = this.defines;
  752. var fallbacks = this._fallbacks;
  753. this._valueCache = {};
  754. var previousProgram = this._program;
  755. try {
  756. var engine = this._engine;
  757. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  758. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  759. }
  760. else {
  761. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  762. }
  763. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  764. if (engine.supportsUniformBuffers) {
  765. for (var name in this._uniformBuffersNames) {
  766. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  767. }
  768. }
  769. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  770. this._attributes = engine.getAttributes(this._program, attributesNames);
  771. var index;
  772. for (index = 0; index < this._samplers.length; index++) {
  773. var sampler = this.getUniform(this._samplers[index]);
  774. if (sampler == null) {
  775. this._samplers.splice(index, 1);
  776. index--;
  777. }
  778. }
  779. engine.bindSamplers(this);
  780. this._compilationError = "";
  781. this._isReady = true;
  782. if (this.onCompiled) {
  783. this.onCompiled(this);
  784. }
  785. this.onCompileObservable.notifyObservers(this);
  786. this.onCompileObservable.clear();
  787. // Unbind mesh reference in fallbacks
  788. if (this._fallbacks) {
  789. this._fallbacks.unBindMesh();
  790. }
  791. if (previousProgram) {
  792. this.getEngine()._deleteProgram(previousProgram);
  793. }
  794. }
  795. catch (e) {
  796. this._compilationError = e.message;
  797. // Let's go through fallbacks then
  798. BABYLON.Tools.Error("Unable to compile effect:");
  799. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  800. return " " + uniform;
  801. }));
  802. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  803. return " " + attribute;
  804. }));
  805. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  806. BABYLON.Tools.Error("Error: " + this._compilationError);
  807. if (previousProgram) {
  808. this._program = previousProgram;
  809. this._isReady = true;
  810. if (this.onError) {
  811. this.onError(this, this._compilationError);
  812. }
  813. this.onErrorObservable.notifyObservers(this);
  814. }
  815. if (fallbacks && fallbacks.isMoreFallbacks) {
  816. BABYLON.Tools.Error("Trying next fallback.");
  817. this.defines = fallbacks.reduce(this.defines, this);
  818. this._prepareEffect();
  819. }
  820. else {
  821. if (this.onError) {
  822. this.onError(this, this._compilationError);
  823. }
  824. this.onErrorObservable.notifyObservers(this);
  825. this.onErrorObservable.clear();
  826. // Unbind mesh reference in fallbacks
  827. if (this._fallbacks) {
  828. this._fallbacks.unBindMesh();
  829. }
  830. }
  831. }
  832. };
  833. Object.defineProperty(Effect.prototype, "isSupported", {
  834. /**
  835. * Checks if the effect is supported. (Must be called after compilation)
  836. */
  837. get: function () {
  838. return this._compilationError === "";
  839. },
  840. enumerable: true,
  841. configurable: true
  842. });
  843. /**
  844. * Binds a texture to the engine to be used as output of the shader.
  845. * @param channel Name of the output variable.
  846. * @param texture Texture to bind.
  847. */
  848. Effect.prototype._bindTexture = function (channel, texture) {
  849. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  850. };
  851. /**
  852. * Sets a texture on the engine to be used in the shader.
  853. * @param channel Name of the sampler variable.
  854. * @param texture Texture to set.
  855. */
  856. Effect.prototype.setTexture = function (channel, texture) {
  857. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  858. };
  859. /**
  860. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  861. * @param channel Name of the sampler variable.
  862. * @param texture Texture to set.
  863. */
  864. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  865. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  866. };
  867. /**
  868. * Sets an array of textures on the engine to be used in the shader.
  869. * @param channel Name of the variable.
  870. * @param textures Textures to set.
  871. */
  872. Effect.prototype.setTextureArray = function (channel, textures) {
  873. if (this._samplers.indexOf(channel + "Ex") === -1) {
  874. var initialPos = this._samplers.indexOf(channel);
  875. for (var index = 1; index < textures.length; index++) {
  876. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  877. }
  878. }
  879. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  880. };
  881. /**
  882. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  883. * @param channel Name of the sampler variable.
  884. * @param postProcess Post process to get the input texture from.
  885. */
  886. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  887. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  888. };
  889. /** @ignore */
  890. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  891. var cache = this._valueCache[uniformName];
  892. var flag = matrix.updateFlag;
  893. if (cache !== undefined && cache === flag) {
  894. return false;
  895. }
  896. this._valueCache[uniformName] = flag;
  897. return true;
  898. };
  899. /** @ignore */
  900. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  901. var cache = this._valueCache[uniformName];
  902. if (!cache) {
  903. cache = [x, y];
  904. this._valueCache[uniformName] = cache;
  905. return true;
  906. }
  907. var changed = false;
  908. if (cache[0] !== x) {
  909. cache[0] = x;
  910. changed = true;
  911. }
  912. if (cache[1] !== y) {
  913. cache[1] = y;
  914. changed = true;
  915. }
  916. return changed;
  917. };
  918. /** @ignore */
  919. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  920. var cache = this._valueCache[uniformName];
  921. if (!cache) {
  922. cache = [x, y, z];
  923. this._valueCache[uniformName] = cache;
  924. return true;
  925. }
  926. var changed = false;
  927. if (cache[0] !== x) {
  928. cache[0] = x;
  929. changed = true;
  930. }
  931. if (cache[1] !== y) {
  932. cache[1] = y;
  933. changed = true;
  934. }
  935. if (cache[2] !== z) {
  936. cache[2] = z;
  937. changed = true;
  938. }
  939. return changed;
  940. };
  941. /** @ignore */
  942. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  943. var cache = this._valueCache[uniformName];
  944. if (!cache) {
  945. cache = [x, y, z, w];
  946. this._valueCache[uniformName] = cache;
  947. return true;
  948. }
  949. var changed = false;
  950. if (cache[0] !== x) {
  951. cache[0] = x;
  952. changed = true;
  953. }
  954. if (cache[1] !== y) {
  955. cache[1] = y;
  956. changed = true;
  957. }
  958. if (cache[2] !== z) {
  959. cache[2] = z;
  960. changed = true;
  961. }
  962. if (cache[3] !== w) {
  963. cache[3] = w;
  964. changed = true;
  965. }
  966. return changed;
  967. };
  968. /**
  969. * Binds a buffer to a uniform.
  970. * @param buffer Buffer to bind.
  971. * @param name Name of the uniform variable to bind to.
  972. */
  973. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  974. var bufferName = this._uniformBuffersNames[name];
  975. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  976. return;
  977. }
  978. Effect._baseCache[bufferName] = buffer;
  979. this._engine.bindUniformBufferBase(buffer, bufferName);
  980. };
  981. /**
  982. * Binds block to a uniform.
  983. * @param blockName Name of the block to bind.
  984. * @param index Index to bind.
  985. */
  986. Effect.prototype.bindUniformBlock = function (blockName, index) {
  987. this._engine.bindUniformBlock(this._program, blockName, index);
  988. };
  989. /**
  990. * Sets an interger value on a uniform variable.
  991. * @param uniformName Name of the variable.
  992. * @param value Value to be set.
  993. * @returns this effect.
  994. */
  995. Effect.prototype.setInt = function (uniformName, value) {
  996. var cache = this._valueCache[uniformName];
  997. if (cache !== undefined && cache === value)
  998. return this;
  999. this._valueCache[uniformName] = value;
  1000. this._engine.setInt(this.getUniform(uniformName), value);
  1001. return this;
  1002. };
  1003. /**
  1004. * Sets an int array on a uniform variable.
  1005. * @param uniformName Name of the variable.
  1006. * @param array array to be set.
  1007. * @returns this effect.
  1008. */
  1009. Effect.prototype.setIntArray = function (uniformName, array) {
  1010. this._valueCache[uniformName] = null;
  1011. this._engine.setIntArray(this.getUniform(uniformName), array);
  1012. return this;
  1013. };
  1014. /**
  1015. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1016. * @param uniformName Name of the variable.
  1017. * @param array array to be set.
  1018. * @returns this effect.
  1019. */
  1020. Effect.prototype.setIntArray2 = function (uniformName, array) {
  1021. this._valueCache[uniformName] = null;
  1022. this._engine.setIntArray2(this.getUniform(uniformName), array);
  1023. return this;
  1024. };
  1025. /**
  1026. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1027. * @param uniformName Name of the variable.
  1028. * @param array array to be set.
  1029. * @returns this effect.
  1030. */
  1031. Effect.prototype.setIntArray3 = function (uniformName, array) {
  1032. this._valueCache[uniformName] = null;
  1033. this._engine.setIntArray3(this.getUniform(uniformName), array);
  1034. return this;
  1035. };
  1036. /**
  1037. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1038. * @param uniformName Name of the variable.
  1039. * @param array array to be set.
  1040. * @returns this effect.
  1041. */
  1042. Effect.prototype.setIntArray4 = function (uniformName, array) {
  1043. this._valueCache[uniformName] = null;
  1044. this._engine.setIntArray4(this.getUniform(uniformName), array);
  1045. return this;
  1046. };
  1047. /**
  1048. * Sets an float array on a uniform variable.
  1049. * @param uniformName Name of the variable.
  1050. * @param array array to be set.
  1051. * @returns this effect.
  1052. */
  1053. Effect.prototype.setFloatArray = function (uniformName, array) {
  1054. this._valueCache[uniformName] = null;
  1055. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1056. return this;
  1057. };
  1058. /**
  1059. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1060. * @param uniformName Name of the variable.
  1061. * @param array array to be set.
  1062. * @returns this effect.
  1063. */
  1064. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  1065. this._valueCache[uniformName] = null;
  1066. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1067. return this;
  1068. };
  1069. /**
  1070. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1071. * @param uniformName Name of the variable.
  1072. * @param array array to be set.
  1073. * @returns this effect.
  1074. */
  1075. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1076. this._valueCache[uniformName] = null;
  1077. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1078. return this;
  1079. };
  1080. /**
  1081. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1082. * @param uniformName Name of the variable.
  1083. * @param array array to be set.
  1084. * @returns this effect.
  1085. */
  1086. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1087. this._valueCache[uniformName] = null;
  1088. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1089. return this;
  1090. };
  1091. /**
  1092. * Sets an array on a uniform variable.
  1093. * @param uniformName Name of the variable.
  1094. * @param array array to be set.
  1095. * @returns this effect.
  1096. */
  1097. Effect.prototype.setArray = function (uniformName, array) {
  1098. this._valueCache[uniformName] = null;
  1099. this._engine.setArray(this.getUniform(uniformName), array);
  1100. return this;
  1101. };
  1102. /**
  1103. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1104. * @param uniformName Name of the variable.
  1105. * @param array array to be set.
  1106. * @returns this effect.
  1107. */
  1108. Effect.prototype.setArray2 = function (uniformName, array) {
  1109. this._valueCache[uniformName] = null;
  1110. this._engine.setArray2(this.getUniform(uniformName), array);
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1115. * @param uniformName Name of the variable.
  1116. * @param array array to be set.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setArray3 = function (uniformName, array) {
  1120. this._valueCache[uniformName] = null;
  1121. this._engine.setArray3(this.getUniform(uniformName), array);
  1122. return this;
  1123. };
  1124. /**
  1125. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1126. * @param uniformName Name of the variable.
  1127. * @param array array to be set.
  1128. * @returns this effect.
  1129. */
  1130. Effect.prototype.setArray4 = function (uniformName, array) {
  1131. this._valueCache[uniformName] = null;
  1132. this._engine.setArray4(this.getUniform(uniformName), array);
  1133. return this;
  1134. };
  1135. /**
  1136. * Sets matrices on a uniform variable.
  1137. * @param uniformName Name of the variable.
  1138. * @param matrices matrices to be set.
  1139. * @returns this effect.
  1140. */
  1141. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1142. if (!matrices) {
  1143. return this;
  1144. }
  1145. this._valueCache[uniformName] = null;
  1146. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1147. return this;
  1148. };
  1149. /**
  1150. * Sets matrix on a uniform variable.
  1151. * @param uniformName Name of the variable.
  1152. * @param matrix matrix to be set.
  1153. * @returns this effect.
  1154. */
  1155. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1156. if (this._cacheMatrix(uniformName, matrix)) {
  1157. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1158. }
  1159. return this;
  1160. };
  1161. /**
  1162. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1163. * @param uniformName Name of the variable.
  1164. * @param matrix matrix to be set.
  1165. * @returns this effect.
  1166. */
  1167. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1168. this._valueCache[uniformName] = null;
  1169. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1170. return this;
  1171. };
  1172. /**
  1173. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1174. * @param uniformName Name of the variable.
  1175. * @param matrix matrix to be set.
  1176. * @returns this effect.
  1177. */
  1178. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1179. this._valueCache[uniformName] = null;
  1180. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1181. return this;
  1182. };
  1183. /**
  1184. * Sets a float on a uniform variable.
  1185. * @param uniformName Name of the variable.
  1186. * @param value value to be set.
  1187. * @returns this effect.
  1188. */
  1189. Effect.prototype.setFloat = function (uniformName, value) {
  1190. var cache = this._valueCache[uniformName];
  1191. if (cache !== undefined && cache === value)
  1192. return this;
  1193. this._valueCache[uniformName] = value;
  1194. this._engine.setFloat(this.getUniform(uniformName), value);
  1195. return this;
  1196. };
  1197. /**
  1198. * Sets a boolean on a uniform variable.
  1199. * @param uniformName Name of the variable.
  1200. * @param bool value to be set.
  1201. * @returns this effect.
  1202. */
  1203. Effect.prototype.setBool = function (uniformName, bool) {
  1204. var cache = this._valueCache[uniformName];
  1205. if (cache !== undefined && cache === bool)
  1206. return this;
  1207. this._valueCache[uniformName] = bool;
  1208. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1209. return this;
  1210. };
  1211. /**
  1212. * Sets a Vector2 on a uniform variable.
  1213. * @param uniformName Name of the variable.
  1214. * @param vector2 vector2 to be set.
  1215. * @returns this effect.
  1216. */
  1217. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1218. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1219. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1220. }
  1221. return this;
  1222. };
  1223. /**
  1224. * Sets a float2 on a uniform variable.
  1225. * @param uniformName Name of the variable.
  1226. * @param x First float in float2.
  1227. * @param y Second float in float2.
  1228. * @returns this effect.
  1229. */
  1230. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1231. if (this._cacheFloat2(uniformName, x, y)) {
  1232. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1233. }
  1234. return this;
  1235. };
  1236. /**
  1237. * Sets a Vector3 on a uniform variable.
  1238. * @param uniformName Name of the variable.
  1239. * @param vector3 Value to be set.
  1240. * @returns this effect.
  1241. */
  1242. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1243. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1244. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1245. }
  1246. return this;
  1247. };
  1248. /**
  1249. * Sets a float3 on a uniform variable.
  1250. * @param uniformName Name of the variable.
  1251. * @param x First float in float3.
  1252. * @param y Second float in float3.
  1253. * @param z Third float in float3.
  1254. * @returns this effect.
  1255. */
  1256. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1257. if (this._cacheFloat3(uniformName, x, y, z)) {
  1258. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1259. }
  1260. return this;
  1261. };
  1262. /**
  1263. * Sets a Vector4 on a uniform variable.
  1264. * @param uniformName Name of the variable.
  1265. * @param vector4 Value to be set.
  1266. * @returns this effect.
  1267. */
  1268. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1269. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1270. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1271. }
  1272. return this;
  1273. };
  1274. /**
  1275. * Sets a float4 on a uniform variable.
  1276. * @param uniformName Name of the variable.
  1277. * @param x First float in float4.
  1278. * @param y Second float in float4.
  1279. * @param z Third float in float4.
  1280. * @param w Fourth float in float4.
  1281. * @returns this effect.
  1282. */
  1283. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1284. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1285. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1286. }
  1287. return this;
  1288. };
  1289. /**
  1290. * Sets a Color3 on a uniform variable.
  1291. * @param uniformName Name of the variable.
  1292. * @param color3 Value to be set.
  1293. * @returns this effect.
  1294. */
  1295. Effect.prototype.setColor3 = function (uniformName, color3) {
  1296. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1297. this._engine.setColor3(this.getUniform(uniformName), color3);
  1298. }
  1299. return this;
  1300. };
  1301. /**
  1302. * Sets a Color4 on a uniform variable.
  1303. * @param uniformName Name of the variable.
  1304. * @param color3 Value to be set.
  1305. * @param alpha Alpha value to be set.
  1306. * @returns this effect.
  1307. */
  1308. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1309. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1310. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1311. }
  1312. return this;
  1313. };
  1314. /**
  1315. * Sets a Color4 on a uniform variable
  1316. * @param uniformName defines the name of the variable
  1317. * @param color4 defines the value to be set
  1318. * @returns this effect.
  1319. */
  1320. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1321. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1322. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1323. }
  1324. return this;
  1325. };
  1326. /**
  1327. * Resets the cache of effects.
  1328. */
  1329. Effect.ResetCache = function () {
  1330. Effect._baseCache = {};
  1331. };
  1332. Effect._uniqueIdSeed = 0;
  1333. Effect._baseCache = {};
  1334. Effect._sourceCache = {};
  1335. // Statics
  1336. /**
  1337. * Store of each shader (The can be looked up using effect.key)
  1338. */
  1339. Effect.ShadersStore = {};
  1340. /**
  1341. * Store of each included file for a shader (The can be looked up using effect.key)
  1342. */
  1343. Effect.IncludesShadersStore = {};
  1344. return Effect;
  1345. }());
  1346. BABYLON.Effect = Effect;
  1347. })(BABYLON || (BABYLON = {}));
  1348. //# sourceMappingURL=babylon.effect.js.map
  1349. //# sourceMappingURL=babylon.types.js.map
  1350. var BABYLON;
  1351. (function (BABYLON) {
  1352. var KeyboardEventTypes = /** @class */ (function () {
  1353. function KeyboardEventTypes() {
  1354. }
  1355. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1356. get: function () {
  1357. return KeyboardEventTypes._KEYDOWN;
  1358. },
  1359. enumerable: true,
  1360. configurable: true
  1361. });
  1362. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1363. get: function () {
  1364. return KeyboardEventTypes._KEYUP;
  1365. },
  1366. enumerable: true,
  1367. configurable: true
  1368. });
  1369. KeyboardEventTypes._KEYDOWN = 0x01;
  1370. KeyboardEventTypes._KEYUP = 0x02;
  1371. return KeyboardEventTypes;
  1372. }());
  1373. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1374. var KeyboardInfo = /** @class */ (function () {
  1375. function KeyboardInfo(type, event) {
  1376. this.type = type;
  1377. this.event = event;
  1378. }
  1379. return KeyboardInfo;
  1380. }());
  1381. BABYLON.KeyboardInfo = KeyboardInfo;
  1382. /**
  1383. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1384. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1385. */
  1386. var KeyboardInfoPre = /** @class */ (function (_super) {
  1387. __extends(KeyboardInfoPre, _super);
  1388. function KeyboardInfoPre(type, event) {
  1389. var _this = _super.call(this, type, event) || this;
  1390. _this.skipOnPointerObservable = false;
  1391. return _this;
  1392. }
  1393. return KeyboardInfoPre;
  1394. }(KeyboardInfo));
  1395. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1396. })(BABYLON || (BABYLON = {}));
  1397. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1398. var BABYLON;
  1399. (function (BABYLON) {
  1400. var PointerEventTypes = /** @class */ (function () {
  1401. function PointerEventTypes() {
  1402. }
  1403. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1404. get: function () {
  1405. return PointerEventTypes._POINTERDOWN;
  1406. },
  1407. enumerable: true,
  1408. configurable: true
  1409. });
  1410. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1411. get: function () {
  1412. return PointerEventTypes._POINTERUP;
  1413. },
  1414. enumerable: true,
  1415. configurable: true
  1416. });
  1417. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1418. get: function () {
  1419. return PointerEventTypes._POINTERMOVE;
  1420. },
  1421. enumerable: true,
  1422. configurable: true
  1423. });
  1424. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1425. get: function () {
  1426. return PointerEventTypes._POINTERWHEEL;
  1427. },
  1428. enumerable: true,
  1429. configurable: true
  1430. });
  1431. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1432. get: function () {
  1433. return PointerEventTypes._POINTERPICK;
  1434. },
  1435. enumerable: true,
  1436. configurable: true
  1437. });
  1438. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1439. get: function () {
  1440. return PointerEventTypes._POINTERTAP;
  1441. },
  1442. enumerable: true,
  1443. configurable: true
  1444. });
  1445. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1446. get: function () {
  1447. return PointerEventTypes._POINTERDOUBLETAP;
  1448. },
  1449. enumerable: true,
  1450. configurable: true
  1451. });
  1452. PointerEventTypes._POINTERDOWN = 0x01;
  1453. PointerEventTypes._POINTERUP = 0x02;
  1454. PointerEventTypes._POINTERMOVE = 0x04;
  1455. PointerEventTypes._POINTERWHEEL = 0x08;
  1456. PointerEventTypes._POINTERPICK = 0x10;
  1457. PointerEventTypes._POINTERTAP = 0x20;
  1458. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1459. return PointerEventTypes;
  1460. }());
  1461. BABYLON.PointerEventTypes = PointerEventTypes;
  1462. var PointerInfoBase = /** @class */ (function () {
  1463. function PointerInfoBase(type, event) {
  1464. this.type = type;
  1465. this.event = event;
  1466. }
  1467. return PointerInfoBase;
  1468. }());
  1469. BABYLON.PointerInfoBase = PointerInfoBase;
  1470. /**
  1471. * This class is used to store pointer related info for the onPrePointerObservable event.
  1472. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1473. */
  1474. var PointerInfoPre = /** @class */ (function (_super) {
  1475. __extends(PointerInfoPre, _super);
  1476. function PointerInfoPre(type, event, localX, localY) {
  1477. var _this = _super.call(this, type, event) || this;
  1478. _this.skipOnPointerObservable = false;
  1479. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1480. return _this;
  1481. }
  1482. return PointerInfoPre;
  1483. }(PointerInfoBase));
  1484. BABYLON.PointerInfoPre = PointerInfoPre;
  1485. /**
  1486. * This type contains all the data related to a pointer event in Babylon.js.
  1487. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1488. */
  1489. var PointerInfo = /** @class */ (function (_super) {
  1490. __extends(PointerInfo, _super);
  1491. function PointerInfo(type, event, pickInfo) {
  1492. var _this = _super.call(this, type, event) || this;
  1493. _this.pickInfo = pickInfo;
  1494. return _this;
  1495. }
  1496. return PointerInfo;
  1497. }(PointerInfoBase));
  1498. BABYLON.PointerInfo = PointerInfo;
  1499. })(BABYLON || (BABYLON = {}));
  1500. //# sourceMappingURL=babylon.pointerEvents.js.map
  1501. var BABYLON;
  1502. (function (BABYLON) {
  1503. BABYLON.ToGammaSpace = 1 / 2.2;
  1504. BABYLON.ToLinearSpace = 2.2;
  1505. BABYLON.Epsilon = 0.001;
  1506. /**
  1507. * Class used to hold a RBG color
  1508. */
  1509. var Color3 = /** @class */ (function () {
  1510. /**
  1511. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1512. * @param r defines the red component (between 0 and 1, default is 0)
  1513. * @param g defines the green component (between 0 and 1, default is 0)
  1514. * @param b defines the blue component (between 0 and 1, default is 0)
  1515. */
  1516. function Color3(
  1517. /**
  1518. * Defines the red component (between 0 and 1, default is 0)
  1519. */
  1520. r,
  1521. /**
  1522. * Defines the green component (between 0 and 1, default is 0)
  1523. */
  1524. g,
  1525. /**
  1526. * Defines the blue component (between 0 and 1, default is 0)
  1527. */
  1528. b) {
  1529. if (r === void 0) { r = 0; }
  1530. if (g === void 0) { g = 0; }
  1531. if (b === void 0) { b = 0; }
  1532. this.r = r;
  1533. this.g = g;
  1534. this.b = b;
  1535. }
  1536. /**
  1537. * Creates a string with the Color3 current values
  1538. * @returns the string representation of the Color3 object
  1539. */
  1540. Color3.prototype.toString = function () {
  1541. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1542. };
  1543. /**
  1544. * Returns the string "Color3"
  1545. * @returns "Color3"
  1546. */
  1547. Color3.prototype.getClassName = function () {
  1548. return "Color3";
  1549. };
  1550. /**
  1551. * Compute the Color3 hash code
  1552. * @returns an unique number that can be used to hash Color3 objects
  1553. */
  1554. Color3.prototype.getHashCode = function () {
  1555. var hash = this.r || 0;
  1556. hash = (hash * 397) ^ (this.g || 0);
  1557. hash = (hash * 397) ^ (this.b || 0);
  1558. return hash;
  1559. };
  1560. // Operators
  1561. /**
  1562. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1563. * @param array defines the array where to store the r,g,b components
  1564. * @param index defines an optional index in the target array to define where to start storing values
  1565. * @returns the current Color3 object
  1566. */
  1567. Color3.prototype.toArray = function (array, index) {
  1568. if (index === undefined) {
  1569. index = 0;
  1570. }
  1571. array[index] = this.r;
  1572. array[index + 1] = this.g;
  1573. array[index + 2] = this.b;
  1574. return this;
  1575. };
  1576. /**
  1577. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1578. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1579. * @returns a new {BABYLON.Color4} object
  1580. */
  1581. Color3.prototype.toColor4 = function (alpha) {
  1582. if (alpha === void 0) { alpha = 1; }
  1583. return new Color4(this.r, this.g, this.b, alpha);
  1584. };
  1585. /**
  1586. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1587. * @returns the new array
  1588. */
  1589. Color3.prototype.asArray = function () {
  1590. var result = new Array();
  1591. this.toArray(result, 0);
  1592. return result;
  1593. };
  1594. /**
  1595. * Returns the luminance value
  1596. * @returns a float value
  1597. */
  1598. Color3.prototype.toLuminance = function () {
  1599. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1600. };
  1601. /**
  1602. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1603. * @param otherColor defines the second operand
  1604. * @returns the new Color3 object
  1605. */
  1606. Color3.prototype.multiply = function (otherColor) {
  1607. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1608. };
  1609. /**
  1610. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1611. * @param otherColor defines the second operand
  1612. * @param result defines the Color3 object where to store the result
  1613. * @returns the current Color3
  1614. */
  1615. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1616. result.r = this.r * otherColor.r;
  1617. result.g = this.g * otherColor.g;
  1618. result.b = this.b * otherColor.b;
  1619. return this;
  1620. };
  1621. /**
  1622. * Determines equality between Color3 objects
  1623. * @param otherColor defines the second operand
  1624. * @returns true if the rgb values are equal to the passed ones
  1625. */
  1626. Color3.prototype.equals = function (otherColor) {
  1627. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1628. };
  1629. /**
  1630. * Determines equality between the current Color3 object and a set of r,b,g values
  1631. * @param r defines the red component to check
  1632. * @param g defines the green component to check
  1633. * @param b defines the blue component to check
  1634. * @returns true if the rgb values are equal to the passed ones
  1635. */
  1636. Color3.prototype.equalsFloats = function (r, g, b) {
  1637. return this.r === r && this.g === g && this.b === b;
  1638. };
  1639. /**
  1640. * Multiplies in place each rgb value by scale
  1641. * @param scale defines the scaling factor
  1642. * @returns the updated Color3.
  1643. */
  1644. Color3.prototype.scale = function (scale) {
  1645. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1646. };
  1647. /**
  1648. * Multiplies the rgb values by scale and stores the result into "result"
  1649. * @param scale defines the scaling factor
  1650. * @param result defines the Color3 object where to store the result
  1651. * @returns the unmodified current Color3.
  1652. */
  1653. Color3.prototype.scaleToRef = function (scale, result) {
  1654. result.r = this.r * scale;
  1655. result.g = this.g * scale;
  1656. result.b = this.b * scale;
  1657. return this;
  1658. };
  1659. /**
  1660. * Clamps the rgb values by the min and max values and stores the result into "result"
  1661. * @param min defines minimum clamping value (default is 0)
  1662. * @param max defines maximum clamping value (default is 1)
  1663. * @param result defines color to store the result into
  1664. * @returns the original Color3
  1665. */
  1666. Color3.prototype.clampToRef = function (min, max, result) {
  1667. if (min === void 0) { min = 0; }
  1668. if (max === void 0) { max = 1; }
  1669. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1670. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1671. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1672. return this;
  1673. };
  1674. /**
  1675. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1676. * @param otherColor defines the second operand
  1677. * @returns the new Color3
  1678. */
  1679. Color3.prototype.add = function (otherColor) {
  1680. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1681. };
  1682. /**
  1683. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1684. * @param otherColor defines the second operand
  1685. * @param result defines Color3 object to store the result into
  1686. * @returns the unmodified current Color3
  1687. */
  1688. Color3.prototype.addToRef = function (otherColor, result) {
  1689. result.r = this.r + otherColor.r;
  1690. result.g = this.g + otherColor.g;
  1691. result.b = this.b + otherColor.b;
  1692. return this;
  1693. };
  1694. /**
  1695. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1696. * @param otherColor defines the second operand
  1697. * @returns the new Color3
  1698. */
  1699. Color3.prototype.subtract = function (otherColor) {
  1700. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1701. };
  1702. /**
  1703. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1704. * @param otherColor defines the second operand
  1705. * @param result defines Color3 object to store the result into
  1706. * @returns the unmodified current Color3
  1707. */
  1708. Color3.prototype.subtractToRef = function (otherColor, result) {
  1709. result.r = this.r - otherColor.r;
  1710. result.g = this.g - otherColor.g;
  1711. result.b = this.b - otherColor.b;
  1712. return this;
  1713. };
  1714. /**
  1715. * Copy the current object
  1716. * @returns a new Color3 copied the current one
  1717. */
  1718. Color3.prototype.clone = function () {
  1719. return new Color3(this.r, this.g, this.b);
  1720. };
  1721. /**
  1722. * Copies the rgb values from the source in the current Color3
  1723. * @param source defines the source Color3 object
  1724. * @returns the updated Color3 object
  1725. */
  1726. Color3.prototype.copyFrom = function (source) {
  1727. this.r = source.r;
  1728. this.g = source.g;
  1729. this.b = source.b;
  1730. return this;
  1731. };
  1732. /**
  1733. * Updates the Color3 rgb values from the passed floats
  1734. * @param r defines the red component to read from
  1735. * @param g defines the green component to read from
  1736. * @param b defines the blue component to read from
  1737. * @returns the current Color3 object
  1738. */
  1739. Color3.prototype.copyFromFloats = function (r, g, b) {
  1740. this.r = r;
  1741. this.g = g;
  1742. this.b = b;
  1743. return this;
  1744. };
  1745. /**
  1746. * Updates the Color3 rgb values from the passed floats
  1747. * @param r defines the red component to read from
  1748. * @param g defines the green component to read from
  1749. * @param b defines the blue component to read from
  1750. * @returns the current Color3 object
  1751. */
  1752. Color3.prototype.set = function (r, g, b) {
  1753. return this.copyFromFloats(r, g, b);
  1754. };
  1755. /**
  1756. * Compute the Color3 hexadecimal code as a string
  1757. * @returns a string containing the hexadecimal representation of the Color3 object
  1758. */
  1759. Color3.prototype.toHexString = function () {
  1760. var intR = (this.r * 255) | 0;
  1761. var intG = (this.g * 255) | 0;
  1762. var intB = (this.b * 255) | 0;
  1763. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1764. };
  1765. /**
  1766. * Computes a new Color3 converted from the current one to linear space
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.prototype.toLinearSpace = function () {
  1770. var convertedColor = new Color3();
  1771. this.toLinearSpaceToRef(convertedColor);
  1772. return convertedColor;
  1773. };
  1774. /**
  1775. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1776. * @param convertedColor defines the Color3 object where to store the linear space version
  1777. * @returns the unmodified Color3
  1778. */
  1779. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1780. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1781. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1782. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1783. return this;
  1784. };
  1785. /**
  1786. * Computes a new Color3 converted from the current one to gamma space
  1787. * @returns a new Color3 object
  1788. */
  1789. Color3.prototype.toGammaSpace = function () {
  1790. var convertedColor = new Color3();
  1791. this.toGammaSpaceToRef(convertedColor);
  1792. return convertedColor;
  1793. };
  1794. /**
  1795. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1796. * @param convertedColor defines the Color3 object where to store the gamma space version
  1797. * @returns the unmodified Color3
  1798. */
  1799. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1800. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1801. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1802. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1803. return this;
  1804. };
  1805. // Statics
  1806. /**
  1807. * Creates a new Color3 from the string containing valid hexadecimal values
  1808. * @param hex defines a string containing valid hexadecimal values
  1809. * @returns a new Color3 object
  1810. */
  1811. Color3.FromHexString = function (hex) {
  1812. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1813. return new Color3(0, 0, 0);
  1814. }
  1815. var r = parseInt(hex.substring(1, 3), 16);
  1816. var g = parseInt(hex.substring(3, 5), 16);
  1817. var b = parseInt(hex.substring(5, 7), 16);
  1818. return Color3.FromInts(r, g, b);
  1819. };
  1820. /**
  1821. * Creates a new Vector3 from the starting index of the passed array
  1822. * @param array defines the source array
  1823. * @param offset defines an offset in the source array
  1824. * @returns a new Color3 object
  1825. */
  1826. Color3.FromArray = function (array, offset) {
  1827. if (offset === void 0) { offset = 0; }
  1828. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1829. };
  1830. /**
  1831. * Creates a new Color3 from integer values (< 256)
  1832. * @param r defines the red component to read from (value between 0 and 255)
  1833. * @param g defines the green component to read from (value between 0 and 255)
  1834. * @param b defines the blue component to read from (value between 0 and 255)
  1835. * @returns a new Color3 object
  1836. */
  1837. Color3.FromInts = function (r, g, b) {
  1838. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1839. };
  1840. /**
  1841. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1842. * @param start defines the start Color3 value
  1843. * @param end defines the end Color3 value
  1844. * @param amount defines the gradient value between start and end
  1845. * @returns a new Color3 object
  1846. */
  1847. Color3.Lerp = function (start, end, amount) {
  1848. var r = start.r + ((end.r - start.r) * amount);
  1849. var g = start.g + ((end.g - start.g) * amount);
  1850. var b = start.b + ((end.b - start.b) * amount);
  1851. return new Color3(r, g, b);
  1852. };
  1853. /**
  1854. * Returns a Color3 value containing a red color
  1855. * @returns a new Color3 object
  1856. */
  1857. Color3.Red = function () { return new Color3(1, 0, 0); };
  1858. /**
  1859. * Returns a Color3 value containing a green color
  1860. * @returns a new Color3 object
  1861. */
  1862. Color3.Green = function () { return new Color3(0, 1, 0); };
  1863. /**
  1864. * Returns a Color3 value containing a blue color
  1865. * @returns a new Color3 object
  1866. */
  1867. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1868. /**
  1869. * Returns a Color3 value containing a black color
  1870. * @returns a new Color3 object
  1871. */
  1872. Color3.Black = function () { return new Color3(0, 0, 0); };
  1873. /**
  1874. * Returns a Color3 value containing a white color
  1875. * @returns a new Color3 object
  1876. */
  1877. Color3.White = function () { return new Color3(1, 1, 1); };
  1878. /**
  1879. * Returns a Color3 value containing a purple color
  1880. * @returns a new Color3 object
  1881. */
  1882. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1883. /**
  1884. * Returns a Color3 value containing a magenta color
  1885. * @returns a new Color3 object
  1886. */
  1887. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1888. /**
  1889. * Returns a Color3 value containing a yellow color
  1890. * @returns a new Color3 object
  1891. */
  1892. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1893. /**
  1894. * Returns a Color3 value containing a gray color
  1895. * @returns a new Color3 object
  1896. */
  1897. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1898. /**
  1899. * Returns a Color3 value containing a teal color
  1900. * @returns a new Color3 object
  1901. */
  1902. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1903. /**
  1904. * Returns a Color3 value containing a random color
  1905. * @returns a new Color3 object
  1906. */
  1907. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1908. return Color3;
  1909. }());
  1910. BABYLON.Color3 = Color3;
  1911. /**
  1912. * Class used to hold a RBGA color
  1913. */
  1914. var Color4 = /** @class */ (function () {
  1915. /**
  1916. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1917. * @param r defines the red component (between 0 and 1, default is 0)
  1918. * @param g defines the green component (between 0 and 1, default is 0)
  1919. * @param b defines the blue component (between 0 and 1, default is 0)
  1920. * @param a defines the alpha component (between 0 and 1, default is 1)
  1921. */
  1922. function Color4(
  1923. /**
  1924. * Defines the red component (between 0 and 1, default is 0)
  1925. */
  1926. r,
  1927. /**
  1928. * Defines the green component (between 0 and 1, default is 0)
  1929. */
  1930. g,
  1931. /**
  1932. * Defines the blue component (between 0 and 1, default is 0)
  1933. */
  1934. b,
  1935. /**
  1936. * Defines the alpha component (between 0 and 1, default is 1)
  1937. */
  1938. a) {
  1939. if (r === void 0) { r = 0; }
  1940. if (g === void 0) { g = 0; }
  1941. if (b === void 0) { b = 0; }
  1942. if (a === void 0) { a = 1; }
  1943. this.r = r;
  1944. this.g = g;
  1945. this.b = b;
  1946. this.a = a;
  1947. }
  1948. // Operators
  1949. /**
  1950. * Adds in place the passed Color4 values to the current Color4 object
  1951. * @param right defines the second operand
  1952. * @returns the current updated Color4 object
  1953. */
  1954. Color4.prototype.addInPlace = function (right) {
  1955. this.r += right.r;
  1956. this.g += right.g;
  1957. this.b += right.b;
  1958. this.a += right.a;
  1959. return this;
  1960. };
  1961. /**
  1962. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1963. * @returns the new array
  1964. */
  1965. Color4.prototype.asArray = function () {
  1966. var result = new Array();
  1967. this.toArray(result, 0);
  1968. return result;
  1969. };
  1970. /**
  1971. * Stores from the starting index in the passed array the Color4 successive values
  1972. * @param array defines the array where to store the r,g,b components
  1973. * @param index defines an optional index in the target array to define where to start storing values
  1974. * @returns the current Color4 object
  1975. */
  1976. Color4.prototype.toArray = function (array, index) {
  1977. if (index === undefined) {
  1978. index = 0;
  1979. }
  1980. array[index] = this.r;
  1981. array[index + 1] = this.g;
  1982. array[index + 2] = this.b;
  1983. array[index + 3] = this.a;
  1984. return this;
  1985. };
  1986. /**
  1987. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1988. * @param right defines the second operand
  1989. * @returns a new Color4 object
  1990. */
  1991. Color4.prototype.add = 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. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1996. * @param right defines the second operand
  1997. * @returns a new Color4 object
  1998. */
  1999. Color4.prototype.subtract = function (right) {
  2000. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  2001. };
  2002. /**
  2003. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  2004. * @param right defines the second operand
  2005. * @param result defines the Color4 object where to store the result
  2006. * @returns the current Color4 object
  2007. */
  2008. Color4.prototype.subtractToRef = function (right, result) {
  2009. result.r = this.r - right.r;
  2010. result.g = this.g - right.g;
  2011. result.b = this.b - right.b;
  2012. result.a = this.a - right.a;
  2013. return this;
  2014. };
  2015. /**
  2016. * Creates a new Color4 with the current Color4 values multiplied by scale
  2017. * @param scale defines the scaling factor to apply
  2018. * @returns a new Color4 object
  2019. */
  2020. Color4.prototype.scale = function (scale) {
  2021. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2022. };
  2023. /**
  2024. * Multiplies the current Color4 values by scale and stores the result in "result"
  2025. * @param scale defines the scaling factor to apply
  2026. * @param result defines the Color4 object where to store the result
  2027. * @returns the current Color4.
  2028. */
  2029. Color4.prototype.scaleToRef = function (scale, result) {
  2030. result.r = this.r * scale;
  2031. result.g = this.g * scale;
  2032. result.b = this.b * scale;
  2033. result.a = this.a * scale;
  2034. return this;
  2035. };
  2036. /**
  2037. * Clamps the rgb values by the min and max values and stores the result into "result"
  2038. * @param min defines minimum clamping value (default is 0)
  2039. * @param max defines maximum clamping value (default is 1)
  2040. * @param result defines color to store the result into.
  2041. * @returns the cuurent Color4
  2042. */
  2043. Color4.prototype.clampToRef = function (min, max, result) {
  2044. if (min === void 0) { min = 0; }
  2045. if (max === void 0) { max = 1; }
  2046. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2047. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2048. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2049. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2050. return this;
  2051. };
  2052. /**
  2053. * Multipy an Color4 value by another and return a new Color4 object
  2054. * @param color defines the Color4 value to multiply by
  2055. * @returns a new Color4 object
  2056. */
  2057. Color4.prototype.multiply = function (color) {
  2058. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2059. };
  2060. /**
  2061. * Multipy a Color4 value by another and push the result in a reference value
  2062. * @param color defines the Color4 value to multiply by
  2063. * @param result defines the Color4 to fill the result in
  2064. * @returns the result Color4
  2065. */
  2066. Color4.prototype.multiplyToRef = function (color, result) {
  2067. result.r = this.r * color.r;
  2068. result.g = this.g * color.g;
  2069. result.b = this.b * color.b;
  2070. result.a = this.a * color.a;
  2071. return result;
  2072. };
  2073. /**
  2074. * Creates a string with the Color4 current values
  2075. * @returns the string representation of the Color4 object
  2076. */
  2077. Color4.prototype.toString = function () {
  2078. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2079. };
  2080. /**
  2081. * Returns the string "Color4"
  2082. * @returns "Color4"
  2083. */
  2084. Color4.prototype.getClassName = function () {
  2085. return "Color4";
  2086. };
  2087. /**
  2088. * Compute the Color4 hash code
  2089. * @returns an unique number that can be used to hash Color4 objects
  2090. */
  2091. Color4.prototype.getHashCode = function () {
  2092. var hash = this.r || 0;
  2093. hash = (hash * 397) ^ (this.g || 0);
  2094. hash = (hash * 397) ^ (this.b || 0);
  2095. hash = (hash * 397) ^ (this.a || 0);
  2096. return hash;
  2097. };
  2098. /**
  2099. * Creates a new Color4 copied from the current one
  2100. * @returns a new Color4 object
  2101. */
  2102. Color4.prototype.clone = function () {
  2103. return new Color4(this.r, this.g, this.b, this.a);
  2104. };
  2105. /**
  2106. * Copies the passed Color4 values into the current one
  2107. * @param source defines the source Color4 object
  2108. * @returns the current updated Color4 object
  2109. */
  2110. Color4.prototype.copyFrom = function (source) {
  2111. this.r = source.r;
  2112. this.g = source.g;
  2113. this.b = source.b;
  2114. this.a = source.a;
  2115. return this;
  2116. };
  2117. /**
  2118. * Copies the passed float values into the current one
  2119. * @param r defines the red component to read from
  2120. * @param g defines the green component to read from
  2121. * @param b defines the blue component to read from
  2122. * @param a defines the alpha component to read from
  2123. * @returns the current updated Color4 object
  2124. */
  2125. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2126. this.r = r;
  2127. this.g = g;
  2128. this.b = b;
  2129. this.a = a;
  2130. return this;
  2131. };
  2132. /**
  2133. * Copies the passed float values into the current one
  2134. * @param r defines the red component to read from
  2135. * @param g defines the green component to read from
  2136. * @param b defines the blue component to read from
  2137. * @param a defines the alpha component to read from
  2138. * @returns the current updated Color4 object
  2139. */
  2140. Color4.prototype.set = function (r, g, b, a) {
  2141. return this.copyFromFloats(r, g, b, a);
  2142. };
  2143. /**
  2144. * Compute the Color4 hexadecimal code as a string
  2145. * @returns a string containing the hexadecimal representation of the Color4 object
  2146. */
  2147. Color4.prototype.toHexString = function () {
  2148. var intR = (this.r * 255) | 0;
  2149. var intG = (this.g * 255) | 0;
  2150. var intB = (this.b * 255) | 0;
  2151. var intA = (this.a * 255) | 0;
  2152. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2153. };
  2154. /**
  2155. * Computes a new Color4 converted from the current one to linear space
  2156. * @returns a new Color4 object
  2157. */
  2158. Color4.prototype.toLinearSpace = function () {
  2159. var convertedColor = new Color4();
  2160. this.toLinearSpaceToRef(convertedColor);
  2161. return convertedColor;
  2162. };
  2163. /**
  2164. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2165. * @param convertedColor defines the Color4 object where to store the linear space version
  2166. * @returns the unmodified Color4
  2167. */
  2168. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2169. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2170. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2171. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2172. convertedColor.a = this.a;
  2173. return this;
  2174. };
  2175. /**
  2176. * Computes a new Color4 converted from the current one to gamma space
  2177. * @returns a new Color4 object
  2178. */
  2179. Color4.prototype.toGammaSpace = function () {
  2180. var convertedColor = new Color4();
  2181. this.toGammaSpaceToRef(convertedColor);
  2182. return convertedColor;
  2183. };
  2184. /**
  2185. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2186. * @param convertedColor defines the Color4 object where to store the gamma space version
  2187. * @returns the unmodified Color4
  2188. */
  2189. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2190. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2191. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2192. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2193. convertedColor.a = this.a;
  2194. return this;
  2195. };
  2196. // Statics
  2197. /**
  2198. * Creates a new Color4 from the string containing valid hexadecimal values
  2199. * @param hex defines a string containing valid hexadecimal values
  2200. * @returns a new Color4 object
  2201. */
  2202. Color4.FromHexString = function (hex) {
  2203. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2204. return new Color4(0.0, 0.0, 0.0, 0.0);
  2205. }
  2206. var r = parseInt(hex.substring(1, 3), 16);
  2207. var g = parseInt(hex.substring(3, 5), 16);
  2208. var b = parseInt(hex.substring(5, 7), 16);
  2209. var a = parseInt(hex.substring(7, 9), 16);
  2210. return Color4.FromInts(r, g, b, a);
  2211. };
  2212. /**
  2213. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2214. * @param left defines the start value
  2215. * @param right defines the end value
  2216. * @param amount defines the gradient factor
  2217. * @returns a new Color4 object
  2218. */
  2219. Color4.Lerp = function (left, right, amount) {
  2220. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2221. Color4.LerpToRef(left, right, amount, result);
  2222. return result;
  2223. };
  2224. /**
  2225. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2226. * @param left defines the start value
  2227. * @param right defines the end value
  2228. * @param amount defines the gradient factor
  2229. * @param result defines the Color4 object where to store data
  2230. */
  2231. Color4.LerpToRef = function (left, right, amount, result) {
  2232. result.r = left.r + (right.r - left.r) * amount;
  2233. result.g = left.g + (right.g - left.g) * amount;
  2234. result.b = left.b + (right.b - left.b) * amount;
  2235. result.a = left.a + (right.a - left.a) * amount;
  2236. };
  2237. /**
  2238. * Creates a new Color4 from the starting index element of the passed array
  2239. * @param array defines the source array to read from
  2240. * @param offset defines the offset in the source array
  2241. * @returns a new Color4 object
  2242. */
  2243. Color4.FromArray = function (array, offset) {
  2244. if (offset === void 0) { offset = 0; }
  2245. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2246. };
  2247. /**
  2248. * Creates a new Color3 from integer values (< 256)
  2249. * @param r defines the red component to read from (value between 0 and 255)
  2250. * @param g defines the green component to read from (value between 0 and 255)
  2251. * @param b defines the blue component to read from (value between 0 and 255)
  2252. * @param a defines the alpha component to read from (value between 0 and 255)
  2253. * @returns a new Color3 object
  2254. */
  2255. Color4.FromInts = function (r, g, b, a) {
  2256. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2257. };
  2258. /**
  2259. * Check the content of a given array and convert it to an array containing RGBA data
  2260. * If the original array was already containing count * 4 values then it is returned directly
  2261. * @param colors defines the array to check
  2262. * @param count defines the number of RGBA data to expect
  2263. * @returns an array containing count * 4 values (RGBA)
  2264. */
  2265. Color4.CheckColors4 = function (colors, count) {
  2266. // Check if color3 was used
  2267. if (colors.length === count * 3) {
  2268. var colors4 = [];
  2269. for (var index = 0; index < colors.length; index += 3) {
  2270. var newIndex = (index / 3) * 4;
  2271. colors4[newIndex] = colors[index];
  2272. colors4[newIndex + 1] = colors[index + 1];
  2273. colors4[newIndex + 2] = colors[index + 2];
  2274. colors4[newIndex + 3] = 1.0;
  2275. }
  2276. return colors4;
  2277. }
  2278. return colors;
  2279. };
  2280. return Color4;
  2281. }());
  2282. BABYLON.Color4 = Color4;
  2283. var Vector2 = /** @class */ (function () {
  2284. /**
  2285. * Creates a new Vector2 from the passed x and y coordinates.
  2286. */
  2287. function Vector2(x, y) {
  2288. this.x = x;
  2289. this.y = y;
  2290. }
  2291. /**
  2292. * Returns a string with the Vector2 coordinates.
  2293. */
  2294. Vector2.prototype.toString = function () {
  2295. return "{X: " + this.x + " Y:" + this.y + "}";
  2296. };
  2297. /**
  2298. * Returns the string "Vector2"
  2299. */
  2300. Vector2.prototype.getClassName = function () {
  2301. return "Vector2";
  2302. };
  2303. /**
  2304. * Returns the Vector2 hash code as a number.
  2305. */
  2306. Vector2.prototype.getHashCode = function () {
  2307. var hash = this.x || 0;
  2308. hash = (hash * 397) ^ (this.y || 0);
  2309. return hash;
  2310. };
  2311. // Operators
  2312. /**
  2313. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2314. * Returns the Vector2.
  2315. */
  2316. Vector2.prototype.toArray = function (array, index) {
  2317. if (index === void 0) { index = 0; }
  2318. array[index] = this.x;
  2319. array[index + 1] = this.y;
  2320. return this;
  2321. };
  2322. /**
  2323. * Returns a new array with 2 elements : the Vector2 coordinates.
  2324. */
  2325. Vector2.prototype.asArray = function () {
  2326. var result = new Array();
  2327. this.toArray(result, 0);
  2328. return result;
  2329. };
  2330. /**
  2331. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2332. * Returns the updated Vector2.
  2333. */
  2334. Vector2.prototype.copyFrom = function (source) {
  2335. this.x = source.x;
  2336. this.y = source.y;
  2337. return this;
  2338. };
  2339. /**
  2340. * Sets the Vector2 coordinates with the passed floats.
  2341. * Returns the updated Vector2.
  2342. */
  2343. Vector2.prototype.copyFromFloats = function (x, y) {
  2344. this.x = x;
  2345. this.y = y;
  2346. return this;
  2347. };
  2348. /**
  2349. * Sets the Vector2 coordinates with the passed floats.
  2350. * Returns the updated Vector2.
  2351. */
  2352. Vector2.prototype.set = function (x, y) {
  2353. return this.copyFromFloats(x, y);
  2354. };
  2355. /**
  2356. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2357. */
  2358. Vector2.prototype.add = function (otherVector) {
  2359. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2360. };
  2361. /**
  2362. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2363. * Returns the Vector2.
  2364. */
  2365. Vector2.prototype.addToRef = function (otherVector, result) {
  2366. result.x = this.x + otherVector.x;
  2367. result.y = this.y + otherVector.y;
  2368. return this;
  2369. };
  2370. /**
  2371. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2372. * Returns the updated Vector2.
  2373. */
  2374. Vector2.prototype.addInPlace = function (otherVector) {
  2375. this.x += otherVector.x;
  2376. this.y += otherVector.y;
  2377. return this;
  2378. };
  2379. /**
  2380. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2381. */
  2382. Vector2.prototype.addVector3 = function (otherVector) {
  2383. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2384. };
  2385. /**
  2386. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2387. */
  2388. Vector2.prototype.subtract = function (otherVector) {
  2389. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2390. };
  2391. /**
  2392. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2393. * Returns the Vector2.
  2394. */
  2395. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2396. result.x = this.x - otherVector.x;
  2397. result.y = this.y - otherVector.y;
  2398. return this;
  2399. };
  2400. /**
  2401. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2402. * Returns the updated Vector2.
  2403. */
  2404. Vector2.prototype.subtractInPlace = function (otherVector) {
  2405. this.x -= otherVector.x;
  2406. this.y -= otherVector.y;
  2407. return this;
  2408. };
  2409. /**
  2410. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2411. * Returns the updated Vector2.
  2412. */
  2413. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2414. this.x *= otherVector.x;
  2415. this.y *= otherVector.y;
  2416. return this;
  2417. };
  2418. /**
  2419. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2420. */
  2421. Vector2.prototype.multiply = function (otherVector) {
  2422. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2423. };
  2424. /**
  2425. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2426. * Returns the Vector2.
  2427. */
  2428. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2429. result.x = this.x * otherVector.x;
  2430. result.y = this.y * otherVector.y;
  2431. return this;
  2432. };
  2433. /**
  2434. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2435. */
  2436. Vector2.prototype.multiplyByFloats = function (x, y) {
  2437. return new Vector2(this.x * x, this.y * y);
  2438. };
  2439. /**
  2440. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2441. */
  2442. Vector2.prototype.divide = function (otherVector) {
  2443. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2444. };
  2445. /**
  2446. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2447. * Returns the Vector2.
  2448. */
  2449. Vector2.prototype.divideToRef = function (otherVector, result) {
  2450. result.x = this.x / otherVector.x;
  2451. result.y = this.y / otherVector.y;
  2452. return this;
  2453. };
  2454. /**
  2455. * Divides the current Vector3 coordinates by the passed ones.
  2456. * Returns the updated Vector3.
  2457. */
  2458. Vector2.prototype.divideInPlace = function (otherVector) {
  2459. return this.divideToRef(otherVector, this);
  2460. };
  2461. /**
  2462. * Returns a new Vector2 with current Vector2 negated coordinates.
  2463. */
  2464. Vector2.prototype.negate = function () {
  2465. return new Vector2(-this.x, -this.y);
  2466. };
  2467. /**
  2468. * Multiply the Vector2 coordinates by scale.
  2469. * Returns the updated Vector2.
  2470. */
  2471. Vector2.prototype.scaleInPlace = function (scale) {
  2472. this.x *= scale;
  2473. this.y *= scale;
  2474. return this;
  2475. };
  2476. /**
  2477. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2478. */
  2479. Vector2.prototype.scale = function (scale) {
  2480. return new Vector2(this.x * scale, this.y * scale);
  2481. };
  2482. /**
  2483. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2484. */
  2485. Vector2.prototype.equals = function (otherVector) {
  2486. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2487. };
  2488. /**
  2489. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2490. */
  2491. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2492. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2493. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2494. };
  2495. // Properties
  2496. /**
  2497. * Returns the vector length (float).
  2498. */
  2499. Vector2.prototype.length = function () {
  2500. return Math.sqrt(this.x * this.x + this.y * this.y);
  2501. };
  2502. /**
  2503. * Returns the vector squared length (float);
  2504. */
  2505. Vector2.prototype.lengthSquared = function () {
  2506. return (this.x * this.x + this.y * this.y);
  2507. };
  2508. // Methods
  2509. /**
  2510. * Normalize the vector.
  2511. * Returns the updated Vector2.
  2512. */
  2513. Vector2.prototype.normalize = function () {
  2514. var len = this.length();
  2515. if (len === 0)
  2516. return this;
  2517. var num = 1.0 / len;
  2518. this.x *= num;
  2519. this.y *= num;
  2520. return this;
  2521. };
  2522. /**
  2523. * Returns a new Vector2 copied from the Vector2.
  2524. */
  2525. Vector2.prototype.clone = function () {
  2526. return new Vector2(this.x, this.y);
  2527. };
  2528. // Statics
  2529. /**
  2530. * Returns a new Vector2(0, 0)
  2531. */
  2532. Vector2.Zero = function () {
  2533. return new Vector2(0, 0);
  2534. };
  2535. /**
  2536. * Returns a new Vector2(1, 1)
  2537. */
  2538. Vector2.One = function () {
  2539. return new Vector2(1, 1);
  2540. };
  2541. /**
  2542. * Returns a new Vector2 set from the passed index element of the passed array.
  2543. */
  2544. Vector2.FromArray = function (array, offset) {
  2545. if (offset === void 0) { offset = 0; }
  2546. return new Vector2(array[offset], array[offset + 1]);
  2547. };
  2548. /**
  2549. * Sets "result" from the passed index element of the passed array.
  2550. */
  2551. Vector2.FromArrayToRef = function (array, offset, result) {
  2552. result.x = array[offset];
  2553. result.y = array[offset + 1];
  2554. };
  2555. /**
  2556. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2557. */
  2558. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2559. var squared = amount * amount;
  2560. var cubed = amount * squared;
  2561. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2562. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2563. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2564. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2565. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2566. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2567. return new Vector2(x, y);
  2568. };
  2569. /**
  2570. * 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".
  2571. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2572. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2573. */
  2574. Vector2.Clamp = function (value, min, max) {
  2575. var x = value.x;
  2576. x = (x > max.x) ? max.x : x;
  2577. x = (x < min.x) ? min.x : x;
  2578. var y = value.y;
  2579. y = (y > max.y) ? max.y : y;
  2580. y = (y < min.y) ? min.y : y;
  2581. return new Vector2(x, y);
  2582. };
  2583. /**
  2584. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2585. */
  2586. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2587. var squared = amount * amount;
  2588. var cubed = amount * squared;
  2589. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2590. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2591. var part3 = (cubed - (2.0 * squared)) + amount;
  2592. var part4 = cubed - squared;
  2593. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2594. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2595. return new Vector2(x, y);
  2596. };
  2597. /**
  2598. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2599. */
  2600. Vector2.Lerp = function (start, end, amount) {
  2601. var x = start.x + ((end.x - start.x) * amount);
  2602. var y = start.y + ((end.y - start.y) * amount);
  2603. return new Vector2(x, y);
  2604. };
  2605. /**
  2606. * Returns the dot product (float) of the vector "left" and the vector "right".
  2607. */
  2608. Vector2.Dot = function (left, right) {
  2609. return left.x * right.x + left.y * right.y;
  2610. };
  2611. /**
  2612. * Returns a new Vector2 equal to the normalized passed vector.
  2613. */
  2614. Vector2.Normalize = function (vector) {
  2615. var newVector = vector.clone();
  2616. newVector.normalize();
  2617. return newVector;
  2618. };
  2619. /**
  2620. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2621. */
  2622. Vector2.Minimize = 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 maximal coordinate values from the "left" and "right" vectors.
  2629. */
  2630. Vector2.Maximize = function (left, right) {
  2631. var x = (left.x > right.x) ? left.x : right.x;
  2632. var y = (left.y > right.y) ? left.y : right.y;
  2633. return new Vector2(x, y);
  2634. };
  2635. /**
  2636. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2637. */
  2638. Vector2.Transform = function (vector, transformation) {
  2639. var r = Vector2.Zero();
  2640. Vector2.TransformToRef(vector, transformation, r);
  2641. return r;
  2642. };
  2643. /**
  2644. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2645. */
  2646. Vector2.TransformToRef = function (vector, transformation, result) {
  2647. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2648. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2649. result.x = x;
  2650. result.y = y;
  2651. };
  2652. /**
  2653. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2654. */
  2655. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2656. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2657. var sign = a < 0 ? -1 : 1;
  2658. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2659. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2660. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2661. };
  2662. /**
  2663. * Returns the distance (float) between the vectors "value1" and "value2".
  2664. */
  2665. Vector2.Distance = function (value1, value2) {
  2666. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2667. };
  2668. /**
  2669. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2670. */
  2671. Vector2.DistanceSquared = function (value1, value2) {
  2672. var x = value1.x - value2.x;
  2673. var y = value1.y - value2.y;
  2674. return (x * x) + (y * y);
  2675. };
  2676. /**
  2677. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2678. */
  2679. Vector2.Center = function (value1, value2) {
  2680. var center = value1.add(value2);
  2681. center.scaleInPlace(0.5);
  2682. return center;
  2683. };
  2684. /**
  2685. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2686. */
  2687. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2688. var l2 = Vector2.DistanceSquared(segA, segB);
  2689. if (l2 === 0.0) {
  2690. return Vector2.Distance(p, segA);
  2691. }
  2692. var v = segB.subtract(segA);
  2693. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2694. var proj = segA.add(v.multiplyByFloats(t, t));
  2695. return Vector2.Distance(p, proj);
  2696. };
  2697. return Vector2;
  2698. }());
  2699. BABYLON.Vector2 = Vector2;
  2700. /**
  2701. * Classed used to store (x,y,z) vector representation
  2702. * A Vector3 is the main object used in 3D geometry
  2703. * It can represent etiher the coordinates of a point the space, either a direction
  2704. * Reminder: Babylon.js uses a left handed forward facing system
  2705. */
  2706. var Vector3 = /** @class */ (function () {
  2707. /**
  2708. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2709. * @param x defines the first coordinates (on X axis)
  2710. * @param y defines the second coordinates (on Y axis)
  2711. * @param z defines the third coordinates (on Z axis)
  2712. */
  2713. function Vector3(
  2714. /**
  2715. * Defines the first coordinates (on X axis)
  2716. */
  2717. x,
  2718. /**
  2719. * Defines the second coordinates (on Y axis)
  2720. */
  2721. y,
  2722. /**
  2723. * Defines the third coordinates (on Z axis)
  2724. */
  2725. z) {
  2726. this.x = x;
  2727. this.y = y;
  2728. this.z = z;
  2729. }
  2730. /**
  2731. * Creates a string representation of the Vector3
  2732. * @returns a string with the Vector3 coordinates.
  2733. */
  2734. Vector3.prototype.toString = function () {
  2735. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2736. };
  2737. /**
  2738. * Gets the class name
  2739. * @returns the string "Vector3"
  2740. */
  2741. Vector3.prototype.getClassName = function () {
  2742. return "Vector3";
  2743. };
  2744. /**
  2745. * Creates the Vector3 hash code
  2746. * @returns a number which tends to be unique between Vector3 instances
  2747. */
  2748. Vector3.prototype.getHashCode = function () {
  2749. var hash = this.x || 0;
  2750. hash = (hash * 397) ^ (this.y || 0);
  2751. hash = (hash * 397) ^ (this.z || 0);
  2752. return hash;
  2753. };
  2754. // Operators
  2755. /**
  2756. * Creates an array containing three elements : the coordinates of the Vector3
  2757. * @returns a new array of numbers
  2758. */
  2759. Vector3.prototype.asArray = function () {
  2760. var result = [];
  2761. this.toArray(result, 0);
  2762. return result;
  2763. };
  2764. /**
  2765. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2766. * @param array defines the destination array
  2767. * @param index defines the offset in the destination array
  2768. * @returns the current Vector3
  2769. */
  2770. Vector3.prototype.toArray = function (array, index) {
  2771. if (index === void 0) { index = 0; }
  2772. array[index] = this.x;
  2773. array[index + 1] = this.y;
  2774. array[index + 2] = this.z;
  2775. return this;
  2776. };
  2777. /**
  2778. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2779. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2780. */
  2781. Vector3.prototype.toQuaternion = function () {
  2782. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2783. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2784. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2785. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2786. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2787. var cosy = Math.cos(this.y * 0.5);
  2788. var siny = Math.sin(this.y * 0.5);
  2789. result.x = coszMinusx * siny;
  2790. result.y = -sinzMinusx * siny;
  2791. result.z = sinxPlusz * cosy;
  2792. result.w = cosxPlusz * cosy;
  2793. return result;
  2794. };
  2795. /**
  2796. * Adds the passed vector to the current Vector3
  2797. * @param otherVector defines the second operand
  2798. * @returns the current updated Vector3
  2799. */
  2800. Vector3.prototype.addInPlace = function (otherVector) {
  2801. this.x += otherVector.x;
  2802. this.y += otherVector.y;
  2803. this.z += otherVector.z;
  2804. return this;
  2805. };
  2806. /**
  2807. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2808. * @param otherVector defines the second operand
  2809. * @returns the resulting Vector3
  2810. */
  2811. Vector3.prototype.add = function (otherVector) {
  2812. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2813. };
  2814. /**
  2815. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2816. * @param otherVector defines the second operand
  2817. * @param result defines the Vector3 object where to store the result
  2818. * @returns the current Vector3
  2819. */
  2820. Vector3.prototype.addToRef = function (otherVector, result) {
  2821. result.x = this.x + otherVector.x;
  2822. result.y = this.y + otherVector.y;
  2823. result.z = this.z + otherVector.z;
  2824. return this;
  2825. };
  2826. /**
  2827. * Subtract the passed vector from the current Vector3
  2828. * @param otherVector defines the second operand
  2829. * @returns the current updated Vector3
  2830. */
  2831. Vector3.prototype.subtractInPlace = function (otherVector) {
  2832. this.x -= otherVector.x;
  2833. this.y -= otherVector.y;
  2834. this.z -= otherVector.z;
  2835. return this;
  2836. };
  2837. /**
  2838. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2839. * @param otherVector defines the second operand
  2840. * @returns the resulting Vector3
  2841. */
  2842. Vector3.prototype.subtract = function (otherVector) {
  2843. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2844. };
  2845. /**
  2846. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2847. * @param otherVector defines the second operand
  2848. * @param result defines the Vector3 object where to store the result
  2849. * @returns the current Vector3
  2850. */
  2851. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2852. result.x = this.x - otherVector.x;
  2853. result.y = this.y - otherVector.y;
  2854. result.z = this.z - otherVector.z;
  2855. return this;
  2856. };
  2857. /**
  2858. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2859. * @param x defines the x coordinate of the operand
  2860. * @param y defines the y coordinate of the operand
  2861. * @param z defines the z coordinate of the operand
  2862. * @returns the resulting Vector3
  2863. */
  2864. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2865. return new Vector3(this.x - x, this.y - y, this.z - z);
  2866. };
  2867. /**
  2868. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2869. * @param x defines the x coordinate of the operand
  2870. * @param y defines the y coordinate of the operand
  2871. * @param z defines the z coordinate of the operand
  2872. * @param result defines the Vector3 object where to store the result
  2873. * @returns the current Vector3
  2874. */
  2875. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2876. result.x = this.x - x;
  2877. result.y = this.y - y;
  2878. result.z = this.z - z;
  2879. return this;
  2880. };
  2881. /**
  2882. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2883. * @returns a new Vector3
  2884. */
  2885. Vector3.prototype.negate = function () {
  2886. return new Vector3(-this.x, -this.y, -this.z);
  2887. };
  2888. /**
  2889. * Multiplies the Vector3 coordinates by the float "scale"
  2890. * @param scale defines the multiplier factor
  2891. * @returns the current updated Vector3
  2892. */
  2893. Vector3.prototype.scaleInPlace = function (scale) {
  2894. this.x *= scale;
  2895. this.y *= scale;
  2896. this.z *= scale;
  2897. return this;
  2898. };
  2899. /**
  2900. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2901. * @param scale defines the multiplier factor
  2902. * @returns a new Vector3
  2903. */
  2904. Vector3.prototype.scale = function (scale) {
  2905. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2906. };
  2907. /**
  2908. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2909. * @param scale defines the multiplier factor
  2910. * @param result defines the Vector3 object where to store the result
  2911. * @returns the current Vector3
  2912. */
  2913. Vector3.prototype.scaleToRef = function (scale, result) {
  2914. result.x = this.x * scale;
  2915. result.y = this.y * scale;
  2916. result.z = this.z * scale;
  2917. return this;
  2918. };
  2919. /**
  2920. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2921. * @param otherVector defines the second operand
  2922. * @returns true if both vectors are equals
  2923. */
  2924. Vector3.prototype.equals = function (otherVector) {
  2925. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2926. };
  2927. /**
  2928. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2929. * @param otherVector defines the second operand
  2930. * @param epsilon defines the minimal distance to define values as equals
  2931. * @returns true if both vectors are distant less than epsilon
  2932. */
  2933. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2934. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2935. 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);
  2936. };
  2937. /**
  2938. * Returns true if the current Vector3 coordinates equals the passed floats
  2939. * @param x defines the x coordinate of the operand
  2940. * @param y defines the y coordinate of the operand
  2941. * @param z defines the z coordinate of the operand
  2942. * @returns true if both vectors are equals
  2943. */
  2944. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2945. return this.x === x && this.y === y && this.z === z;
  2946. };
  2947. /**
  2948. * Multiplies the current Vector3 coordinates by the passed ones
  2949. * @param otherVector defines the second operand
  2950. * @returns the current updated Vector3
  2951. */
  2952. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2953. this.x *= otherVector.x;
  2954. this.y *= otherVector.y;
  2955. this.z *= otherVector.z;
  2956. return this;
  2957. };
  2958. /**
  2959. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2960. * @param otherVector defines the second operand
  2961. * @returns the new Vector3
  2962. */
  2963. Vector3.prototype.multiply = function (otherVector) {
  2964. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2965. };
  2966. /**
  2967. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2968. * @param otherVector defines the second operand
  2969. * @param result defines the Vector3 object where to store the result
  2970. * @returns the current Vector3
  2971. */
  2972. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2973. result.x = this.x * otherVector.x;
  2974. result.y = this.y * otherVector.y;
  2975. result.z = this.z * otherVector.z;
  2976. return this;
  2977. };
  2978. /**
  2979. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2980. * @param x defines the x coordinate of the operand
  2981. * @param y defines the y coordinate of the operand
  2982. * @param z defines the z coordinate of the operand
  2983. * @returns the new Vector3
  2984. */
  2985. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2986. return new Vector3(this.x * x, this.y * y, this.z * z);
  2987. };
  2988. /**
  2989. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2990. * @param otherVector defines the second operand
  2991. * @returns the new Vector3
  2992. */
  2993. Vector3.prototype.divide = function (otherVector) {
  2994. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2995. };
  2996. /**
  2997. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2998. * @param otherVector defines the second operand
  2999. * @param result defines the Vector3 object where to store the result
  3000. * @returns the current Vector3
  3001. */
  3002. Vector3.prototype.divideToRef = function (otherVector, result) {
  3003. result.x = this.x / otherVector.x;
  3004. result.y = this.y / otherVector.y;
  3005. result.z = this.z / otherVector.z;
  3006. return this;
  3007. };
  3008. /**
  3009. * Divides the current Vector3 coordinates by the passed ones.
  3010. * @param otherVector defines the second operand
  3011. * @returns the current updated Vector3
  3012. */
  3013. Vector3.prototype.divideInPlace = function (otherVector) {
  3014. return this.divideToRef(otherVector, this);
  3015. };
  3016. /**
  3017. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  3018. * @param other defines the second operand
  3019. * @returns the current updated Vector3
  3020. */
  3021. Vector3.prototype.minimizeInPlace = function (other) {
  3022. if (other.x < this.x)
  3023. this.x = other.x;
  3024. if (other.y < this.y)
  3025. this.y = other.y;
  3026. if (other.z < this.z)
  3027. this.z = other.z;
  3028. return this;
  3029. };
  3030. /**
  3031. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  3032. * @param other defines the second operand
  3033. * @returns the current updated Vector3
  3034. */
  3035. Vector3.prototype.maximizeInPlace = function (other) {
  3036. if (other.x > this.x)
  3037. this.x = other.x;
  3038. if (other.y > this.y)
  3039. this.y = other.y;
  3040. if (other.z > this.z)
  3041. this.z = other.z;
  3042. return this;
  3043. };
  3044. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3045. /**
  3046. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3047. */
  3048. get: function () {
  3049. var absX = Math.abs(this.x);
  3050. var absY = Math.abs(this.y);
  3051. if (absX !== absY) {
  3052. return true;
  3053. }
  3054. var absZ = Math.abs(this.z);
  3055. if (absX !== absZ) {
  3056. return true;
  3057. }
  3058. if (absY !== absZ) {
  3059. return true;
  3060. }
  3061. return false;
  3062. },
  3063. enumerable: true,
  3064. configurable: true
  3065. });
  3066. // Properties
  3067. /**
  3068. * Gets the length of the Vector3
  3069. * @returns the length of the Vecto3
  3070. */
  3071. Vector3.prototype.length = function () {
  3072. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3073. };
  3074. /**
  3075. * Gets the squared length of the Vector3
  3076. * @returns squared length of the Vector3
  3077. */
  3078. Vector3.prototype.lengthSquared = function () {
  3079. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3080. };
  3081. /**
  3082. * Normalize the current Vector3.
  3083. * Please note that this is an in place operation.
  3084. * @returns the current updated Vector3
  3085. */
  3086. Vector3.prototype.normalize = function () {
  3087. var len = this.length();
  3088. if (len === 0 || len === 1.0)
  3089. return this;
  3090. var num = 1.0 / len;
  3091. this.x *= num;
  3092. this.y *= num;
  3093. this.z *= num;
  3094. return this;
  3095. };
  3096. /**
  3097. * Normalize the current Vector3 to a new vector
  3098. * @returns the new Vector3
  3099. */
  3100. Vector3.prototype.normalizeToNew = function () {
  3101. var normalized = new Vector3(0, 0, 0);
  3102. this.normalizeToRef(normalized);
  3103. return normalized;
  3104. };
  3105. /**
  3106. * Normalize the current Vector3 to the reference
  3107. * @param reference define the Vector3 to update
  3108. * @returns the updated Vector3
  3109. */
  3110. Vector3.prototype.normalizeToRef = function (reference) {
  3111. var len = this.length();
  3112. if (len === 0 || len === 1.0) {
  3113. reference.set(this.x, this.y, this.z);
  3114. return reference;
  3115. }
  3116. var scale = 1.0 / len;
  3117. this.scaleToRef(scale, reference);
  3118. return reference;
  3119. };
  3120. /**
  3121. * Creates a new Vector3 copied from the current Vector3
  3122. * @returns the new Vector3
  3123. */
  3124. Vector3.prototype.clone = function () {
  3125. return new Vector3(this.x, this.y, this.z);
  3126. };
  3127. /**
  3128. * Copies the passed vector coordinates to the current Vector3 ones
  3129. * @param source defines the source Vector3
  3130. * @returns the current updated Vector3
  3131. */
  3132. Vector3.prototype.copyFrom = function (source) {
  3133. this.x = source.x;
  3134. this.y = source.y;
  3135. this.z = source.z;
  3136. return this;
  3137. };
  3138. /**
  3139. * Copies the passed floats to the current Vector3 coordinates
  3140. * @param x defines the x coordinate of the operand
  3141. * @param y defines the y coordinate of the operand
  3142. * @param z defines the z coordinate of the operand
  3143. * @returns the current updated Vector3
  3144. */
  3145. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3146. this.x = x;
  3147. this.y = y;
  3148. this.z = z;
  3149. return this;
  3150. };
  3151. /**
  3152. * Copies the passed floats to the current Vector3 coordinates
  3153. * @param x defines the x coordinate of the operand
  3154. * @param y defines the y coordinate of the operand
  3155. * @param z defines the z coordinate of the operand
  3156. * @returns the current updated Vector3
  3157. */
  3158. Vector3.prototype.set = function (x, y, z) {
  3159. return this.copyFromFloats(x, y, z);
  3160. };
  3161. // Statics
  3162. /**
  3163. * Get the clip factor between two vectors
  3164. * @param vector0 defines the first operand
  3165. * @param vector1 defines the second operand
  3166. * @param axis defines the axis to use
  3167. * @param size defines the size along the axis
  3168. * @returns the clip factor
  3169. */
  3170. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3171. var d0 = Vector3.Dot(vector0, axis) - size;
  3172. var d1 = Vector3.Dot(vector1, axis) - size;
  3173. var s = d0 / (d0 - d1);
  3174. return s;
  3175. };
  3176. /**
  3177. * Get angle between two vectors
  3178. * @param vector0 angle between vector0 and vector1
  3179. * @param vector1 angle between vector0 and vector1
  3180. * @param normal direction of the normal
  3181. * @return the angle between vector0 and vector1
  3182. */
  3183. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3184. var v0 = vector0.clone().normalize();
  3185. var v1 = vector1.clone().normalize();
  3186. var dot = Vector3.Dot(v0, v1);
  3187. var n = Vector3.Cross(v0, v1);
  3188. if (Vector3.Dot(n, normal) > 0) {
  3189. return Math.acos(dot);
  3190. }
  3191. return -Math.acos(dot);
  3192. };
  3193. /**
  3194. * Returns a new Vector3 set from the index "offset" of the passed array
  3195. * @param array defines the source array
  3196. * @param offset defines the offset in the source array
  3197. * @returns the new Vector3
  3198. */
  3199. Vector3.FromArray = function (array, offset) {
  3200. if (!offset) {
  3201. offset = 0;
  3202. }
  3203. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3204. };
  3205. /**
  3206. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3207. * This function is deprecated. Use FromArray instead
  3208. * @param array defines the source array
  3209. * @param offset defines the offset in the source array
  3210. * @returns the new Vector3
  3211. */
  3212. Vector3.FromFloatArray = function (array, offset) {
  3213. return Vector3.FromArray(array, offset);
  3214. };
  3215. /**
  3216. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3217. * @param array defines the source array
  3218. * @param offset defines the offset in the source array
  3219. * @param result defines the Vector3 where to store the result
  3220. */
  3221. Vector3.FromArrayToRef = function (array, offset, result) {
  3222. result.x = array[offset];
  3223. result.y = array[offset + 1];
  3224. result.z = array[offset + 2];
  3225. };
  3226. /**
  3227. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3228. * This function is deprecated. Use FromArrayToRef instead.
  3229. * @param array defines the source array
  3230. * @param offset defines the offset in the source array
  3231. * @param result defines the Vector3 where to store the result
  3232. */
  3233. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3234. return Vector3.FromArrayToRef(array, offset, result);
  3235. };
  3236. /**
  3237. * Sets the passed vector "result" with the passed floats.
  3238. * @param x defines the x coordinate of the source
  3239. * @param y defines the y coordinate of the source
  3240. * @param z defines the z coordinate of the source
  3241. * @param result defines the Vector3 where to store the result
  3242. */
  3243. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3244. result.x = x;
  3245. result.y = y;
  3246. result.z = z;
  3247. };
  3248. /**
  3249. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3250. * @returns a new empty Vector3
  3251. */
  3252. Vector3.Zero = function () {
  3253. return new Vector3(0.0, 0.0, 0.0);
  3254. };
  3255. /**
  3256. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3257. * @returns a new unit Vector3
  3258. */
  3259. Vector3.One = function () {
  3260. return new Vector3(1.0, 1.0, 1.0);
  3261. };
  3262. /**
  3263. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3264. * @returns a new up Vector3
  3265. */
  3266. Vector3.Up = function () {
  3267. return new Vector3(0.0, 1.0, 0.0);
  3268. };
  3269. /**
  3270. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3271. * @returns a new forward Vector3
  3272. */
  3273. Vector3.Forward = function () {
  3274. return new Vector3(0.0, 0.0, 1.0);
  3275. };
  3276. /**
  3277. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3278. * @returns a new right Vector3
  3279. */
  3280. Vector3.Right = function () {
  3281. return new Vector3(1.0, 0.0, 0.0);
  3282. };
  3283. /**
  3284. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3285. * @returns a new left Vector3
  3286. */
  3287. Vector3.Left = function () {
  3288. return new Vector3(-1.0, 0.0, 0.0);
  3289. };
  3290. /**
  3291. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3292. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3293. * @param vector defines the Vector3 to transform
  3294. * @param transformation defines the transformation matrix
  3295. * @returns the transformed Vector3
  3296. */
  3297. Vector3.TransformCoordinates = function (vector, transformation) {
  3298. var result = Vector3.Zero();
  3299. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3300. return result;
  3301. };
  3302. /**
  3303. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3304. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3305. * @param vector defines the Vector3 to transform
  3306. * @param transformation defines the transformation matrix
  3307. * @param result defines the Vector3 where to store the result
  3308. */
  3309. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3310. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3311. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3312. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3313. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3314. result.x = x / w;
  3315. result.y = y / w;
  3316. result.z = z / w;
  3317. };
  3318. /**
  3319. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3320. * This method computes tranformed coordinates only, not transformed direction vectors
  3321. * @param x define the x coordinate of the source vector
  3322. * @param y define the y coordinate of the source vector
  3323. * @param z define the z coordinate of the source vector
  3324. * @param transformation defines the transformation matrix
  3325. * @param result defines the Vector3 where to store the result
  3326. */
  3327. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3328. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3329. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3330. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3331. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3332. result.x = rx / rw;
  3333. result.y = ry / rw;
  3334. result.z = rz / rw;
  3335. };
  3336. /**
  3337. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3338. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3339. * @param vector defines the Vector3 to transform
  3340. * @param transformation defines the transformation matrix
  3341. * @returns the new Vector3
  3342. */
  3343. Vector3.TransformNormal = function (vector, transformation) {
  3344. var result = Vector3.Zero();
  3345. Vector3.TransformNormalToRef(vector, transformation, result);
  3346. return result;
  3347. };
  3348. /**
  3349. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3350. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3351. * @param vector defines the Vector3 to transform
  3352. * @param transformation defines the transformation matrix
  3353. * @param result defines the Vector3 where to store the result
  3354. */
  3355. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3356. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3357. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3358. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3359. result.x = x;
  3360. result.y = y;
  3361. result.z = z;
  3362. };
  3363. /**
  3364. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3365. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3366. * @param x define the x coordinate of the source vector
  3367. * @param y define the y coordinate of the source vector
  3368. * @param z define the z coordinate of the source vector
  3369. * @param transformation defines the transformation matrix
  3370. * @param result defines the Vector3 where to store the result
  3371. */
  3372. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3373. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3374. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3375. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3376. };
  3377. /**
  3378. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3379. * @param value1 defines the first control point
  3380. * @param value2 defines the second control point
  3381. * @param value3 defines the third control point
  3382. * @param value4 defines the fourth control point
  3383. * @param amount defines the amount on the spline to use
  3384. * @returns the new Vector3
  3385. */
  3386. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3387. var squared = amount * amount;
  3388. var cubed = amount * squared;
  3389. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3390. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3391. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3392. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3393. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3394. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3395. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3396. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3397. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3398. return new Vector3(x, y, z);
  3399. };
  3400. /**
  3401. * 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"
  3402. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3403. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3404. * @param value defines the current value
  3405. * @param min defines the lower range value
  3406. * @param max defines the upper range value
  3407. * @returns the new Vector3
  3408. */
  3409. Vector3.Clamp = function (value, min, max) {
  3410. var x = value.x;
  3411. x = (x > max.x) ? max.x : x;
  3412. x = (x < min.x) ? min.x : x;
  3413. var y = value.y;
  3414. y = (y > max.y) ? max.y : y;
  3415. y = (y < min.y) ? min.y : y;
  3416. var z = value.z;
  3417. z = (z > max.z) ? max.z : z;
  3418. z = (z < min.z) ? min.z : z;
  3419. return new Vector3(x, y, z);
  3420. };
  3421. /**
  3422. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3423. * @param value1 defines the first control point
  3424. * @param tangent1 defines the first tangent vector
  3425. * @param value2 defines the second control point
  3426. * @param tangent2 defines the second tangent vector
  3427. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3428. * @returns the new Vector3
  3429. */
  3430. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3431. var squared = amount * amount;
  3432. var cubed = amount * squared;
  3433. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3434. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3435. var part3 = (cubed - (2.0 * squared)) + amount;
  3436. var part4 = cubed - squared;
  3437. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3438. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3439. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3440. return new Vector3(x, y, z);
  3441. };
  3442. /**
  3443. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3444. * @param start defines the start value
  3445. * @param end defines the end value
  3446. * @param amount max defines amount between both (between 0 and 1)
  3447. * @returns the new Vector3
  3448. */
  3449. Vector3.Lerp = function (start, end, amount) {
  3450. var result = new Vector3(0, 0, 0);
  3451. Vector3.LerpToRef(start, end, amount, result);
  3452. return result;
  3453. };
  3454. /**
  3455. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3456. * @param start defines the start value
  3457. * @param end defines the end value
  3458. * @param amount max defines amount between both (between 0 and 1)
  3459. * @param result defines the Vector3 where to store the result
  3460. */
  3461. Vector3.LerpToRef = function (start, end, amount, result) {
  3462. result.x = start.x + ((end.x - start.x) * amount);
  3463. result.y = start.y + ((end.y - start.y) * amount);
  3464. result.z = start.z + ((end.z - start.z) * amount);
  3465. };
  3466. /**
  3467. * Returns the dot product (float) between the vectors "left" and "right"
  3468. * @param left defines the left operand
  3469. * @param right defines the right operand
  3470. * @returns the dot product
  3471. */
  3472. Vector3.Dot = function (left, right) {
  3473. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3474. };
  3475. /**
  3476. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3477. * The cross product is then orthogonal to both "left" and "right"
  3478. * @param left defines the left operand
  3479. * @param right defines the right operand
  3480. * @returns the cross product
  3481. */
  3482. Vector3.Cross = function (left, right) {
  3483. var result = Vector3.Zero();
  3484. Vector3.CrossToRef(left, right, result);
  3485. return result;
  3486. };
  3487. /**
  3488. * Sets the passed vector "result" with the cross product of "left" and "right"
  3489. * The cross product is then orthogonal to both "left" and "right"
  3490. * @param left defines the left operand
  3491. * @param right defines the right operand
  3492. * @param result defines the Vector3 where to store the result
  3493. */
  3494. Vector3.CrossToRef = function (left, right, result) {
  3495. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3496. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3497. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3498. result.copyFrom(MathTmp.Vector3[0]);
  3499. };
  3500. /**
  3501. * Returns a new Vector3 as the normalization of the passed vector
  3502. * @param vector defines the Vector3 to normalize
  3503. * @returns the new Vector3
  3504. */
  3505. Vector3.Normalize = function (vector) {
  3506. var result = Vector3.Zero();
  3507. Vector3.NormalizeToRef(vector, result);
  3508. return result;
  3509. };
  3510. /**
  3511. * Sets the passed vector "result" with the normalization of the passed first vector
  3512. * @param vector defines the Vector3 to normalize
  3513. * @param result defines the Vector3 where to store the result
  3514. */
  3515. Vector3.NormalizeToRef = function (vector, result) {
  3516. result.copyFrom(vector);
  3517. result.normalize();
  3518. };
  3519. /**
  3520. * Project a Vector3 onto screen space
  3521. * @param vector defines the Vector3 to project
  3522. * @param world defines the world matrix to use
  3523. * @param transform defines the transform (view x projection) matrix to use
  3524. * @param viewport defines the screen viewport to use
  3525. * @returns the new Vector3
  3526. */
  3527. Vector3.Project = function (vector, world, transform, viewport) {
  3528. var cw = viewport.width;
  3529. var ch = viewport.height;
  3530. var cx = viewport.x;
  3531. var cy = viewport.y;
  3532. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3533. 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);
  3534. var matrix = MathTmp.Matrix[0];
  3535. world.multiplyToRef(transform, matrix);
  3536. matrix.multiplyToRef(viewportMatrix, matrix);
  3537. return Vector3.TransformCoordinates(vector, matrix);
  3538. };
  3539. /**
  3540. * Unproject from screen space to object space
  3541. * @param source defines the screen space Vector3 to use
  3542. * @param viewportWidth defines the current width of the viewport
  3543. * @param viewportHeight defines the current height of the viewport
  3544. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3545. * @param transform defines the transform (view x projection) matrix to use
  3546. * @returns the new Vector3
  3547. */
  3548. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3549. var matrix = MathTmp.Matrix[0];
  3550. world.multiplyToRef(transform, matrix);
  3551. matrix.invert();
  3552. source.x = source.x / viewportWidth * 2 - 1;
  3553. source.y = -(source.y / viewportHeight * 2 - 1);
  3554. var vector = Vector3.TransformCoordinates(source, matrix);
  3555. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3556. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3557. vector = vector.scale(1.0 / num);
  3558. }
  3559. return vector;
  3560. };
  3561. /**
  3562. * Unproject from screen space to object space
  3563. * @param source defines the screen space Vector3 to use
  3564. * @param viewportWidth defines the current width of the viewport
  3565. * @param viewportHeight defines the current height of the viewport
  3566. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3567. * @param view defines the view matrix to use
  3568. * @param projection defines the projection matrix to use
  3569. * @returns the new Vector3
  3570. */
  3571. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3572. var result = Vector3.Zero();
  3573. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3574. return result;
  3575. };
  3576. /**
  3577. * Unproject from screen space to object space
  3578. * @param source defines the screen space Vector3 to use
  3579. * @param viewportWidth defines the current width of the viewport
  3580. * @param viewportHeight defines the current height of the viewport
  3581. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3582. * @param view defines the view matrix to use
  3583. * @param projection defines the projection matrix to use
  3584. * @param result defines the Vector3 where to store the result
  3585. */
  3586. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3587. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3588. };
  3589. /**
  3590. * Unproject from screen space to object space
  3591. * @param sourceX defines the screen space x coordinate to use
  3592. * @param sourceY defines the screen space y coordinate to use
  3593. * @param sourceZ defines the screen space z coordinate to use
  3594. * @param viewportWidth defines the current width of the viewport
  3595. * @param viewportHeight defines the current height of the viewport
  3596. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3597. * @param view defines the view matrix to use
  3598. * @param projection defines the projection matrix to use
  3599. * @param result defines the Vector3 where to store the result
  3600. */
  3601. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3602. var matrix = MathTmp.Matrix[0];
  3603. world.multiplyToRef(view, matrix);
  3604. matrix.multiplyToRef(projection, matrix);
  3605. matrix.invert();
  3606. var screenSource = MathTmp.Vector3[0];
  3607. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3608. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3609. screenSource.z = 2 * sourceZ - 1.0;
  3610. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3611. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3612. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3613. result.scaleInPlace(1.0 / num);
  3614. }
  3615. };
  3616. /**
  3617. * Gets the minimal coordinate values between two Vector3
  3618. * @param left defines the first operand
  3619. * @param right defines the second operand
  3620. * @returns the new Vector3
  3621. */
  3622. Vector3.Minimize = function (left, right) {
  3623. var min = left.clone();
  3624. min.minimizeInPlace(right);
  3625. return min;
  3626. };
  3627. /**
  3628. * Gets the maximal coordinate values between two Vector3
  3629. * @param left defines the first operand
  3630. * @param right defines the second operand
  3631. * @returns the new Vector3
  3632. */
  3633. Vector3.Maximize = function (left, right) {
  3634. var max = left.clone();
  3635. max.maximizeInPlace(right);
  3636. return max;
  3637. };
  3638. /**
  3639. * Returns the distance between the vectors "value1" and "value2"
  3640. * @param value1 defines the first operand
  3641. * @param value2 defines the second operand
  3642. * @returns the distance
  3643. */
  3644. Vector3.Distance = function (value1, value2) {
  3645. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3646. };
  3647. /**
  3648. * Returns the squared distance between the vectors "value1" and "value2"
  3649. * @param value1 defines the first operand
  3650. * @param value2 defines the second operand
  3651. * @returns the squared distance
  3652. */
  3653. Vector3.DistanceSquared = function (value1, value2) {
  3654. var x = value1.x - value2.x;
  3655. var y = value1.y - value2.y;
  3656. var z = value1.z - value2.z;
  3657. return (x * x) + (y * y) + (z * z);
  3658. };
  3659. /**
  3660. * Returns a new Vector3 located at the center between "value1" and "value2"
  3661. * @param value1 defines the first operand
  3662. * @param value2 defines the second operand
  3663. * @returns the new Vector3
  3664. */
  3665. Vector3.Center = function (value1, value2) {
  3666. var center = value1.add(value2);
  3667. center.scaleInPlace(0.5);
  3668. return center;
  3669. };
  3670. /**
  3671. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3672. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3673. * to something in order to rotate it from its local system to the given target system
  3674. * Note: axis1, axis2 and axis3 are normalized during this operation
  3675. * @param axis1 defines the first axis
  3676. * @param axis2 defines the second axis
  3677. * @param axis3 defines the third axis
  3678. * @returns a new Vector3
  3679. */
  3680. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3681. var rotation = Vector3.Zero();
  3682. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3683. return rotation;
  3684. };
  3685. /**
  3686. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3687. * @param axis1 defines the first axis
  3688. * @param axis2 defines the second axis
  3689. * @param axis3 defines the third axis
  3690. * @param ref defines the Vector3 where to store the result
  3691. */
  3692. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3693. var quat = MathTmp.Quaternion[0];
  3694. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3695. quat.toEulerAnglesToRef(ref);
  3696. };
  3697. return Vector3;
  3698. }());
  3699. BABYLON.Vector3 = Vector3;
  3700. //Vector4 class created for EulerAngle class conversion to Quaternion
  3701. var Vector4 = /** @class */ (function () {
  3702. /**
  3703. * Creates a Vector4 object from the passed floats.
  3704. */
  3705. function Vector4(x, y, z, w) {
  3706. this.x = x;
  3707. this.y = y;
  3708. this.z = z;
  3709. this.w = w;
  3710. }
  3711. /**
  3712. * Returns the string with the Vector4 coordinates.
  3713. */
  3714. Vector4.prototype.toString = function () {
  3715. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3716. };
  3717. /**
  3718. * Returns the string "Vector4".
  3719. */
  3720. Vector4.prototype.getClassName = function () {
  3721. return "Vector4";
  3722. };
  3723. /**
  3724. * Returns the Vector4 hash code.
  3725. */
  3726. Vector4.prototype.getHashCode = function () {
  3727. var hash = this.x || 0;
  3728. hash = (hash * 397) ^ (this.y || 0);
  3729. hash = (hash * 397) ^ (this.z || 0);
  3730. hash = (hash * 397) ^ (this.w || 0);
  3731. return hash;
  3732. };
  3733. // Operators
  3734. /**
  3735. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3736. */
  3737. Vector4.prototype.asArray = function () {
  3738. var result = new Array();
  3739. this.toArray(result, 0);
  3740. return result;
  3741. };
  3742. /**
  3743. * Populates the passed array from the passed index with the Vector4 coordinates.
  3744. * Returns the Vector4.
  3745. */
  3746. Vector4.prototype.toArray = function (array, index) {
  3747. if (index === undefined) {
  3748. index = 0;
  3749. }
  3750. array[index] = this.x;
  3751. array[index + 1] = this.y;
  3752. array[index + 2] = this.z;
  3753. array[index + 3] = this.w;
  3754. return this;
  3755. };
  3756. /**
  3757. * Adds the passed vector to the current Vector4.
  3758. * Returns the updated Vector4.
  3759. */
  3760. Vector4.prototype.addInPlace = function (otherVector) {
  3761. this.x += otherVector.x;
  3762. this.y += otherVector.y;
  3763. this.z += otherVector.z;
  3764. this.w += otherVector.w;
  3765. return this;
  3766. };
  3767. /**
  3768. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3769. */
  3770. Vector4.prototype.add = function (otherVector) {
  3771. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3772. };
  3773. /**
  3774. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3775. * Returns the current Vector4.
  3776. */
  3777. Vector4.prototype.addToRef = function (otherVector, result) {
  3778. result.x = this.x + otherVector.x;
  3779. result.y = this.y + otherVector.y;
  3780. result.z = this.z + otherVector.z;
  3781. result.w = this.w + otherVector.w;
  3782. return this;
  3783. };
  3784. /**
  3785. * Subtract in place the passed vector from the current Vector4.
  3786. * Returns the updated Vector4.
  3787. */
  3788. Vector4.prototype.subtractInPlace = function (otherVector) {
  3789. this.x -= otherVector.x;
  3790. this.y -= otherVector.y;
  3791. this.z -= otherVector.z;
  3792. this.w -= otherVector.w;
  3793. return this;
  3794. };
  3795. /**
  3796. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3797. */
  3798. Vector4.prototype.subtract = function (otherVector) {
  3799. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3800. };
  3801. /**
  3802. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3803. * Returns the current Vector4.
  3804. */
  3805. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3806. result.x = this.x - otherVector.x;
  3807. result.y = this.y - otherVector.y;
  3808. result.z = this.z - otherVector.z;
  3809. result.w = this.w - otherVector.w;
  3810. return this;
  3811. };
  3812. /**
  3813. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3814. */
  3815. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3816. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3817. };
  3818. /**
  3819. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3820. * Returns the current Vector4.
  3821. */
  3822. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3823. result.x = this.x - x;
  3824. result.y = this.y - y;
  3825. result.z = this.z - z;
  3826. result.w = this.w - w;
  3827. return this;
  3828. };
  3829. /**
  3830. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3831. */
  3832. Vector4.prototype.negate = function () {
  3833. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3834. };
  3835. /**
  3836. * Multiplies the current Vector4 coordinates by scale (float).
  3837. * Returns the updated Vector4.
  3838. */
  3839. Vector4.prototype.scaleInPlace = function (scale) {
  3840. this.x *= scale;
  3841. this.y *= scale;
  3842. this.z *= scale;
  3843. this.w *= scale;
  3844. return this;
  3845. };
  3846. /**
  3847. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3848. */
  3849. Vector4.prototype.scale = function (scale) {
  3850. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3851. };
  3852. /**
  3853. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3854. * Returns the current Vector4.
  3855. */
  3856. Vector4.prototype.scaleToRef = function (scale, result) {
  3857. result.x = this.x * scale;
  3858. result.y = this.y * scale;
  3859. result.z = this.z * scale;
  3860. result.w = this.w * scale;
  3861. return this;
  3862. };
  3863. /**
  3864. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3865. */
  3866. Vector4.prototype.equals = function (otherVector) {
  3867. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3868. };
  3869. /**
  3870. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3871. */
  3872. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3873. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3874. return otherVector
  3875. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3876. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3877. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3878. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3879. };
  3880. /**
  3881. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3882. */
  3883. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3884. return this.x === x && this.y === y && this.z === z && this.w === w;
  3885. };
  3886. /**
  3887. * Multiplies in place the current Vector4 by the passed one.
  3888. * Returns the updated Vector4.
  3889. */
  3890. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3891. this.x *= otherVector.x;
  3892. this.y *= otherVector.y;
  3893. this.z *= otherVector.z;
  3894. this.w *= otherVector.w;
  3895. return this;
  3896. };
  3897. /**
  3898. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3899. */
  3900. Vector4.prototype.multiply = function (otherVector) {
  3901. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3902. };
  3903. /**
  3904. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3905. * Returns the current Vector4.
  3906. */
  3907. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3908. result.x = this.x * otherVector.x;
  3909. result.y = this.y * otherVector.y;
  3910. result.z = this.z * otherVector.z;
  3911. result.w = this.w * otherVector.w;
  3912. return this;
  3913. };
  3914. /**
  3915. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3916. */
  3917. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3918. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3919. };
  3920. /**
  3921. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3922. */
  3923. Vector4.prototype.divide = function (otherVector) {
  3924. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3925. };
  3926. /**
  3927. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3928. * Returns the current Vector4.
  3929. */
  3930. Vector4.prototype.divideToRef = function (otherVector, result) {
  3931. result.x = this.x / otherVector.x;
  3932. result.y = this.y / otherVector.y;
  3933. result.z = this.z / otherVector.z;
  3934. result.w = this.w / otherVector.w;
  3935. return this;
  3936. };
  3937. /**
  3938. * Divides the current Vector3 coordinates by the passed ones.
  3939. * @returns the updated Vector3.
  3940. */
  3941. Vector4.prototype.divideInPlace = function (otherVector) {
  3942. return this.divideToRef(otherVector, this);
  3943. };
  3944. /**
  3945. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3946. * @param other defines the second operand
  3947. * @returns the current updated Vector4
  3948. */
  3949. Vector4.prototype.minimizeInPlace = function (other) {
  3950. if (other.x < this.x)
  3951. this.x = other.x;
  3952. if (other.y < this.y)
  3953. this.y = other.y;
  3954. if (other.z < this.z)
  3955. this.z = other.z;
  3956. if (other.w < this.w)
  3957. this.w = other.w;
  3958. return this;
  3959. };
  3960. /**
  3961. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3962. * @param other defines the second operand
  3963. * @returns the current updated Vector4
  3964. */
  3965. Vector4.prototype.maximizeInPlace = function (other) {
  3966. if (other.x > this.x)
  3967. this.x = other.x;
  3968. if (other.y > this.y)
  3969. this.y = other.y;
  3970. if (other.z > this.z)
  3971. this.z = other.z;
  3972. if (other.w > this.w)
  3973. this.w = other.w;
  3974. return this;
  3975. };
  3976. // Properties
  3977. /**
  3978. * Returns the Vector4 length (float).
  3979. */
  3980. Vector4.prototype.length = function () {
  3981. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3982. };
  3983. /**
  3984. * Returns the Vector4 squared length (float).
  3985. */
  3986. Vector4.prototype.lengthSquared = function () {
  3987. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3988. };
  3989. // Methods
  3990. /**
  3991. * Normalizes in place the Vector4.
  3992. * Returns the updated Vector4.
  3993. */
  3994. Vector4.prototype.normalize = function () {
  3995. var len = this.length();
  3996. if (len === 0)
  3997. return this;
  3998. var num = 1.0 / len;
  3999. this.x *= num;
  4000. this.y *= num;
  4001. this.z *= num;
  4002. this.w *= num;
  4003. return this;
  4004. };
  4005. /**
  4006. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4007. */
  4008. Vector4.prototype.toVector3 = function () {
  4009. return new Vector3(this.x, this.y, this.z);
  4010. };
  4011. /**
  4012. * Returns a new Vector4 copied from the current one.
  4013. */
  4014. Vector4.prototype.clone = function () {
  4015. return new Vector4(this.x, this.y, this.z, this.w);
  4016. };
  4017. /**
  4018. * Updates the current Vector4 with the passed one coordinates.
  4019. * Returns the updated Vector4.
  4020. */
  4021. Vector4.prototype.copyFrom = function (source) {
  4022. this.x = source.x;
  4023. this.y = source.y;
  4024. this.z = source.z;
  4025. this.w = source.w;
  4026. return this;
  4027. };
  4028. /**
  4029. * Updates the current Vector4 coordinates with the passed floats.
  4030. * Returns the updated Vector4.
  4031. */
  4032. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4033. this.x = x;
  4034. this.y = y;
  4035. this.z = z;
  4036. this.w = w;
  4037. return this;
  4038. };
  4039. /**
  4040. * Updates the current Vector4 coordinates with the passed floats.
  4041. * Returns the updated Vector4.
  4042. */
  4043. Vector4.prototype.set = function (x, y, z, w) {
  4044. return this.copyFromFloats(x, y, z, w);
  4045. };
  4046. // Statics
  4047. /**
  4048. * Returns a new Vector4 set from the starting index of the passed array.
  4049. */
  4050. Vector4.FromArray = function (array, offset) {
  4051. if (!offset) {
  4052. offset = 0;
  4053. }
  4054. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4055. };
  4056. /**
  4057. * Updates the passed vector "result" from the starting index of the passed array.
  4058. */
  4059. Vector4.FromArrayToRef = function (array, offset, result) {
  4060. result.x = array[offset];
  4061. result.y = array[offset + 1];
  4062. result.z = array[offset + 2];
  4063. result.w = array[offset + 3];
  4064. };
  4065. /**
  4066. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4067. */
  4068. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4069. Vector4.FromArrayToRef(array, offset, result);
  4070. };
  4071. /**
  4072. * Updates the passed vector "result" coordinates from the passed floats.
  4073. */
  4074. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4075. result.x = x;
  4076. result.y = y;
  4077. result.z = z;
  4078. result.w = w;
  4079. };
  4080. /**
  4081. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4082. */
  4083. Vector4.Zero = function () {
  4084. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4085. };
  4086. /**
  4087. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4088. */
  4089. Vector4.One = function () {
  4090. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4091. };
  4092. /**
  4093. * Returns a new normalized Vector4 from the passed one.
  4094. */
  4095. Vector4.Normalize = function (vector) {
  4096. var result = Vector4.Zero();
  4097. Vector4.NormalizeToRef(vector, result);
  4098. return result;
  4099. };
  4100. /**
  4101. * Updates the passed vector "result" from the normalization of the passed one.
  4102. */
  4103. Vector4.NormalizeToRef = function (vector, result) {
  4104. result.copyFrom(vector);
  4105. result.normalize();
  4106. };
  4107. Vector4.Minimize = function (left, right) {
  4108. var min = left.clone();
  4109. min.minimizeInPlace(right);
  4110. return min;
  4111. };
  4112. Vector4.Maximize = function (left, right) {
  4113. var max = left.clone();
  4114. max.maximizeInPlace(right);
  4115. return max;
  4116. };
  4117. /**
  4118. * Returns the distance (float) between the vectors "value1" and "value2".
  4119. */
  4120. Vector4.Distance = function (value1, value2) {
  4121. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4122. };
  4123. /**
  4124. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4125. */
  4126. Vector4.DistanceSquared = function (value1, value2) {
  4127. var x = value1.x - value2.x;
  4128. var y = value1.y - value2.y;
  4129. var z = value1.z - value2.z;
  4130. var w = value1.w - value2.w;
  4131. return (x * x) + (y * y) + (z * z) + (w * w);
  4132. };
  4133. /**
  4134. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4135. */
  4136. Vector4.Center = function (value1, value2) {
  4137. var center = value1.add(value2);
  4138. center.scaleInPlace(0.5);
  4139. return center;
  4140. };
  4141. /**
  4142. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4143. * This methods computes transformed normalized direction vectors only.
  4144. */
  4145. Vector4.TransformNormal = function (vector, transformation) {
  4146. var result = Vector4.Zero();
  4147. Vector4.TransformNormalToRef(vector, transformation, result);
  4148. return result;
  4149. };
  4150. /**
  4151. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4152. * This methods computes transformed normalized direction vectors only.
  4153. */
  4154. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4155. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4156. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4157. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4158. result.x = x;
  4159. result.y = y;
  4160. result.z = z;
  4161. result.w = vector.w;
  4162. };
  4163. /**
  4164. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4165. * This methods computes transformed normalized direction vectors only.
  4166. */
  4167. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4168. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4169. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4170. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4171. result.w = w;
  4172. };
  4173. return Vector4;
  4174. }());
  4175. BABYLON.Vector4 = Vector4;
  4176. var Size = /** @class */ (function () {
  4177. /**
  4178. * Creates a Size object from the passed width and height (floats).
  4179. */
  4180. function Size(width, height) {
  4181. this.width = width;
  4182. this.height = height;
  4183. }
  4184. // Returns a string with the Size width and height.
  4185. Size.prototype.toString = function () {
  4186. return "{W: " + this.width + ", H: " + this.height + "}";
  4187. };
  4188. /**
  4189. * Returns the string "Size"
  4190. */
  4191. Size.prototype.getClassName = function () {
  4192. return "Size";
  4193. };
  4194. /**
  4195. * Returns the Size hash code.
  4196. */
  4197. Size.prototype.getHashCode = function () {
  4198. var hash = this.width || 0;
  4199. hash = (hash * 397) ^ (this.height || 0);
  4200. return hash;
  4201. };
  4202. /**
  4203. * Updates the current size from the passed one.
  4204. * Returns the updated Size.
  4205. */
  4206. Size.prototype.copyFrom = function (src) {
  4207. this.width = src.width;
  4208. this.height = src.height;
  4209. };
  4210. /**
  4211. * Updates in place the current Size from the passed floats.
  4212. * Returns the updated Size.
  4213. */
  4214. Size.prototype.copyFromFloats = function (width, height) {
  4215. this.width = width;
  4216. this.height = height;
  4217. return this;
  4218. };
  4219. /**
  4220. * Updates in place the current Size from the passed floats.
  4221. * Returns the updated Size.
  4222. */
  4223. Size.prototype.set = function (width, height) {
  4224. return this.copyFromFloats(width, height);
  4225. };
  4226. /**
  4227. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4228. */
  4229. Size.prototype.multiplyByFloats = function (w, h) {
  4230. return new Size(this.width * w, this.height * h);
  4231. };
  4232. /**
  4233. * Returns a new Size copied from the passed one.
  4234. */
  4235. Size.prototype.clone = function () {
  4236. return new Size(this.width, this.height);
  4237. };
  4238. /**
  4239. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4240. */
  4241. Size.prototype.equals = function (other) {
  4242. if (!other) {
  4243. return false;
  4244. }
  4245. return (this.width === other.width) && (this.height === other.height);
  4246. };
  4247. Object.defineProperty(Size.prototype, "surface", {
  4248. /**
  4249. * Returns the surface of the Size : width * height (float).
  4250. */
  4251. get: function () {
  4252. return this.width * this.height;
  4253. },
  4254. enumerable: true,
  4255. configurable: true
  4256. });
  4257. /**
  4258. * Returns a new Size set to (0.0, 0.0)
  4259. */
  4260. Size.Zero = function () {
  4261. return new Size(0.0, 0.0);
  4262. };
  4263. /**
  4264. * Returns a new Size set as the addition result of the current Size and the passed one.
  4265. */
  4266. Size.prototype.add = function (otherSize) {
  4267. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4268. return r;
  4269. };
  4270. /**
  4271. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4272. */
  4273. Size.prototype.subtract = function (otherSize) {
  4274. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4275. return r;
  4276. };
  4277. /**
  4278. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4279. */
  4280. Size.Lerp = function (start, end, amount) {
  4281. var w = start.width + ((end.width - start.width) * amount);
  4282. var h = start.height + ((end.height - start.height) * amount);
  4283. return new Size(w, h);
  4284. };
  4285. return Size;
  4286. }());
  4287. BABYLON.Size = Size;
  4288. var Quaternion = /** @class */ (function () {
  4289. /**
  4290. * Creates a new Quaternion from the passed floats.
  4291. */
  4292. function Quaternion(x, y, z, w) {
  4293. if (x === void 0) { x = 0.0; }
  4294. if (y === void 0) { y = 0.0; }
  4295. if (z === void 0) { z = 0.0; }
  4296. if (w === void 0) { w = 1.0; }
  4297. this.x = x;
  4298. this.y = y;
  4299. this.z = z;
  4300. this.w = w;
  4301. }
  4302. /**
  4303. * Returns a string with the Quaternion coordinates.
  4304. */
  4305. Quaternion.prototype.toString = function () {
  4306. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4307. };
  4308. /**
  4309. * Returns the string "Quaternion".
  4310. */
  4311. Quaternion.prototype.getClassName = function () {
  4312. return "Quaternion";
  4313. };
  4314. /**
  4315. * Returns the Quaternion hash code.
  4316. */
  4317. Quaternion.prototype.getHashCode = function () {
  4318. var hash = this.x || 0;
  4319. hash = (hash * 397) ^ (this.y || 0);
  4320. hash = (hash * 397) ^ (this.z || 0);
  4321. hash = (hash * 397) ^ (this.w || 0);
  4322. return hash;
  4323. };
  4324. /**
  4325. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4326. */
  4327. Quaternion.prototype.asArray = function () {
  4328. return [this.x, this.y, this.z, this.w];
  4329. };
  4330. /**
  4331. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4332. */
  4333. Quaternion.prototype.equals = function (otherQuaternion) {
  4334. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4335. };
  4336. /**
  4337. * Returns a new Quaternion copied from the current one.
  4338. */
  4339. Quaternion.prototype.clone = function () {
  4340. return new Quaternion(this.x, this.y, this.z, this.w);
  4341. };
  4342. /**
  4343. * Updates the current Quaternion from the passed one coordinates.
  4344. * Returns the updated Quaterion.
  4345. */
  4346. Quaternion.prototype.copyFrom = function (other) {
  4347. this.x = other.x;
  4348. this.y = other.y;
  4349. this.z = other.z;
  4350. this.w = other.w;
  4351. return this;
  4352. };
  4353. /**
  4354. * Updates the current Quaternion from the passed float coordinates.
  4355. * Returns the updated Quaterion.
  4356. */
  4357. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4358. this.x = x;
  4359. this.y = y;
  4360. this.z = z;
  4361. this.w = w;
  4362. return this;
  4363. };
  4364. /**
  4365. * Updates the current Quaternion from the passed float coordinates.
  4366. * Returns the updated Quaterion.
  4367. */
  4368. Quaternion.prototype.set = function (x, y, z, w) {
  4369. return this.copyFromFloats(x, y, z, w);
  4370. };
  4371. /**
  4372. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4373. */
  4374. Quaternion.prototype.add = function (other) {
  4375. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4376. };
  4377. /**
  4378. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4379. */
  4380. Quaternion.prototype.subtract = function (other) {
  4381. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4382. };
  4383. /**
  4384. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4385. */
  4386. Quaternion.prototype.scale = function (value) {
  4387. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4388. };
  4389. /**
  4390. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4391. */
  4392. Quaternion.prototype.multiply = function (q1) {
  4393. var result = new Quaternion(0, 0, 0, 1.0);
  4394. this.multiplyToRef(q1, result);
  4395. return result;
  4396. };
  4397. /**
  4398. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4399. * Returns the current Quaternion.
  4400. */
  4401. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4402. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4403. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4404. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4405. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4406. result.copyFromFloats(x, y, z, w);
  4407. return this;
  4408. };
  4409. /**
  4410. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4411. * Returns the updated Quaternion.
  4412. */
  4413. Quaternion.prototype.multiplyInPlace = function (q1) {
  4414. this.multiplyToRef(q1, this);
  4415. return this;
  4416. };
  4417. /**
  4418. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4419. * Returns the current Quaternion.
  4420. */
  4421. Quaternion.prototype.conjugateToRef = function (ref) {
  4422. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4423. return this;
  4424. };
  4425. /**
  4426. * Conjugates in place the current Quaternion.
  4427. * Returns the updated Quaternion.
  4428. */
  4429. Quaternion.prototype.conjugateInPlace = function () {
  4430. this.x *= -1;
  4431. this.y *= -1;
  4432. this.z *= -1;
  4433. return this;
  4434. };
  4435. /**
  4436. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4437. */
  4438. Quaternion.prototype.conjugate = function () {
  4439. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4440. return result;
  4441. };
  4442. /**
  4443. * Returns the Quaternion length (float).
  4444. */
  4445. Quaternion.prototype.length = function () {
  4446. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4447. };
  4448. /**
  4449. * Normalize in place the current Quaternion.
  4450. * Returns the updated Quaternion.
  4451. */
  4452. Quaternion.prototype.normalize = function () {
  4453. var length = 1.0 / this.length();
  4454. this.x *= length;
  4455. this.y *= length;
  4456. this.z *= length;
  4457. this.w *= length;
  4458. return this;
  4459. };
  4460. /**
  4461. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4462. * @param order is a reserved parameter and is ignore for now
  4463. * @returns the new Vector3
  4464. */
  4465. Quaternion.prototype.toEulerAngles = function (order) {
  4466. if (order === void 0) { order = "YZX"; }
  4467. var result = Vector3.Zero();
  4468. this.toEulerAnglesToRef(result, order);
  4469. return result;
  4470. };
  4471. /**
  4472. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4473. * @param result defines the vector which will be filled with the Euler angles
  4474. * @param order is a reserved parameter and is ignore for now
  4475. * @returns the current Quaternion
  4476. */
  4477. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4478. if (order === void 0) { order = "YZX"; }
  4479. var qz = this.z;
  4480. var qx = this.x;
  4481. var qy = this.y;
  4482. var qw = this.w;
  4483. var sqw = qw * qw;
  4484. var sqz = qz * qz;
  4485. var sqx = qx * qx;
  4486. var sqy = qy * qy;
  4487. var zAxisY = qy * qz - qx * qw;
  4488. var limit = .4999999;
  4489. if (zAxisY < -limit) {
  4490. result.y = 2 * Math.atan2(qy, qw);
  4491. result.x = Math.PI / 2;
  4492. result.z = 0;
  4493. }
  4494. else if (zAxisY > limit) {
  4495. result.y = 2 * Math.atan2(qy, qw);
  4496. result.x = -Math.PI / 2;
  4497. result.z = 0;
  4498. }
  4499. else {
  4500. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4501. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4502. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4503. }
  4504. return this;
  4505. };
  4506. /**
  4507. * Updates the passed rotation matrix with the current Quaternion values.
  4508. * Returns the current Quaternion.
  4509. */
  4510. Quaternion.prototype.toRotationMatrix = function (result) {
  4511. var xx = this.x * this.x;
  4512. var yy = this.y * this.y;
  4513. var zz = this.z * this.z;
  4514. var xy = this.x * this.y;
  4515. var zw = this.z * this.w;
  4516. var zx = this.z * this.x;
  4517. var yw = this.y * this.w;
  4518. var yz = this.y * this.z;
  4519. var xw = this.x * this.w;
  4520. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4521. result.m[1] = 2.0 * (xy + zw);
  4522. result.m[2] = 2.0 * (zx - yw);
  4523. result.m[3] = 0;
  4524. result.m[4] = 2.0 * (xy - zw);
  4525. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4526. result.m[6] = 2.0 * (yz + xw);
  4527. result.m[7] = 0;
  4528. result.m[8] = 2.0 * (zx + yw);
  4529. result.m[9] = 2.0 * (yz - xw);
  4530. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4531. result.m[11] = 0;
  4532. result.m[12] = 0;
  4533. result.m[13] = 0;
  4534. result.m[14] = 0;
  4535. result.m[15] = 1.0;
  4536. result._markAsUpdated();
  4537. return this;
  4538. };
  4539. /**
  4540. * Updates the current Quaternion from the passed rotation matrix values.
  4541. * Returns the updated Quaternion.
  4542. */
  4543. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4544. Quaternion.FromRotationMatrixToRef(matrix, this);
  4545. return this;
  4546. };
  4547. // Statics
  4548. /**
  4549. * Returns a new Quaternion set from the passed rotation matrix values.
  4550. */
  4551. Quaternion.FromRotationMatrix = function (matrix) {
  4552. var result = new Quaternion();
  4553. Quaternion.FromRotationMatrixToRef(matrix, result);
  4554. return result;
  4555. };
  4556. /**
  4557. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4558. */
  4559. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4560. var data = matrix.m;
  4561. var m11 = data[0], m12 = data[4], m13 = data[8];
  4562. var m21 = data[1], m22 = data[5], m23 = data[9];
  4563. var m31 = data[2], m32 = data[6], m33 = data[10];
  4564. var trace = m11 + m22 + m33;
  4565. var s;
  4566. if (trace > 0) {
  4567. s = 0.5 / Math.sqrt(trace + 1.0);
  4568. result.w = 0.25 / s;
  4569. result.x = (m32 - m23) * s;
  4570. result.y = (m13 - m31) * s;
  4571. result.z = (m21 - m12) * s;
  4572. }
  4573. else if (m11 > m22 && m11 > m33) {
  4574. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4575. result.w = (m32 - m23) / s;
  4576. result.x = 0.25 * s;
  4577. result.y = (m12 + m21) / s;
  4578. result.z = (m13 + m31) / s;
  4579. }
  4580. else if (m22 > m33) {
  4581. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4582. result.w = (m13 - m31) / s;
  4583. result.x = (m12 + m21) / s;
  4584. result.y = 0.25 * s;
  4585. result.z = (m23 + m32) / s;
  4586. }
  4587. else {
  4588. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4589. result.w = (m21 - m12) / s;
  4590. result.x = (m13 + m31) / s;
  4591. result.y = (m23 + m32) / s;
  4592. result.z = 0.25 * s;
  4593. }
  4594. };
  4595. /**
  4596. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4597. */
  4598. Quaternion.Zero = function () {
  4599. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4600. };
  4601. /**
  4602. * Returns a new Quaternion as the inverted current Quaternion.
  4603. */
  4604. Quaternion.Inverse = function (q) {
  4605. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4606. };
  4607. /**
  4608. * Returns the identity Quaternion.
  4609. */
  4610. Quaternion.Identity = function () {
  4611. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4612. };
  4613. Quaternion.IsIdentity = function (quaternion) {
  4614. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4615. };
  4616. /**
  4617. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4618. */
  4619. Quaternion.RotationAxis = function (axis, angle) {
  4620. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4621. };
  4622. /**
  4623. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4624. */
  4625. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4626. var sin = Math.sin(angle / 2);
  4627. axis.normalize();
  4628. result.w = Math.cos(angle / 2);
  4629. result.x = axis.x * sin;
  4630. result.y = axis.y * sin;
  4631. result.z = axis.z * sin;
  4632. return result;
  4633. };
  4634. /**
  4635. * Retuns a new Quaternion set from the starting index of the passed array.
  4636. */
  4637. Quaternion.FromArray = function (array, offset) {
  4638. if (!offset) {
  4639. offset = 0;
  4640. }
  4641. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4642. };
  4643. /**
  4644. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4645. */
  4646. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4647. var q = new Quaternion();
  4648. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4649. return q;
  4650. };
  4651. /**
  4652. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4653. */
  4654. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4655. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4656. var halfRoll = roll * 0.5;
  4657. var halfPitch = pitch * 0.5;
  4658. var halfYaw = yaw * 0.5;
  4659. var sinRoll = Math.sin(halfRoll);
  4660. var cosRoll = Math.cos(halfRoll);
  4661. var sinPitch = Math.sin(halfPitch);
  4662. var cosPitch = Math.cos(halfPitch);
  4663. var sinYaw = Math.sin(halfYaw);
  4664. var cosYaw = Math.cos(halfYaw);
  4665. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4666. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4667. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4668. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4669. };
  4670. /**
  4671. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4672. */
  4673. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4674. var result = new Quaternion();
  4675. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4676. return result;
  4677. };
  4678. /**
  4679. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4680. */
  4681. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4682. // Produces a quaternion from Euler angles in the z-x-z orientation
  4683. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4684. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4685. var halfBeta = beta * 0.5;
  4686. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4687. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4688. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4689. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4690. };
  4691. /**
  4692. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4693. * cf to Vector3.RotationFromAxis() documentation.
  4694. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4695. */
  4696. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4697. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4698. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4699. return quat;
  4700. };
  4701. /**
  4702. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4703. * cf to Vector3.RotationFromAxis() documentation.
  4704. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4705. */
  4706. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4707. var rotMat = MathTmp.Matrix[0];
  4708. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4709. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4710. };
  4711. Quaternion.Slerp = function (left, right, amount) {
  4712. var result = Quaternion.Identity();
  4713. Quaternion.SlerpToRef(left, right, amount, result);
  4714. return result;
  4715. };
  4716. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4717. var num2;
  4718. var num3;
  4719. var num = amount;
  4720. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4721. var flag = false;
  4722. if (num4 < 0) {
  4723. flag = true;
  4724. num4 = -num4;
  4725. }
  4726. if (num4 > 0.999999) {
  4727. num3 = 1 - num;
  4728. num2 = flag ? -num : num;
  4729. }
  4730. else {
  4731. var num5 = Math.acos(num4);
  4732. var num6 = (1.0 / Math.sin(num5));
  4733. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4734. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4735. }
  4736. result.x = (num3 * left.x) + (num2 * right.x);
  4737. result.y = (num3 * left.y) + (num2 * right.y);
  4738. result.z = (num3 * left.z) + (num2 * right.z);
  4739. result.w = (num3 * left.w) + (num2 * right.w);
  4740. };
  4741. /**
  4742. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4743. */
  4744. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4745. var squared = amount * amount;
  4746. var cubed = amount * squared;
  4747. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4748. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4749. var part3 = (cubed - (2.0 * squared)) + amount;
  4750. var part4 = cubed - squared;
  4751. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4752. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4753. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4754. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4755. return new Quaternion(x, y, z, w);
  4756. };
  4757. return Quaternion;
  4758. }());
  4759. BABYLON.Quaternion = Quaternion;
  4760. var Matrix = /** @class */ (function () {
  4761. function Matrix() {
  4762. this._isIdentity = false;
  4763. this._isIdentityDirty = true;
  4764. this.m = new Float32Array(16);
  4765. this._markAsUpdated();
  4766. }
  4767. Matrix.prototype._markAsUpdated = function () {
  4768. this.updateFlag = Matrix._updateFlagSeed++;
  4769. this._isIdentityDirty = true;
  4770. };
  4771. // Properties
  4772. /**
  4773. * Boolean : True is the matrix is the identity matrix
  4774. */
  4775. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4776. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4777. if (this._isIdentityDirty) {
  4778. this._isIdentityDirty = false;
  4779. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4780. this._isIdentity = false;
  4781. }
  4782. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4783. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4784. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4785. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4786. this._isIdentity = false;
  4787. }
  4788. else {
  4789. this._isIdentity = true;
  4790. }
  4791. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4792. this._isIdentity = false;
  4793. }
  4794. }
  4795. return this._isIdentity;
  4796. };
  4797. /**
  4798. * Returns the matrix determinant (float).
  4799. */
  4800. Matrix.prototype.determinant = function () {
  4801. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4802. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4803. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4804. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4805. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4806. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4807. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4808. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4809. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4810. };
  4811. // Methods
  4812. /**
  4813. * Returns the matrix underlying array.
  4814. */
  4815. Matrix.prototype.toArray = function () {
  4816. return this.m;
  4817. };
  4818. /**
  4819. * Returns the matrix underlying array.
  4820. */
  4821. Matrix.prototype.asArray = function () {
  4822. return this.toArray();
  4823. };
  4824. /**
  4825. * Inverts in place the Matrix.
  4826. * Returns the Matrix inverted.
  4827. */
  4828. Matrix.prototype.invert = function () {
  4829. this.invertToRef(this);
  4830. return this;
  4831. };
  4832. /**
  4833. * Sets all the matrix elements to zero.
  4834. * Returns the Matrix.
  4835. */
  4836. Matrix.prototype.reset = function () {
  4837. for (var index = 0; index < 16; index++) {
  4838. this.m[index] = 0.0;
  4839. }
  4840. this._markAsUpdated();
  4841. return this;
  4842. };
  4843. /**
  4844. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4845. */
  4846. Matrix.prototype.add = function (other) {
  4847. var result = new Matrix();
  4848. this.addToRef(other, result);
  4849. return result;
  4850. };
  4851. /**
  4852. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4853. * Returns the Matrix.
  4854. */
  4855. Matrix.prototype.addToRef = function (other, result) {
  4856. for (var index = 0; index < 16; index++) {
  4857. result.m[index] = this.m[index] + other.m[index];
  4858. }
  4859. result._markAsUpdated();
  4860. return this;
  4861. };
  4862. /**
  4863. * Adds in place the passed matrix to the current Matrix.
  4864. * Returns the updated Matrix.
  4865. */
  4866. Matrix.prototype.addToSelf = function (other) {
  4867. for (var index = 0; index < 16; index++) {
  4868. this.m[index] += other.m[index];
  4869. }
  4870. this._markAsUpdated();
  4871. return this;
  4872. };
  4873. /**
  4874. * Sets the passed matrix with the current inverted Matrix.
  4875. * Returns the unmodified current Matrix.
  4876. */
  4877. Matrix.prototype.invertToRef = function (other) {
  4878. var l1 = this.m[0];
  4879. var l2 = this.m[1];
  4880. var l3 = this.m[2];
  4881. var l4 = this.m[3];
  4882. var l5 = this.m[4];
  4883. var l6 = this.m[5];
  4884. var l7 = this.m[6];
  4885. var l8 = this.m[7];
  4886. var l9 = this.m[8];
  4887. var l10 = this.m[9];
  4888. var l11 = this.m[10];
  4889. var l12 = this.m[11];
  4890. var l13 = this.m[12];
  4891. var l14 = this.m[13];
  4892. var l15 = this.m[14];
  4893. var l16 = this.m[15];
  4894. var l17 = (l11 * l16) - (l12 * l15);
  4895. var l18 = (l10 * l16) - (l12 * l14);
  4896. var l19 = (l10 * l15) - (l11 * l14);
  4897. var l20 = (l9 * l16) - (l12 * l13);
  4898. var l21 = (l9 * l15) - (l11 * l13);
  4899. var l22 = (l9 * l14) - (l10 * l13);
  4900. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4901. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4902. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4903. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4904. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4905. var l28 = (l7 * l16) - (l8 * l15);
  4906. var l29 = (l6 * l16) - (l8 * l14);
  4907. var l30 = (l6 * l15) - (l7 * l14);
  4908. var l31 = (l5 * l16) - (l8 * l13);
  4909. var l32 = (l5 * l15) - (l7 * l13);
  4910. var l33 = (l5 * l14) - (l6 * l13);
  4911. var l34 = (l7 * l12) - (l8 * l11);
  4912. var l35 = (l6 * l12) - (l8 * l10);
  4913. var l36 = (l6 * l11) - (l7 * l10);
  4914. var l37 = (l5 * l12) - (l8 * l9);
  4915. var l38 = (l5 * l11) - (l7 * l9);
  4916. var l39 = (l5 * l10) - (l6 * l9);
  4917. other.m[0] = l23 * l27;
  4918. other.m[4] = l24 * l27;
  4919. other.m[8] = l25 * l27;
  4920. other.m[12] = l26 * l27;
  4921. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4922. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4923. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4924. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4925. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4926. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4927. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4928. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4929. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4930. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4931. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4932. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4933. other._markAsUpdated();
  4934. return this;
  4935. };
  4936. /**
  4937. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4938. * Returns the updated Matrix.
  4939. */
  4940. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4941. this.m[12] = x;
  4942. this.m[13] = y;
  4943. this.m[14] = z;
  4944. this._markAsUpdated();
  4945. return this;
  4946. };
  4947. /**
  4948. * Inserts the translation vector in the current Matrix.
  4949. * Returns the updated Matrix.
  4950. */
  4951. Matrix.prototype.setTranslation = function (vector3) {
  4952. this.m[12] = vector3.x;
  4953. this.m[13] = vector3.y;
  4954. this.m[14] = vector3.z;
  4955. this._markAsUpdated();
  4956. return this;
  4957. };
  4958. /**
  4959. * Returns a new Vector3 as the extracted translation from the Matrix.
  4960. */
  4961. Matrix.prototype.getTranslation = function () {
  4962. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4963. };
  4964. /**
  4965. * Fill a Vector3 with the extracted translation from the Matrix.
  4966. */
  4967. Matrix.prototype.getTranslationToRef = function (result) {
  4968. result.x = this.m[12];
  4969. result.y = this.m[13];
  4970. result.z = this.m[14];
  4971. return this;
  4972. };
  4973. /**
  4974. * Remove rotation and scaling part from the Matrix.
  4975. * Returns the updated Matrix.
  4976. */
  4977. Matrix.prototype.removeRotationAndScaling = function () {
  4978. this.setRowFromFloats(0, 1, 0, 0, 0);
  4979. this.setRowFromFloats(1, 0, 1, 0, 0);
  4980. this.setRowFromFloats(2, 0, 0, 1, 0);
  4981. return this;
  4982. };
  4983. /**
  4984. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4985. */
  4986. Matrix.prototype.multiply = function (other) {
  4987. var result = new Matrix();
  4988. this.multiplyToRef(other, result);
  4989. return result;
  4990. };
  4991. /**
  4992. * Updates the current Matrix from the passed one values.
  4993. * Returns the updated Matrix.
  4994. */
  4995. Matrix.prototype.copyFrom = function (other) {
  4996. for (var index = 0; index < 16; index++) {
  4997. this.m[index] = other.m[index];
  4998. }
  4999. this._markAsUpdated();
  5000. return this;
  5001. };
  5002. /**
  5003. * Populates the passed array from the starting index with the Matrix values.
  5004. * Returns the Matrix.
  5005. */
  5006. Matrix.prototype.copyToArray = function (array, offset) {
  5007. if (offset === void 0) { offset = 0; }
  5008. for (var index = 0; index < 16; index++) {
  5009. array[offset + index] = this.m[index];
  5010. }
  5011. return this;
  5012. };
  5013. /**
  5014. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  5015. */
  5016. Matrix.prototype.multiplyToRef = function (other, result) {
  5017. this.multiplyToArray(other, result.m, 0);
  5018. result._markAsUpdated();
  5019. return this;
  5020. };
  5021. /**
  5022. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  5023. */
  5024. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5025. var tm0 = this.m[0];
  5026. var tm1 = this.m[1];
  5027. var tm2 = this.m[2];
  5028. var tm3 = this.m[3];
  5029. var tm4 = this.m[4];
  5030. var tm5 = this.m[5];
  5031. var tm6 = this.m[6];
  5032. var tm7 = this.m[7];
  5033. var tm8 = this.m[8];
  5034. var tm9 = this.m[9];
  5035. var tm10 = this.m[10];
  5036. var tm11 = this.m[11];
  5037. var tm12 = this.m[12];
  5038. var tm13 = this.m[13];
  5039. var tm14 = this.m[14];
  5040. var tm15 = this.m[15];
  5041. var om0 = other.m[0];
  5042. var om1 = other.m[1];
  5043. var om2 = other.m[2];
  5044. var om3 = other.m[3];
  5045. var om4 = other.m[4];
  5046. var om5 = other.m[5];
  5047. var om6 = other.m[6];
  5048. var om7 = other.m[7];
  5049. var om8 = other.m[8];
  5050. var om9 = other.m[9];
  5051. var om10 = other.m[10];
  5052. var om11 = other.m[11];
  5053. var om12 = other.m[12];
  5054. var om13 = other.m[13];
  5055. var om14 = other.m[14];
  5056. var om15 = other.m[15];
  5057. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5058. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5059. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5060. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5061. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5062. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5063. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5064. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5065. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5066. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5067. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5068. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5069. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5070. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5071. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5072. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5073. return this;
  5074. };
  5075. /**
  5076. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5077. */
  5078. Matrix.prototype.equals = function (value) {
  5079. return value &&
  5080. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5081. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5082. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5083. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5084. };
  5085. /**
  5086. * Returns a new Matrix from the current Matrix.
  5087. */
  5088. Matrix.prototype.clone = function () {
  5089. 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]);
  5090. };
  5091. /**
  5092. * Returns the string "Matrix"
  5093. */
  5094. Matrix.prototype.getClassName = function () {
  5095. return "Matrix";
  5096. };
  5097. /**
  5098. * Returns the Matrix hash code.
  5099. */
  5100. Matrix.prototype.getHashCode = function () {
  5101. var hash = this.m[0] || 0;
  5102. for (var i = 1; i < 16; i++) {
  5103. hash = (hash * 397) ^ (this.m[i] || 0);
  5104. }
  5105. return hash;
  5106. };
  5107. /**
  5108. * Decomposes the current Matrix into :
  5109. * - a scale vector3 passed as a reference to update,
  5110. * - a rotation quaternion passed as a reference to update,
  5111. * - a translation vector3 passed as a reference to update.
  5112. * Returns the true if operation was successful.
  5113. */
  5114. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5115. translation.x = this.m[12];
  5116. translation.y = this.m[13];
  5117. translation.z = this.m[14];
  5118. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5119. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5120. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5121. if (this.determinant() <= 0) {
  5122. scale.y *= -1;
  5123. }
  5124. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5125. rotation.x = 0;
  5126. rotation.y = 0;
  5127. rotation.z = 0;
  5128. rotation.w = 1;
  5129. return false;
  5130. }
  5131. 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]);
  5132. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5133. return true;
  5134. };
  5135. /**
  5136. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5137. * @param ref matrix to store the result
  5138. */
  5139. Matrix.prototype.toNormalMatrix = function (ref) {
  5140. this.invertToRef(ref);
  5141. ref.transpose();
  5142. var m = ref.m;
  5143. 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);
  5144. };
  5145. /**
  5146. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5147. */
  5148. Matrix.prototype.getRotationMatrix = function () {
  5149. var result = Matrix.Identity();
  5150. this.getRotationMatrixToRef(result);
  5151. return result;
  5152. };
  5153. /**
  5154. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5155. * Returns the current Matrix.
  5156. */
  5157. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5158. var m = this.m;
  5159. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5160. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5161. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5162. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5163. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5164. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5165. 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);
  5166. return this;
  5167. };
  5168. // Statics
  5169. /**
  5170. * Returns a new Matrix set from the starting index of the passed array.
  5171. */
  5172. Matrix.FromArray = function (array, offset) {
  5173. var result = new Matrix();
  5174. if (!offset) {
  5175. offset = 0;
  5176. }
  5177. Matrix.FromArrayToRef(array, offset, result);
  5178. return result;
  5179. };
  5180. /**
  5181. * Sets the passed "result" matrix from the starting index of the passed array.
  5182. */
  5183. Matrix.FromArrayToRef = function (array, offset, result) {
  5184. for (var index = 0; index < 16; index++) {
  5185. result.m[index] = array[index + offset];
  5186. }
  5187. result._markAsUpdated();
  5188. };
  5189. /**
  5190. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5191. */
  5192. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5193. for (var index = 0; index < 16; index++) {
  5194. result.m[index] = array[index + offset] * scale;
  5195. }
  5196. result._markAsUpdated();
  5197. };
  5198. /**
  5199. * Sets the passed matrix "result" with the 16 passed floats.
  5200. */
  5201. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5202. result.m[0] = initialM11;
  5203. result.m[1] = initialM12;
  5204. result.m[2] = initialM13;
  5205. result.m[3] = initialM14;
  5206. result.m[4] = initialM21;
  5207. result.m[5] = initialM22;
  5208. result.m[6] = initialM23;
  5209. result.m[7] = initialM24;
  5210. result.m[8] = initialM31;
  5211. result.m[9] = initialM32;
  5212. result.m[10] = initialM33;
  5213. result.m[11] = initialM34;
  5214. result.m[12] = initialM41;
  5215. result.m[13] = initialM42;
  5216. result.m[14] = initialM43;
  5217. result.m[15] = initialM44;
  5218. result._markAsUpdated();
  5219. };
  5220. /**
  5221. * Returns the index-th row of the current matrix as a new Vector4.
  5222. */
  5223. Matrix.prototype.getRow = function (index) {
  5224. if (index < 0 || index > 3) {
  5225. return null;
  5226. }
  5227. var i = index * 4;
  5228. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5229. };
  5230. /**
  5231. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5232. * Returns the updated Matrix.
  5233. */
  5234. Matrix.prototype.setRow = function (index, row) {
  5235. if (index < 0 || index > 3) {
  5236. return this;
  5237. }
  5238. var i = index * 4;
  5239. this.m[i + 0] = row.x;
  5240. this.m[i + 1] = row.y;
  5241. this.m[i + 2] = row.z;
  5242. this.m[i + 3] = row.w;
  5243. this._markAsUpdated();
  5244. return this;
  5245. };
  5246. /**
  5247. * Compute the transpose of the matrix.
  5248. * Returns a new Matrix.
  5249. */
  5250. Matrix.prototype.transpose = function () {
  5251. return Matrix.Transpose(this);
  5252. };
  5253. /**
  5254. * Compute the transpose of the matrix.
  5255. * Returns the current matrix.
  5256. */
  5257. Matrix.prototype.transposeToRef = function (result) {
  5258. Matrix.TransposeToRef(this, result);
  5259. return this;
  5260. };
  5261. /**
  5262. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5263. * Returns the updated Matrix.
  5264. */
  5265. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5266. if (index < 0 || index > 3) {
  5267. return this;
  5268. }
  5269. var i = index * 4;
  5270. this.m[i + 0] = x;
  5271. this.m[i + 1] = y;
  5272. this.m[i + 2] = z;
  5273. this.m[i + 3] = w;
  5274. this._markAsUpdated();
  5275. return this;
  5276. };
  5277. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5278. /**
  5279. * Static identity matrix to be used as readonly matrix
  5280. * Must not be updated.
  5281. */
  5282. get: function () {
  5283. return Matrix._identityReadOnly;
  5284. },
  5285. enumerable: true,
  5286. configurable: true
  5287. });
  5288. /**
  5289. * Returns a new Matrix set from the 16 passed floats.
  5290. */
  5291. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5292. var result = new Matrix();
  5293. result.m[0] = initialM11;
  5294. result.m[1] = initialM12;
  5295. result.m[2] = initialM13;
  5296. result.m[3] = initialM14;
  5297. result.m[4] = initialM21;
  5298. result.m[5] = initialM22;
  5299. result.m[6] = initialM23;
  5300. result.m[7] = initialM24;
  5301. result.m[8] = initialM31;
  5302. result.m[9] = initialM32;
  5303. result.m[10] = initialM33;
  5304. result.m[11] = initialM34;
  5305. result.m[12] = initialM41;
  5306. result.m[13] = initialM42;
  5307. result.m[14] = initialM43;
  5308. result.m[15] = initialM44;
  5309. return result;
  5310. };
  5311. /**
  5312. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5313. */
  5314. Matrix.Compose = function (scale, rotation, translation) {
  5315. var result = Matrix.Identity();
  5316. Matrix.ComposeToRef(scale, rotation, translation, result);
  5317. return result;
  5318. };
  5319. /**
  5320. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5321. */
  5322. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5323. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5324. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5325. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5326. result.setTranslation(translation);
  5327. };
  5328. /**
  5329. * Returns a new indentity Matrix.
  5330. */
  5331. Matrix.Identity = function () {
  5332. 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);
  5333. };
  5334. /**
  5335. * Sets the passed "result" as an identity matrix.
  5336. */
  5337. Matrix.IdentityToRef = function (result) {
  5338. 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);
  5339. };
  5340. /**
  5341. * Returns a new zero Matrix.
  5342. */
  5343. Matrix.Zero = function () {
  5344. 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);
  5345. };
  5346. /**
  5347. * Returns a new rotation matrix for "angle" radians around the X axis.
  5348. */
  5349. Matrix.RotationX = function (angle) {
  5350. var result = new Matrix();
  5351. Matrix.RotationXToRef(angle, result);
  5352. return result;
  5353. };
  5354. /**
  5355. * Returns a new Matrix as the passed inverted one.
  5356. */
  5357. Matrix.Invert = function (source) {
  5358. var result = new Matrix();
  5359. source.invertToRef(result);
  5360. return result;
  5361. };
  5362. /**
  5363. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5364. */
  5365. Matrix.RotationXToRef = function (angle, result) {
  5366. var s = Math.sin(angle);
  5367. var c = Math.cos(angle);
  5368. result.m[0] = 1.0;
  5369. result.m[15] = 1.0;
  5370. result.m[5] = c;
  5371. result.m[10] = c;
  5372. result.m[9] = -s;
  5373. result.m[6] = s;
  5374. result.m[1] = 0.0;
  5375. result.m[2] = 0.0;
  5376. result.m[3] = 0.0;
  5377. result.m[4] = 0.0;
  5378. result.m[7] = 0.0;
  5379. result.m[8] = 0.0;
  5380. result.m[11] = 0.0;
  5381. result.m[12] = 0.0;
  5382. result.m[13] = 0.0;
  5383. result.m[14] = 0.0;
  5384. result._markAsUpdated();
  5385. };
  5386. /**
  5387. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5388. */
  5389. Matrix.RotationY = function (angle) {
  5390. var result = new Matrix();
  5391. Matrix.RotationYToRef(angle, result);
  5392. return result;
  5393. };
  5394. /**
  5395. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5396. */
  5397. Matrix.RotationYToRef = function (angle, result) {
  5398. var s = Math.sin(angle);
  5399. var c = Math.cos(angle);
  5400. result.m[5] = 1.0;
  5401. result.m[15] = 1.0;
  5402. result.m[0] = c;
  5403. result.m[2] = -s;
  5404. result.m[8] = s;
  5405. result.m[10] = c;
  5406. result.m[1] = 0.0;
  5407. result.m[3] = 0.0;
  5408. result.m[4] = 0.0;
  5409. result.m[6] = 0.0;
  5410. result.m[7] = 0.0;
  5411. result.m[9] = 0.0;
  5412. result.m[11] = 0.0;
  5413. result.m[12] = 0.0;
  5414. result.m[13] = 0.0;
  5415. result.m[14] = 0.0;
  5416. result._markAsUpdated();
  5417. };
  5418. /**
  5419. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5420. */
  5421. Matrix.RotationZ = function (angle) {
  5422. var result = new Matrix();
  5423. Matrix.RotationZToRef(angle, result);
  5424. return result;
  5425. };
  5426. /**
  5427. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5428. */
  5429. Matrix.RotationZToRef = function (angle, result) {
  5430. var s = Math.sin(angle);
  5431. var c = Math.cos(angle);
  5432. result.m[10] = 1.0;
  5433. result.m[15] = 1.0;
  5434. result.m[0] = c;
  5435. result.m[1] = s;
  5436. result.m[4] = -s;
  5437. result.m[5] = c;
  5438. result.m[2] = 0.0;
  5439. result.m[3] = 0.0;
  5440. result.m[6] = 0.0;
  5441. result.m[7] = 0.0;
  5442. result.m[8] = 0.0;
  5443. result.m[9] = 0.0;
  5444. result.m[11] = 0.0;
  5445. result.m[12] = 0.0;
  5446. result.m[13] = 0.0;
  5447. result.m[14] = 0.0;
  5448. result._markAsUpdated();
  5449. };
  5450. /**
  5451. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5452. */
  5453. Matrix.RotationAxis = function (axis, angle) {
  5454. var result = Matrix.Zero();
  5455. Matrix.RotationAxisToRef(axis, angle, result);
  5456. return result;
  5457. };
  5458. /**
  5459. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5460. */
  5461. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5462. var s = Math.sin(-angle);
  5463. var c = Math.cos(-angle);
  5464. var c1 = 1 - c;
  5465. axis.normalize();
  5466. result.m[0] = (axis.x * axis.x) * c1 + c;
  5467. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5468. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5469. result.m[3] = 0.0;
  5470. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5471. result.m[5] = (axis.y * axis.y) * c1 + c;
  5472. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5473. result.m[7] = 0.0;
  5474. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5475. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5476. result.m[10] = (axis.z * axis.z) * c1 + c;
  5477. result.m[11] = 0.0;
  5478. result.m[15] = 1.0;
  5479. result._markAsUpdated();
  5480. };
  5481. /**
  5482. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5483. */
  5484. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5485. var result = new Matrix();
  5486. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5487. return result;
  5488. };
  5489. /**
  5490. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5491. */
  5492. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5493. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5494. this._tempQuaternion.toRotationMatrix(result);
  5495. };
  5496. /**
  5497. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5498. */
  5499. Matrix.Scaling = function (x, y, z) {
  5500. var result = Matrix.Zero();
  5501. Matrix.ScalingToRef(x, y, z, result);
  5502. return result;
  5503. };
  5504. /**
  5505. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5506. */
  5507. Matrix.ScalingToRef = function (x, y, z, result) {
  5508. result.m[0] = x;
  5509. result.m[1] = 0.0;
  5510. result.m[2] = 0.0;
  5511. result.m[3] = 0.0;
  5512. result.m[4] = 0.0;
  5513. result.m[5] = y;
  5514. result.m[6] = 0.0;
  5515. result.m[7] = 0.0;
  5516. result.m[8] = 0.0;
  5517. result.m[9] = 0.0;
  5518. result.m[10] = z;
  5519. result.m[11] = 0.0;
  5520. result.m[12] = 0.0;
  5521. result.m[13] = 0.0;
  5522. result.m[14] = 0.0;
  5523. result.m[15] = 1.0;
  5524. result._markAsUpdated();
  5525. };
  5526. /**
  5527. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5528. */
  5529. Matrix.Translation = function (x, y, z) {
  5530. var result = Matrix.Identity();
  5531. Matrix.TranslationToRef(x, y, z, result);
  5532. return result;
  5533. };
  5534. /**
  5535. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5536. */
  5537. Matrix.TranslationToRef = function (x, y, z, result) {
  5538. 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);
  5539. };
  5540. /**
  5541. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5542. * @param startValue defines the start value
  5543. * @param endValue defines the end value
  5544. * @param gradient defines the gradient factor
  5545. * @returns the new matrix
  5546. */
  5547. Matrix.Lerp = function (startValue, endValue, gradient) {
  5548. var result = Matrix.Zero();
  5549. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5550. return result;
  5551. };
  5552. /**
  5553. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5554. * @param startValue defines the start value
  5555. * @param endValue defines the end value
  5556. * @param gradient defines the gradient factor
  5557. * @param result defines the Matrix object where to store data
  5558. */
  5559. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5560. for (var index = 0; index < 16; index++) {
  5561. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5562. }
  5563. result._markAsUpdated();
  5564. };
  5565. /**
  5566. * Returns a new Matrix whose values are computed by :
  5567. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5568. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5569. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5570. */
  5571. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5572. var startScale = new Vector3(0, 0, 0);
  5573. var startRotation = new Quaternion();
  5574. var startTranslation = new Vector3(0, 0, 0);
  5575. startValue.decompose(startScale, startRotation, startTranslation);
  5576. var endScale = new Vector3(0, 0, 0);
  5577. var endRotation = new Quaternion();
  5578. var endTranslation = new Vector3(0, 0, 0);
  5579. endValue.decompose(endScale, endRotation, endTranslation);
  5580. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5581. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5582. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5583. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5584. };
  5585. /**
  5586. * 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".
  5587. * This methods works for a Left-Handed system.
  5588. */
  5589. Matrix.LookAtLH = function (eye, target, up) {
  5590. var result = Matrix.Zero();
  5591. Matrix.LookAtLHToRef(eye, target, up, result);
  5592. return result;
  5593. };
  5594. /**
  5595. * 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".
  5596. * This methods works for a Left-Handed system.
  5597. */
  5598. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5599. // Z axis
  5600. target.subtractToRef(eye, this._zAxis);
  5601. this._zAxis.normalize();
  5602. // X axis
  5603. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5604. if (this._xAxis.lengthSquared() === 0) {
  5605. this._xAxis.x = 1.0;
  5606. }
  5607. else {
  5608. this._xAxis.normalize();
  5609. }
  5610. // Y axis
  5611. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5612. this._yAxis.normalize();
  5613. // Eye angles
  5614. var ex = -Vector3.Dot(this._xAxis, eye);
  5615. var ey = -Vector3.Dot(this._yAxis, eye);
  5616. var ez = -Vector3.Dot(this._zAxis, eye);
  5617. 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);
  5618. };
  5619. /**
  5620. * 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".
  5621. * This methods works for a Right-Handed system.
  5622. */
  5623. Matrix.LookAtRH = function (eye, target, up) {
  5624. var result = Matrix.Zero();
  5625. Matrix.LookAtRHToRef(eye, target, up, result);
  5626. return result;
  5627. };
  5628. /**
  5629. * 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".
  5630. * This methods works for a Left-Handed system.
  5631. */
  5632. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5633. // Z axis
  5634. eye.subtractToRef(target, this._zAxis);
  5635. this._zAxis.normalize();
  5636. // X axis
  5637. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5638. if (this._xAxis.lengthSquared() === 0) {
  5639. this._xAxis.x = 1.0;
  5640. }
  5641. else {
  5642. this._xAxis.normalize();
  5643. }
  5644. // Y axis
  5645. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5646. this._yAxis.normalize();
  5647. // Eye angles
  5648. var ex = -Vector3.Dot(this._xAxis, eye);
  5649. var ey = -Vector3.Dot(this._yAxis, eye);
  5650. var ez = -Vector3.Dot(this._zAxis, eye);
  5651. 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);
  5652. };
  5653. /**
  5654. * 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.
  5655. */
  5656. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5657. var matrix = Matrix.Zero();
  5658. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5659. return matrix;
  5660. };
  5661. /**
  5662. * 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.
  5663. */
  5664. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5665. var n = znear;
  5666. var f = zfar;
  5667. var a = 2.0 / width;
  5668. var b = 2.0 / height;
  5669. var c = 2.0 / (f - n);
  5670. var d = -(f + n) / (f - n);
  5671. 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);
  5672. };
  5673. /**
  5674. * 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.
  5675. */
  5676. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5677. var matrix = Matrix.Zero();
  5678. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5679. return matrix;
  5680. };
  5681. /**
  5682. * 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.
  5683. */
  5684. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5685. var n = znear;
  5686. var f = zfar;
  5687. var a = 2.0 / (right - left);
  5688. var b = 2.0 / (top - bottom);
  5689. var c = 2.0 / (f - n);
  5690. var d = -(f + n) / (f - n);
  5691. var i0 = (left + right) / (left - right);
  5692. var i1 = (top + bottom) / (bottom - top);
  5693. 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);
  5694. };
  5695. /**
  5696. * 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.
  5697. */
  5698. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5699. var matrix = Matrix.Zero();
  5700. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5701. return matrix;
  5702. };
  5703. /**
  5704. * 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.
  5705. */
  5706. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5707. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5708. result.m[10] *= -1.0;
  5709. };
  5710. /**
  5711. * 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.
  5712. */
  5713. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5714. var matrix = Matrix.Zero();
  5715. var n = znear;
  5716. var f = zfar;
  5717. var a = 2.0 * n / width;
  5718. var b = 2.0 * n / height;
  5719. var c = (f + n) / (f - n);
  5720. var d = -2.0 * f * n / (f - n);
  5721. 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);
  5722. return matrix;
  5723. };
  5724. /**
  5725. * 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.
  5726. */
  5727. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5728. var matrix = Matrix.Zero();
  5729. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5730. return matrix;
  5731. };
  5732. /**
  5733. * 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.
  5734. */
  5735. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5736. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5737. var n = znear;
  5738. var f = zfar;
  5739. var t = 1.0 / (Math.tan(fov * 0.5));
  5740. var a = isVerticalFovFixed ? (t / aspect) : t;
  5741. var b = isVerticalFovFixed ? t : (t * aspect);
  5742. var c = (f + n) / (f - n);
  5743. var d = -2.0 * f * n / (f - n);
  5744. 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);
  5745. };
  5746. /**
  5747. * 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.
  5748. */
  5749. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5750. var matrix = Matrix.Zero();
  5751. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5752. return matrix;
  5753. };
  5754. /**
  5755. * 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.
  5756. */
  5757. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5758. //alternatively this could be expressed as:
  5759. // m = PerspectiveFovLHToRef
  5760. // m[10] *= -1.0;
  5761. // m[11] *= -1.0;
  5762. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5763. var n = znear;
  5764. var f = zfar;
  5765. var t = 1.0 / (Math.tan(fov * 0.5));
  5766. var a = isVerticalFovFixed ? (t / aspect) : t;
  5767. var b = isVerticalFovFixed ? t : (t * aspect);
  5768. var c = -(f + n) / (f - n);
  5769. var d = -2 * f * n / (f - n);
  5770. 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);
  5771. };
  5772. /**
  5773. * 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.
  5774. */
  5775. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5776. if (rightHanded === void 0) { rightHanded = false; }
  5777. var rightHandedFactor = rightHanded ? -1 : 1;
  5778. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5779. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5780. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5781. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5782. var xScale = 2.0 / (leftTan + rightTan);
  5783. var yScale = 2.0 / (upTan + downTan);
  5784. result.m[0] = xScale;
  5785. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5786. result.m[5] = yScale;
  5787. result.m[6] = result.m[7] = 0.0;
  5788. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5789. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5790. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5791. result.m[10] = -zfar / (znear - zfar);
  5792. result.m[11] = 1.0 * rightHandedFactor;
  5793. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5794. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5795. // result.m[14] = (znear * zfar) / (znear - zfar);
  5796. result._markAsUpdated();
  5797. };
  5798. /**
  5799. * Returns the final transformation matrix : world * view * projection * viewport
  5800. */
  5801. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5802. var cw = viewport.width;
  5803. var ch = viewport.height;
  5804. var cx = viewport.x;
  5805. var cy = viewport.y;
  5806. 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);
  5807. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5808. };
  5809. /**
  5810. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5811. */
  5812. Matrix.GetAsMatrix2x2 = function (matrix) {
  5813. return new Float32Array([
  5814. matrix.m[0], matrix.m[1],
  5815. matrix.m[4], matrix.m[5]
  5816. ]);
  5817. };
  5818. /**
  5819. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5820. */
  5821. Matrix.GetAsMatrix3x3 = function (matrix) {
  5822. return new Float32Array([
  5823. matrix.m[0], matrix.m[1], matrix.m[2],
  5824. matrix.m[4], matrix.m[5], matrix.m[6],
  5825. matrix.m[8], matrix.m[9], matrix.m[10]
  5826. ]);
  5827. };
  5828. /**
  5829. * Compute the transpose of the passed Matrix.
  5830. * Returns a new Matrix.
  5831. */
  5832. Matrix.Transpose = function (matrix) {
  5833. var result = new Matrix();
  5834. Matrix.TransposeToRef(matrix, result);
  5835. return result;
  5836. };
  5837. /**
  5838. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5839. */
  5840. Matrix.TransposeToRef = function (matrix, result) {
  5841. result.m[0] = matrix.m[0];
  5842. result.m[1] = matrix.m[4];
  5843. result.m[2] = matrix.m[8];
  5844. result.m[3] = matrix.m[12];
  5845. result.m[4] = matrix.m[1];
  5846. result.m[5] = matrix.m[5];
  5847. result.m[6] = matrix.m[9];
  5848. result.m[7] = matrix.m[13];
  5849. result.m[8] = matrix.m[2];
  5850. result.m[9] = matrix.m[6];
  5851. result.m[10] = matrix.m[10];
  5852. result.m[11] = matrix.m[14];
  5853. result.m[12] = matrix.m[3];
  5854. result.m[13] = matrix.m[7];
  5855. result.m[14] = matrix.m[11];
  5856. result.m[15] = matrix.m[15];
  5857. };
  5858. /**
  5859. * Returns a new Matrix as the reflection matrix across the passed plane.
  5860. */
  5861. Matrix.Reflection = function (plane) {
  5862. var matrix = new Matrix();
  5863. Matrix.ReflectionToRef(plane, matrix);
  5864. return matrix;
  5865. };
  5866. /**
  5867. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5868. */
  5869. Matrix.ReflectionToRef = function (plane, result) {
  5870. plane.normalize();
  5871. var x = plane.normal.x;
  5872. var y = plane.normal.y;
  5873. var z = plane.normal.z;
  5874. var temp = -2 * x;
  5875. var temp2 = -2 * y;
  5876. var temp3 = -2 * z;
  5877. result.m[0] = (temp * x) + 1;
  5878. result.m[1] = temp2 * x;
  5879. result.m[2] = temp3 * x;
  5880. result.m[3] = 0.0;
  5881. result.m[4] = temp * y;
  5882. result.m[5] = (temp2 * y) + 1;
  5883. result.m[6] = temp3 * y;
  5884. result.m[7] = 0.0;
  5885. result.m[8] = temp * z;
  5886. result.m[9] = temp2 * z;
  5887. result.m[10] = (temp3 * z) + 1;
  5888. result.m[11] = 0.0;
  5889. result.m[12] = temp * plane.d;
  5890. result.m[13] = temp2 * plane.d;
  5891. result.m[14] = temp3 * plane.d;
  5892. result.m[15] = 1.0;
  5893. result._markAsUpdated();
  5894. };
  5895. /**
  5896. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5897. */
  5898. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5899. result.m[0] = xaxis.x;
  5900. result.m[1] = xaxis.y;
  5901. result.m[2] = xaxis.z;
  5902. result.m[3] = 0.0;
  5903. result.m[4] = yaxis.x;
  5904. result.m[5] = yaxis.y;
  5905. result.m[6] = yaxis.z;
  5906. result.m[7] = 0.0;
  5907. result.m[8] = zaxis.x;
  5908. result.m[9] = zaxis.y;
  5909. result.m[10] = zaxis.z;
  5910. result.m[11] = 0.0;
  5911. result.m[12] = 0.0;
  5912. result.m[13] = 0.0;
  5913. result.m[14] = 0.0;
  5914. result.m[15] = 1.0;
  5915. result._markAsUpdated();
  5916. };
  5917. /**
  5918. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5919. */
  5920. Matrix.FromQuaternionToRef = function (quat, result) {
  5921. var xx = quat.x * quat.x;
  5922. var yy = quat.y * quat.y;
  5923. var zz = quat.z * quat.z;
  5924. var xy = quat.x * quat.y;
  5925. var zw = quat.z * quat.w;
  5926. var zx = quat.z * quat.x;
  5927. var yw = quat.y * quat.w;
  5928. var yz = quat.y * quat.z;
  5929. var xw = quat.x * quat.w;
  5930. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5931. result.m[1] = 2.0 * (xy + zw);
  5932. result.m[2] = 2.0 * (zx - yw);
  5933. result.m[3] = 0.0;
  5934. result.m[4] = 2.0 * (xy - zw);
  5935. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5936. result.m[6] = 2.0 * (yz + xw);
  5937. result.m[7] = 0.0;
  5938. result.m[8] = 2.0 * (zx + yw);
  5939. result.m[9] = 2.0 * (yz - xw);
  5940. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5941. result.m[11] = 0.0;
  5942. result.m[12] = 0.0;
  5943. result.m[13] = 0.0;
  5944. result.m[14] = 0.0;
  5945. result.m[15] = 1.0;
  5946. result._markAsUpdated();
  5947. };
  5948. Matrix._tempQuaternion = new Quaternion();
  5949. Matrix._xAxis = Vector3.Zero();
  5950. Matrix._yAxis = Vector3.Zero();
  5951. Matrix._zAxis = Vector3.Zero();
  5952. Matrix._updateFlagSeed = 0;
  5953. Matrix._identityReadOnly = Matrix.Identity();
  5954. return Matrix;
  5955. }());
  5956. BABYLON.Matrix = Matrix;
  5957. var Plane = /** @class */ (function () {
  5958. /**
  5959. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5960. */
  5961. function Plane(a, b, c, d) {
  5962. this.normal = new Vector3(a, b, c);
  5963. this.d = d;
  5964. }
  5965. /**
  5966. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5967. */
  5968. Plane.prototype.asArray = function () {
  5969. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5970. };
  5971. // Methods
  5972. /**
  5973. * Returns a new plane copied from the current Plane.
  5974. */
  5975. Plane.prototype.clone = function () {
  5976. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5977. };
  5978. /**
  5979. * Returns the string "Plane".
  5980. */
  5981. Plane.prototype.getClassName = function () {
  5982. return "Plane";
  5983. };
  5984. /**
  5985. * Returns the Plane hash code.
  5986. */
  5987. Plane.prototype.getHashCode = function () {
  5988. var hash = this.normal.getHashCode();
  5989. hash = (hash * 397) ^ (this.d || 0);
  5990. return hash;
  5991. };
  5992. /**
  5993. * Normalize the current Plane in place.
  5994. * Returns the updated Plane.
  5995. */
  5996. Plane.prototype.normalize = function () {
  5997. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5998. var magnitude = 0.0;
  5999. if (norm !== 0) {
  6000. magnitude = 1.0 / norm;
  6001. }
  6002. this.normal.x *= magnitude;
  6003. this.normal.y *= magnitude;
  6004. this.normal.z *= magnitude;
  6005. this.d *= magnitude;
  6006. return this;
  6007. };
  6008. /**
  6009. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  6010. */
  6011. Plane.prototype.transform = function (transformation) {
  6012. var transposedMatrix = Matrix.Transpose(transformation);
  6013. var x = this.normal.x;
  6014. var y = this.normal.y;
  6015. var z = this.normal.z;
  6016. var d = this.d;
  6017. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6018. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6019. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6020. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6021. return new Plane(normalX, normalY, normalZ, finalD);
  6022. };
  6023. /**
  6024. * Returns the dot product (float) of the point coordinates and the plane normal.
  6025. */
  6026. Plane.prototype.dotCoordinate = function (point) {
  6027. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6028. };
  6029. /**
  6030. * Updates the current Plane from the plane defined by the three passed points.
  6031. * Returns the updated Plane.
  6032. */
  6033. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6034. var x1 = point2.x - point1.x;
  6035. var y1 = point2.y - point1.y;
  6036. var z1 = point2.z - point1.z;
  6037. var x2 = point3.x - point1.x;
  6038. var y2 = point3.y - point1.y;
  6039. var z2 = point3.z - point1.z;
  6040. var yz = (y1 * z2) - (z1 * y2);
  6041. var xz = (z1 * x2) - (x1 * z2);
  6042. var xy = (x1 * y2) - (y1 * x2);
  6043. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6044. var invPyth;
  6045. if (pyth !== 0) {
  6046. invPyth = 1.0 / pyth;
  6047. }
  6048. else {
  6049. invPyth = 0.0;
  6050. }
  6051. this.normal.x = yz * invPyth;
  6052. this.normal.y = xz * invPyth;
  6053. this.normal.z = xy * invPyth;
  6054. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6055. return this;
  6056. };
  6057. /**
  6058. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6059. */
  6060. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6061. var dot = Vector3.Dot(this.normal, direction);
  6062. return (dot <= epsilon);
  6063. };
  6064. /**
  6065. * Returns the signed distance (float) from the passed point to the Plane.
  6066. */
  6067. Plane.prototype.signedDistanceTo = function (point) {
  6068. return Vector3.Dot(point, this.normal) + this.d;
  6069. };
  6070. // Statics
  6071. /**
  6072. * Returns a new Plane from the passed array.
  6073. */
  6074. Plane.FromArray = function (array) {
  6075. return new Plane(array[0], array[1], array[2], array[3]);
  6076. };
  6077. /**
  6078. * Returns a new Plane defined by the three passed points.
  6079. */
  6080. Plane.FromPoints = function (point1, point2, point3) {
  6081. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6082. result.copyFromPoints(point1, point2, point3);
  6083. return result;
  6084. };
  6085. /**
  6086. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6087. * Note : the vector "normal" is updated because normalized.
  6088. */
  6089. Plane.FromPositionAndNormal = function (origin, normal) {
  6090. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6091. normal.normalize();
  6092. result.normal = normal;
  6093. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6094. return result;
  6095. };
  6096. /**
  6097. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6098. */
  6099. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6100. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6101. return Vector3.Dot(point, normal) + d;
  6102. };
  6103. return Plane;
  6104. }());
  6105. BABYLON.Plane = Plane;
  6106. var Viewport = /** @class */ (function () {
  6107. /**
  6108. * Creates a Viewport object located at (x, y) and sized (width, height).
  6109. */
  6110. function Viewport(x, y, width, height) {
  6111. this.x = x;
  6112. this.y = y;
  6113. this.width = width;
  6114. this.height = height;
  6115. }
  6116. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6117. if (renderWidthOrEngine.getRenderWidth) {
  6118. var engine = renderWidthOrEngine;
  6119. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6120. }
  6121. var renderWidth = renderWidthOrEngine;
  6122. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6123. };
  6124. /**
  6125. * Returns a new Viewport copied from the current one.
  6126. */
  6127. Viewport.prototype.clone = function () {
  6128. return new Viewport(this.x, this.y, this.width, this.height);
  6129. };
  6130. return Viewport;
  6131. }());
  6132. BABYLON.Viewport = Viewport;
  6133. var Frustum = /** @class */ (function () {
  6134. function Frustum() {
  6135. }
  6136. /**
  6137. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6138. */
  6139. Frustum.GetPlanes = function (transform) {
  6140. var frustumPlanes = [];
  6141. for (var index = 0; index < 6; index++) {
  6142. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6143. }
  6144. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6145. return frustumPlanes;
  6146. };
  6147. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6148. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6149. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6150. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6151. frustumPlane.d = transform.m[15] + transform.m[14];
  6152. frustumPlane.normalize();
  6153. };
  6154. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6155. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6156. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6157. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6158. frustumPlane.d = transform.m[15] - transform.m[14];
  6159. frustumPlane.normalize();
  6160. };
  6161. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6162. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6163. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6164. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6165. frustumPlane.d = transform.m[15] + transform.m[12];
  6166. frustumPlane.normalize();
  6167. };
  6168. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6169. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6170. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6171. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6172. frustumPlane.d = transform.m[15] - transform.m[12];
  6173. frustumPlane.normalize();
  6174. };
  6175. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6176. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6177. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6178. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6179. frustumPlane.d = transform.m[15] - transform.m[13];
  6180. frustumPlane.normalize();
  6181. };
  6182. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6183. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6184. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6185. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6186. frustumPlane.d = transform.m[15] + transform.m[13];
  6187. frustumPlane.normalize();
  6188. };
  6189. /**
  6190. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6191. */
  6192. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6193. // Near
  6194. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6195. // Far
  6196. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6197. // Left
  6198. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6199. // Right
  6200. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6201. // Top
  6202. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6203. // Bottom
  6204. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6205. };
  6206. return Frustum;
  6207. }());
  6208. BABYLON.Frustum = Frustum;
  6209. var Space;
  6210. (function (Space) {
  6211. Space[Space["LOCAL"] = 0] = "LOCAL";
  6212. Space[Space["WORLD"] = 1] = "WORLD";
  6213. Space[Space["BONE"] = 2] = "BONE";
  6214. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6215. var Axis = /** @class */ (function () {
  6216. function Axis() {
  6217. }
  6218. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6219. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6220. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6221. return Axis;
  6222. }());
  6223. BABYLON.Axis = Axis;
  6224. ;
  6225. var BezierCurve = /** @class */ (function () {
  6226. function BezierCurve() {
  6227. }
  6228. /**
  6229. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6230. */
  6231. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6232. // Extract X (which is equal to time here)
  6233. var f0 = 1 - 3 * x2 + 3 * x1;
  6234. var f1 = 3 * x2 - 6 * x1;
  6235. var f2 = 3 * x1;
  6236. var refinedT = t;
  6237. for (var i = 0; i < 5; i++) {
  6238. var refinedT2 = refinedT * refinedT;
  6239. var refinedT3 = refinedT2 * refinedT;
  6240. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6241. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6242. refinedT -= (x - t) * slope;
  6243. refinedT = Math.min(1, Math.max(0, refinedT));
  6244. }
  6245. // Resolve cubic bezier for the given x
  6246. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6247. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6248. Math.pow(refinedT, 3);
  6249. };
  6250. return BezierCurve;
  6251. }());
  6252. BABYLON.BezierCurve = BezierCurve;
  6253. var Orientation;
  6254. (function (Orientation) {
  6255. Orientation[Orientation["CW"] = 0] = "CW";
  6256. Orientation[Orientation["CCW"] = 1] = "CCW";
  6257. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6258. var Angle = /** @class */ (function () {
  6259. /**
  6260. * Creates an Angle object of "radians" radians (float).
  6261. */
  6262. function Angle(radians) {
  6263. var _this = this;
  6264. /**
  6265. * Returns the Angle value in degrees (float).
  6266. */
  6267. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6268. /**
  6269. * Returns the Angle value in radians (float).
  6270. */
  6271. this.radians = function () { return _this._radians; };
  6272. this._radians = radians;
  6273. if (this._radians < 0.0)
  6274. this._radians += (2.0 * Math.PI);
  6275. }
  6276. /**
  6277. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6278. */
  6279. Angle.BetweenTwoPoints = function (a, b) {
  6280. var delta = b.subtract(a);
  6281. var theta = Math.atan2(delta.y, delta.x);
  6282. return new Angle(theta);
  6283. };
  6284. /**
  6285. * Returns a new Angle object from the passed float in radians.
  6286. */
  6287. Angle.FromRadians = function (radians) {
  6288. return new Angle(radians);
  6289. };
  6290. /**
  6291. * Returns a new Angle object from the passed float in degrees.
  6292. */
  6293. Angle.FromDegrees = function (degrees) {
  6294. return new Angle(degrees * Math.PI / 180.0);
  6295. };
  6296. return Angle;
  6297. }());
  6298. BABYLON.Angle = Angle;
  6299. var Arc2 = /** @class */ (function () {
  6300. /**
  6301. * Creates an Arc object from the three passed points : start, middle and end.
  6302. */
  6303. function Arc2(startPoint, midPoint, endPoint) {
  6304. this.startPoint = startPoint;
  6305. this.midPoint = midPoint;
  6306. this.endPoint = endPoint;
  6307. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6308. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6309. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6310. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6311. 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);
  6312. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6313. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6314. var a1 = this.startAngle.degrees();
  6315. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6316. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6317. // angles correction
  6318. if (a2 - a1 > +180.0)
  6319. a2 -= 360.0;
  6320. if (a2 - a1 < -180.0)
  6321. a2 += 360.0;
  6322. if (a3 - a2 > +180.0)
  6323. a3 -= 360.0;
  6324. if (a3 - a2 < -180.0)
  6325. a3 += 360.0;
  6326. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6327. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6328. }
  6329. return Arc2;
  6330. }());
  6331. BABYLON.Arc2 = Arc2;
  6332. var Path2 = /** @class */ (function () {
  6333. /**
  6334. * Creates a Path2 object from the starting 2D coordinates x and y.
  6335. */
  6336. function Path2(x, y) {
  6337. this._points = new Array();
  6338. this._length = 0.0;
  6339. this.closed = false;
  6340. this._points.push(new Vector2(x, y));
  6341. }
  6342. /**
  6343. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6344. * Returns the updated Path2.
  6345. */
  6346. Path2.prototype.addLineTo = function (x, y) {
  6347. if (this.closed) {
  6348. return this;
  6349. }
  6350. var newPoint = new Vector2(x, y);
  6351. var previousPoint = this._points[this._points.length - 1];
  6352. this._points.push(newPoint);
  6353. this._length += newPoint.subtract(previousPoint).length();
  6354. return this;
  6355. };
  6356. /**
  6357. * 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.
  6358. * Returns the updated Path2.
  6359. */
  6360. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6361. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6362. if (this.closed) {
  6363. return this;
  6364. }
  6365. var startPoint = this._points[this._points.length - 1];
  6366. var midPoint = new Vector2(midX, midY);
  6367. var endPoint = new Vector2(endX, endY);
  6368. var arc = new Arc2(startPoint, midPoint, endPoint);
  6369. var increment = arc.angle.radians() / numberOfSegments;
  6370. if (arc.orientation === Orientation.CW)
  6371. increment *= -1;
  6372. var currentAngle = arc.startAngle.radians() + increment;
  6373. for (var i = 0; i < numberOfSegments; i++) {
  6374. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6375. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6376. this.addLineTo(x, y);
  6377. currentAngle += increment;
  6378. }
  6379. return this;
  6380. };
  6381. /**
  6382. * Closes the Path2.
  6383. * Returns the Path2.
  6384. */
  6385. Path2.prototype.close = function () {
  6386. this.closed = true;
  6387. return this;
  6388. };
  6389. /**
  6390. * Returns the Path2 total length (float).
  6391. */
  6392. Path2.prototype.length = function () {
  6393. var result = this._length;
  6394. if (!this.closed) {
  6395. var lastPoint = this._points[this._points.length - 1];
  6396. var firstPoint = this._points[0];
  6397. result += (firstPoint.subtract(lastPoint).length());
  6398. }
  6399. return result;
  6400. };
  6401. /**
  6402. * Returns the Path2 internal array of points.
  6403. */
  6404. Path2.prototype.getPoints = function () {
  6405. return this._points;
  6406. };
  6407. /**
  6408. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6409. */
  6410. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6411. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6412. return Vector2.Zero();
  6413. }
  6414. var lengthPosition = normalizedLengthPosition * this.length();
  6415. var previousOffset = 0;
  6416. for (var i = 0; i < this._points.length; i++) {
  6417. var j = (i + 1) % this._points.length;
  6418. var a = this._points[i];
  6419. var b = this._points[j];
  6420. var bToA = b.subtract(a);
  6421. var nextOffset = (bToA.length() + previousOffset);
  6422. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6423. var dir = bToA.normalize();
  6424. var localOffset = lengthPosition - previousOffset;
  6425. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6426. }
  6427. previousOffset = nextOffset;
  6428. }
  6429. return Vector2.Zero();
  6430. };
  6431. /**
  6432. * Returns a new Path2 starting at the coordinates (x, y).
  6433. */
  6434. Path2.StartingAt = function (x, y) {
  6435. return new Path2(x, y);
  6436. };
  6437. return Path2;
  6438. }());
  6439. BABYLON.Path2 = Path2;
  6440. var Path3D = /** @class */ (function () {
  6441. /**
  6442. * new Path3D(path, normal, raw)
  6443. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6444. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6445. * path : an array of Vector3, the curve axis of the Path3D
  6446. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6447. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6448. */
  6449. function Path3D(path, firstNormal, raw) {
  6450. if (firstNormal === void 0) { firstNormal = null; }
  6451. this.path = path;
  6452. this._curve = new Array();
  6453. this._distances = new Array();
  6454. this._tangents = new Array();
  6455. this._normals = new Array();
  6456. this._binormals = new Array();
  6457. for (var p = 0; p < path.length; p++) {
  6458. this._curve[p] = path[p].clone(); // hard copy
  6459. }
  6460. this._raw = raw || false;
  6461. this._compute(firstNormal);
  6462. }
  6463. /**
  6464. * Returns the Path3D array of successive Vector3 designing its curve.
  6465. */
  6466. Path3D.prototype.getCurve = function () {
  6467. return this._curve;
  6468. };
  6469. /**
  6470. * Returns an array populated with tangent vectors on each Path3D curve point.
  6471. */
  6472. Path3D.prototype.getTangents = function () {
  6473. return this._tangents;
  6474. };
  6475. /**
  6476. * Returns an array populated with normal vectors on each Path3D curve point.
  6477. */
  6478. Path3D.prototype.getNormals = function () {
  6479. return this._normals;
  6480. };
  6481. /**
  6482. * Returns an array populated with binormal vectors on each Path3D curve point.
  6483. */
  6484. Path3D.prototype.getBinormals = function () {
  6485. return this._binormals;
  6486. };
  6487. /**
  6488. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6489. */
  6490. Path3D.prototype.getDistances = function () {
  6491. return this._distances;
  6492. };
  6493. /**
  6494. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6495. * Returns the same object updated.
  6496. */
  6497. Path3D.prototype.update = function (path, firstNormal) {
  6498. if (firstNormal === void 0) { firstNormal = null; }
  6499. for (var p = 0; p < path.length; p++) {
  6500. this._curve[p].x = path[p].x;
  6501. this._curve[p].y = path[p].y;
  6502. this._curve[p].z = path[p].z;
  6503. }
  6504. this._compute(firstNormal);
  6505. return this;
  6506. };
  6507. // private function compute() : computes tangents, normals and binormals
  6508. Path3D.prototype._compute = function (firstNormal) {
  6509. var l = this._curve.length;
  6510. // first and last tangents
  6511. this._tangents[0] = this._getFirstNonNullVector(0);
  6512. if (!this._raw) {
  6513. this._tangents[0].normalize();
  6514. }
  6515. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6516. if (!this._raw) {
  6517. this._tangents[l - 1].normalize();
  6518. }
  6519. // normals and binormals at first point : arbitrary vector with _normalVector()
  6520. var tg0 = this._tangents[0];
  6521. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6522. this._normals[0] = pp0;
  6523. if (!this._raw) {
  6524. this._normals[0].normalize();
  6525. }
  6526. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6527. if (!this._raw) {
  6528. this._binormals[0].normalize();
  6529. }
  6530. this._distances[0] = 0.0;
  6531. // normals and binormals : next points
  6532. var prev; // previous vector (segment)
  6533. var cur; // current vector (segment)
  6534. var curTang; // current tangent
  6535. // previous normal
  6536. var prevBinor; // previous binormal
  6537. for (var i = 1; i < l; i++) {
  6538. // tangents
  6539. prev = this._getLastNonNullVector(i);
  6540. if (i < l - 1) {
  6541. cur = this._getFirstNonNullVector(i);
  6542. this._tangents[i] = prev.add(cur);
  6543. this._tangents[i].normalize();
  6544. }
  6545. this._distances[i] = this._distances[i - 1] + prev.length();
  6546. // normals and binormals
  6547. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6548. curTang = this._tangents[i];
  6549. prevBinor = this._binormals[i - 1];
  6550. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6551. if (!this._raw) {
  6552. this._normals[i].normalize();
  6553. }
  6554. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6555. if (!this._raw) {
  6556. this._binormals[i].normalize();
  6557. }
  6558. }
  6559. };
  6560. // private function getFirstNonNullVector(index)
  6561. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6562. Path3D.prototype._getFirstNonNullVector = function (index) {
  6563. var i = 1;
  6564. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6565. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6566. i++;
  6567. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6568. }
  6569. return nNVector;
  6570. };
  6571. // private function getLastNonNullVector(index)
  6572. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6573. Path3D.prototype._getLastNonNullVector = function (index) {
  6574. var i = 1;
  6575. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6576. while (nLVector.length() === 0 && index > i + 1) {
  6577. i++;
  6578. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6579. }
  6580. return nLVector;
  6581. };
  6582. // private function normalVector(v0, vt, va) :
  6583. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6584. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6585. Path3D.prototype._normalVector = function (v0, vt, va) {
  6586. var normal0;
  6587. var tgl = vt.length();
  6588. if (tgl === 0.0) {
  6589. tgl = 1.0;
  6590. }
  6591. if (va === undefined || va === null) {
  6592. var point;
  6593. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6594. point = new Vector3(0.0, -1.0, 0.0);
  6595. }
  6596. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6597. point = new Vector3(1.0, 0.0, 0.0);
  6598. }
  6599. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6600. point = new Vector3(0.0, 0.0, 1.0);
  6601. }
  6602. else {
  6603. point = Vector3.Zero();
  6604. }
  6605. normal0 = Vector3.Cross(vt, point);
  6606. }
  6607. else {
  6608. normal0 = Vector3.Cross(vt, va);
  6609. Vector3.CrossToRef(normal0, vt, normal0);
  6610. }
  6611. normal0.normalize();
  6612. return normal0;
  6613. };
  6614. return Path3D;
  6615. }());
  6616. BABYLON.Path3D = Path3D;
  6617. var Curve3 = /** @class */ (function () {
  6618. /**
  6619. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6620. * A Curve3 is designed from a series of successive Vector3.
  6621. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6622. */
  6623. function Curve3(points) {
  6624. this._length = 0.0;
  6625. this._points = points;
  6626. this._length = this._computeLength(points);
  6627. }
  6628. /**
  6629. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6630. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6631. * @param v1 (Vector3) the control point
  6632. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6633. * @param nbPoints (integer) the wanted number of points in the curve
  6634. */
  6635. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6636. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6637. var bez = new Array();
  6638. var equation = function (t, val0, val1, val2) {
  6639. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6640. return res;
  6641. };
  6642. for (var i = 0; i <= nbPoints; i++) {
  6643. 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)));
  6644. }
  6645. return new Curve3(bez);
  6646. };
  6647. /**
  6648. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6649. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6650. * @param v1 (Vector3) the first control point
  6651. * @param v2 (Vector3) the second control point
  6652. * @param v3 (Vector3) the end point of the Cubic Bezier
  6653. * @param nbPoints (integer) the wanted number of points in the curve
  6654. */
  6655. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6656. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6657. var bez = new Array();
  6658. var equation = function (t, val0, val1, val2, val3) {
  6659. 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;
  6660. return res;
  6661. };
  6662. for (var i = 0; i <= nbPoints; i++) {
  6663. 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)));
  6664. }
  6665. return new Curve3(bez);
  6666. };
  6667. /**
  6668. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6669. * @param p1 (Vector3) the origin point of the Hermite Spline
  6670. * @param t1 (Vector3) the tangent vector at the origin point
  6671. * @param p2 (Vector3) the end point of the Hermite Spline
  6672. * @param t2 (Vector3) the tangent vector at the end point
  6673. * @param nbPoints (integer) the wanted number of points in the curve
  6674. */
  6675. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6676. var hermite = new Array();
  6677. var step = 1.0 / nbPoints;
  6678. for (var i = 0; i <= nbPoints; i++) {
  6679. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6680. }
  6681. return new Curve3(hermite);
  6682. };
  6683. /**
  6684. * Returns a Curve3 object along a CatmullRom Spline curve :
  6685. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6686. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6687. */
  6688. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6689. var totalPoints = new Array();
  6690. totalPoints.push(points[0].clone());
  6691. Array.prototype.push.apply(totalPoints, points);
  6692. totalPoints.push(points[points.length - 1].clone());
  6693. var catmullRom = new Array();
  6694. var step = 1.0 / nbPoints;
  6695. var amount = 0.0;
  6696. for (var i = 0; i < totalPoints.length - 3; i++) {
  6697. amount = 0;
  6698. for (var c = 0; c < nbPoints; c++) {
  6699. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6700. amount += step;
  6701. }
  6702. }
  6703. i--;
  6704. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6705. return new Curve3(catmullRom);
  6706. };
  6707. /**
  6708. * Returns the Curve3 stored array of successive Vector3
  6709. */
  6710. Curve3.prototype.getPoints = function () {
  6711. return this._points;
  6712. };
  6713. /**
  6714. * Returns the computed length (float) of the curve.
  6715. */
  6716. Curve3.prototype.length = function () {
  6717. return this._length;
  6718. };
  6719. /**
  6720. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6721. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6722. * curveA and curveB keep unchanged.
  6723. */
  6724. Curve3.prototype.continue = function (curve) {
  6725. var lastPoint = this._points[this._points.length - 1];
  6726. var continuedPoints = this._points.slice();
  6727. var curvePoints = curve.getPoints();
  6728. for (var i = 1; i < curvePoints.length; i++) {
  6729. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6730. }
  6731. var continuedCurve = new Curve3(continuedPoints);
  6732. return continuedCurve;
  6733. };
  6734. Curve3.prototype._computeLength = function (path) {
  6735. var l = 0;
  6736. for (var i = 1; i < path.length; i++) {
  6737. l += (path[i].subtract(path[i - 1])).length();
  6738. }
  6739. return l;
  6740. };
  6741. return Curve3;
  6742. }());
  6743. BABYLON.Curve3 = Curve3;
  6744. // Vertex formats
  6745. var PositionNormalVertex = /** @class */ (function () {
  6746. function PositionNormalVertex(position, normal) {
  6747. if (position === void 0) { position = Vector3.Zero(); }
  6748. if (normal === void 0) { normal = Vector3.Up(); }
  6749. this.position = position;
  6750. this.normal = normal;
  6751. }
  6752. PositionNormalVertex.prototype.clone = function () {
  6753. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6754. };
  6755. return PositionNormalVertex;
  6756. }());
  6757. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6758. var PositionNormalTextureVertex = /** @class */ (function () {
  6759. function PositionNormalTextureVertex(position, normal, uv) {
  6760. if (position === void 0) { position = Vector3.Zero(); }
  6761. if (normal === void 0) { normal = Vector3.Up(); }
  6762. if (uv === void 0) { uv = Vector2.Zero(); }
  6763. this.position = position;
  6764. this.normal = normal;
  6765. this.uv = uv;
  6766. }
  6767. PositionNormalTextureVertex.prototype.clone = function () {
  6768. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6769. };
  6770. return PositionNormalTextureVertex;
  6771. }());
  6772. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6773. // Temporary pre-allocated objects for engine internal use
  6774. // usage in any internal function :
  6775. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6776. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6777. var Tmp = /** @class */ (function () {
  6778. function Tmp() {
  6779. }
  6780. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6781. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6782. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6783. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6784. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6785. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6786. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6787. Matrix.Zero(), Matrix.Zero(),
  6788. Matrix.Zero(), Matrix.Zero(),
  6789. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6790. return Tmp;
  6791. }());
  6792. BABYLON.Tmp = Tmp;
  6793. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6794. var MathTmp = /** @class */ (function () {
  6795. function MathTmp() {
  6796. }
  6797. MathTmp.Vector3 = [Vector3.Zero()];
  6798. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6799. MathTmp.Quaternion = [Quaternion.Zero()];
  6800. return MathTmp;
  6801. }());
  6802. })(BABYLON || (BABYLON = {}));
  6803. //# sourceMappingURL=babylon.math.js.map
  6804. var BABYLON;
  6805. (function (BABYLON) {
  6806. var Scalar = /** @class */ (function () {
  6807. function Scalar() {
  6808. }
  6809. /**
  6810. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6811. */
  6812. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6813. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6814. var num = a - b;
  6815. return -epsilon <= num && num <= epsilon;
  6816. };
  6817. /**
  6818. * Returns a string : the upper case translation of the number i to hexadecimal.
  6819. */
  6820. Scalar.ToHex = function (i) {
  6821. var str = i.toString(16);
  6822. if (i <= 15) {
  6823. return ("0" + str).toUpperCase();
  6824. }
  6825. return str.toUpperCase();
  6826. };
  6827. /**
  6828. * Returns -1 if value is negative and +1 is value is positive.
  6829. * Returns the value itself if it's equal to zero.
  6830. */
  6831. Scalar.Sign = function (value) {
  6832. value = +value; // convert to a number
  6833. if (value === 0 || isNaN(value))
  6834. return value;
  6835. return value > 0 ? 1 : -1;
  6836. };
  6837. /**
  6838. * Returns the value itself if it's between min and max.
  6839. * Returns min if the value is lower than min.
  6840. * Returns max if the value is greater than max.
  6841. */
  6842. Scalar.Clamp = function (value, min, max) {
  6843. if (min === void 0) { min = 0; }
  6844. if (max === void 0) { max = 1; }
  6845. return Math.min(max, Math.max(min, value));
  6846. };
  6847. /**
  6848. * Returns the log2 of value.
  6849. */
  6850. Scalar.Log2 = function (value) {
  6851. return Math.log(value) * Math.LOG2E;
  6852. };
  6853. /**
  6854. * Loops the value, so that it is never larger than length and never smaller than 0.
  6855. *
  6856. * This is similar to the modulo operator but it works with floating point numbers.
  6857. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6858. * With t = 5 and length = 2.5, the result would be 0.0.
  6859. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6860. */
  6861. Scalar.Repeat = function (value, length) {
  6862. return value - Math.floor(value / length) * length;
  6863. };
  6864. /**
  6865. * Normalize the value between 0.0 and 1.0 using min and max values
  6866. */
  6867. Scalar.Normalize = function (value, min, max) {
  6868. return (value - min) / (max - min);
  6869. };
  6870. /**
  6871. * Denormalize the value from 0.0 and 1.0 using min and max values
  6872. */
  6873. Scalar.Denormalize = function (normalized, min, max) {
  6874. return (normalized * (max - min) + min);
  6875. };
  6876. /**
  6877. * Calculates the shortest difference between two given angles given in degrees.
  6878. */
  6879. Scalar.DeltaAngle = function (current, target) {
  6880. var num = Scalar.Repeat(target - current, 360.0);
  6881. if (num > 180.0) {
  6882. num -= 360.0;
  6883. }
  6884. return num;
  6885. };
  6886. /**
  6887. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6888. *
  6889. * The returned value will move back and forth between 0 and length
  6890. */
  6891. Scalar.PingPong = function (tx, length) {
  6892. var t = Scalar.Repeat(tx, length * 2.0);
  6893. return length - Math.abs(t - length);
  6894. };
  6895. /**
  6896. * Interpolates between min and max with smoothing at the limits.
  6897. *
  6898. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6899. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6900. */
  6901. Scalar.SmoothStep = function (from, to, tx) {
  6902. var t = Scalar.Clamp(tx);
  6903. t = -2.0 * t * t * t + 3.0 * t * t;
  6904. return to * t + from * (1.0 - t);
  6905. };
  6906. /**
  6907. * Moves a value current towards target.
  6908. *
  6909. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6910. * Negative values of maxDelta pushes the value away from target.
  6911. */
  6912. Scalar.MoveTowards = function (current, target, maxDelta) {
  6913. var result = 0;
  6914. if (Math.abs(target - current) <= maxDelta) {
  6915. result = target;
  6916. }
  6917. else {
  6918. result = current + Scalar.Sign(target - current) * maxDelta;
  6919. }
  6920. return result;
  6921. };
  6922. /**
  6923. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6924. *
  6925. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6926. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6927. */
  6928. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6929. var num = Scalar.DeltaAngle(current, target);
  6930. var result = 0;
  6931. if (-maxDelta < num && num < maxDelta) {
  6932. result = target;
  6933. }
  6934. else {
  6935. target = current + num;
  6936. result = Scalar.MoveTowards(current, target, maxDelta);
  6937. }
  6938. return result;
  6939. };
  6940. /**
  6941. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6942. */
  6943. Scalar.Lerp = function (start, end, amount) {
  6944. return start + ((end - start) * amount);
  6945. };
  6946. /**
  6947. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6948. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6949. */
  6950. Scalar.LerpAngle = function (start, end, amount) {
  6951. var num = Scalar.Repeat(end - start, 360.0);
  6952. if (num > 180.0) {
  6953. num -= 360.0;
  6954. }
  6955. return start + num * Scalar.Clamp(amount);
  6956. };
  6957. /**
  6958. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6959. */
  6960. Scalar.InverseLerp = function (a, b, value) {
  6961. var result = 0;
  6962. if (a != b) {
  6963. result = Scalar.Clamp((value - a) / (b - a));
  6964. }
  6965. else {
  6966. result = 0.0;
  6967. }
  6968. return result;
  6969. };
  6970. /**
  6971. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6972. */
  6973. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6974. var squared = amount * amount;
  6975. var cubed = amount * squared;
  6976. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6977. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6978. var part3 = (cubed - (2.0 * squared)) + amount;
  6979. var part4 = cubed - squared;
  6980. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6981. };
  6982. /**
  6983. * Returns a random float number between and min and max values
  6984. */
  6985. Scalar.RandomRange = function (min, max) {
  6986. if (min === max)
  6987. return min;
  6988. return ((Math.random() * (max - min)) + min);
  6989. };
  6990. /**
  6991. * This function returns percentage of a number in a given range.
  6992. *
  6993. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6994. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6995. */
  6996. Scalar.RangeToPercent = function (number, min, max) {
  6997. return ((number - min) / (max - min));
  6998. };
  6999. /**
  7000. * This function returns number that corresponds to the percentage in a given range.
  7001. *
  7002. * PercentToRange(0.34,0,100) will return 34.
  7003. */
  7004. Scalar.PercentToRange = function (percent, min, max) {
  7005. return ((max - min) * percent + min);
  7006. };
  7007. /**
  7008. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7009. * @param angle The angle to normalize in radian.
  7010. * @return The converted angle.
  7011. */
  7012. Scalar.NormalizeRadians = function (angle) {
  7013. // More precise but slower version kept for reference.
  7014. // angle = angle % Tools.TwoPi;
  7015. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7016. //if (angle > Math.PI) {
  7017. // angle -= Tools.TwoPi;
  7018. //}
  7019. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7020. return angle;
  7021. };
  7022. /**
  7023. * Two pi constants convenient for computation.
  7024. */
  7025. Scalar.TwoPi = Math.PI * 2;
  7026. return Scalar;
  7027. }());
  7028. BABYLON.Scalar = Scalar;
  7029. })(BABYLON || (BABYLON = {}));
  7030. //# sourceMappingURL=babylon.math.scalar.js.map
  7031. //# sourceMappingURL=babylon.mixins.js.map
  7032. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7033. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7034. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7035. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7036. //# sourceMappingURL=babylon.webgl2.js.map
  7037. var BABYLON;
  7038. (function (BABYLON) {
  7039. var __decoratorInitialStore = {};
  7040. var __mergedStore = {};
  7041. var _copySource = function (creationFunction, source, instanciate) {
  7042. var destination = creationFunction();
  7043. // Tags
  7044. if (BABYLON.Tags) {
  7045. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7046. }
  7047. var classStore = getMergedStore(destination);
  7048. // Properties
  7049. for (var property in classStore) {
  7050. var propertyDescriptor = classStore[property];
  7051. var sourceProperty = source[property];
  7052. var propertyType = propertyDescriptor.type;
  7053. if (sourceProperty !== undefined && sourceProperty !== null) {
  7054. switch (propertyType) {
  7055. case 0: // Value
  7056. case 6:// Mesh reference
  7057. destination[property] = sourceProperty;
  7058. break;
  7059. case 1:// Texture
  7060. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7061. break;
  7062. case 2: // Color3
  7063. case 3: // FresnelParameters
  7064. case 4: // Vector2
  7065. case 5: // Vector3
  7066. case 7: // Color Curves
  7067. case 10:// Quaternion
  7068. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7069. break;
  7070. }
  7071. }
  7072. }
  7073. return destination;
  7074. };
  7075. function getDirectStore(target) {
  7076. var classKey = target.getClassName();
  7077. if (!__decoratorInitialStore[classKey]) {
  7078. __decoratorInitialStore[classKey] = {};
  7079. }
  7080. return __decoratorInitialStore[classKey];
  7081. }
  7082. /**
  7083. * Return the list of properties flagged as serializable
  7084. * @param target: host object
  7085. */
  7086. function getMergedStore(target) {
  7087. var classKey = target.getClassName();
  7088. if (__mergedStore[classKey]) {
  7089. return __mergedStore[classKey];
  7090. }
  7091. __mergedStore[classKey] = {};
  7092. var store = __mergedStore[classKey];
  7093. var currentTarget = target;
  7094. var currentKey = classKey;
  7095. while (currentKey) {
  7096. var initialStore = __decoratorInitialStore[currentKey];
  7097. for (var property in initialStore) {
  7098. store[property] = initialStore[property];
  7099. }
  7100. var parent_1 = void 0;
  7101. var done = false;
  7102. do {
  7103. parent_1 = Object.getPrototypeOf(currentTarget);
  7104. if (!parent_1.getClassName) {
  7105. done = true;
  7106. break;
  7107. }
  7108. if (parent_1.getClassName() !== currentKey) {
  7109. break;
  7110. }
  7111. currentTarget = parent_1;
  7112. } while (parent_1);
  7113. if (done) {
  7114. break;
  7115. }
  7116. currentKey = parent_1.getClassName();
  7117. currentTarget = parent_1;
  7118. }
  7119. return store;
  7120. }
  7121. function generateSerializableMember(type, sourceName) {
  7122. return function (target, propertyKey) {
  7123. var classStore = getDirectStore(target);
  7124. if (!classStore[propertyKey]) {
  7125. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7126. }
  7127. };
  7128. }
  7129. function generateExpandMember(setCallback, targetKey) {
  7130. if (targetKey === void 0) { targetKey = null; }
  7131. return function (target, propertyKey) {
  7132. var key = targetKey || ("_" + propertyKey);
  7133. Object.defineProperty(target, propertyKey, {
  7134. get: function () {
  7135. return this[key];
  7136. },
  7137. set: function (value) {
  7138. if (this[key] === value) {
  7139. return;
  7140. }
  7141. this[key] = value;
  7142. target[setCallback].apply(this);
  7143. },
  7144. enumerable: true,
  7145. configurable: true
  7146. });
  7147. };
  7148. }
  7149. function expandToProperty(callback, targetKey) {
  7150. if (targetKey === void 0) { targetKey = null; }
  7151. return generateExpandMember(callback, targetKey);
  7152. }
  7153. BABYLON.expandToProperty = expandToProperty;
  7154. function serialize(sourceName) {
  7155. return generateSerializableMember(0, sourceName); // value member
  7156. }
  7157. BABYLON.serialize = serialize;
  7158. function serializeAsTexture(sourceName) {
  7159. return generateSerializableMember(1, sourceName); // texture member
  7160. }
  7161. BABYLON.serializeAsTexture = serializeAsTexture;
  7162. function serializeAsColor3(sourceName) {
  7163. return generateSerializableMember(2, sourceName); // color3 member
  7164. }
  7165. BABYLON.serializeAsColor3 = serializeAsColor3;
  7166. function serializeAsFresnelParameters(sourceName) {
  7167. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7168. }
  7169. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7170. function serializeAsVector2(sourceName) {
  7171. return generateSerializableMember(4, sourceName); // vector2 member
  7172. }
  7173. BABYLON.serializeAsVector2 = serializeAsVector2;
  7174. function serializeAsVector3(sourceName) {
  7175. return generateSerializableMember(5, sourceName); // vector3 member
  7176. }
  7177. BABYLON.serializeAsVector3 = serializeAsVector3;
  7178. function serializeAsMeshReference(sourceName) {
  7179. return generateSerializableMember(6, sourceName); // mesh reference member
  7180. }
  7181. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7182. function serializeAsColorCurves(sourceName) {
  7183. return generateSerializableMember(7, sourceName); // color curves
  7184. }
  7185. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7186. function serializeAsColor4(sourceName) {
  7187. return generateSerializableMember(8, sourceName); // color 4
  7188. }
  7189. BABYLON.serializeAsColor4 = serializeAsColor4;
  7190. function serializeAsImageProcessingConfiguration(sourceName) {
  7191. return generateSerializableMember(9, sourceName); // image processing
  7192. }
  7193. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7194. function serializeAsQuaternion(sourceName) {
  7195. return generateSerializableMember(10, sourceName); // quaternion member
  7196. }
  7197. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7198. var SerializationHelper = /** @class */ (function () {
  7199. function SerializationHelper() {
  7200. }
  7201. SerializationHelper.Serialize = function (entity, serializationObject) {
  7202. if (!serializationObject) {
  7203. serializationObject = {};
  7204. }
  7205. // Tags
  7206. if (BABYLON.Tags) {
  7207. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7208. }
  7209. var serializedProperties = getMergedStore(entity);
  7210. // Properties
  7211. for (var property in serializedProperties) {
  7212. var propertyDescriptor = serializedProperties[property];
  7213. var targetPropertyName = propertyDescriptor.sourceName || property;
  7214. var propertyType = propertyDescriptor.type;
  7215. var sourceProperty = entity[property];
  7216. if (sourceProperty !== undefined && sourceProperty !== null) {
  7217. switch (propertyType) {
  7218. case 0:// Value
  7219. serializationObject[targetPropertyName] = sourceProperty;
  7220. break;
  7221. case 1:// Texture
  7222. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7223. break;
  7224. case 2:// Color3
  7225. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7226. break;
  7227. case 3:// FresnelParameters
  7228. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7229. break;
  7230. case 4:// Vector2
  7231. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7232. break;
  7233. case 5:// Vector3
  7234. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7235. break;
  7236. case 6:// Mesh reference
  7237. serializationObject[targetPropertyName] = sourceProperty.id;
  7238. break;
  7239. case 7:// Color Curves
  7240. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7241. break;
  7242. case 8:// Color 4
  7243. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7244. break;
  7245. case 9:// Image Processing
  7246. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7247. break;
  7248. }
  7249. }
  7250. }
  7251. return serializationObject;
  7252. };
  7253. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7254. if (rootUrl === void 0) { rootUrl = null; }
  7255. var destination = creationFunction();
  7256. if (!rootUrl) {
  7257. rootUrl = "";
  7258. }
  7259. // Tags
  7260. if (BABYLON.Tags) {
  7261. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7262. }
  7263. var classStore = getMergedStore(destination);
  7264. // Properties
  7265. for (var property in classStore) {
  7266. var propertyDescriptor = classStore[property];
  7267. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7268. var propertyType = propertyDescriptor.type;
  7269. if (sourceProperty !== undefined && sourceProperty !== null) {
  7270. var dest = destination;
  7271. switch (propertyType) {
  7272. case 0:// Value
  7273. dest[property] = sourceProperty;
  7274. break;
  7275. case 1:// Texture
  7276. if (scene) {
  7277. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7278. }
  7279. break;
  7280. case 2:// Color3
  7281. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7282. break;
  7283. case 3:// FresnelParameters
  7284. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7285. break;
  7286. case 4:// Vector2
  7287. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7288. break;
  7289. case 5:// Vector3
  7290. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7291. break;
  7292. case 6:// Mesh reference
  7293. if (scene) {
  7294. dest[property] = scene.getLastMeshByID(sourceProperty);
  7295. }
  7296. break;
  7297. case 7:// Color Curves
  7298. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7299. break;
  7300. case 8:// Color 4
  7301. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7302. break;
  7303. case 9:// Image Processing
  7304. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7305. break;
  7306. }
  7307. }
  7308. }
  7309. return destination;
  7310. };
  7311. SerializationHelper.Clone = function (creationFunction, source) {
  7312. return _copySource(creationFunction, source, false);
  7313. };
  7314. SerializationHelper.Instanciate = function (creationFunction, source) {
  7315. return _copySource(creationFunction, source, true);
  7316. };
  7317. return SerializationHelper;
  7318. }());
  7319. BABYLON.SerializationHelper = SerializationHelper;
  7320. })(BABYLON || (BABYLON = {}));
  7321. //# sourceMappingURL=babylon.decorators.js.map
  7322. var BABYLON;
  7323. (function (BABYLON) {
  7324. /**
  7325. * Wrapper class for promise with external resolve and reject.
  7326. */
  7327. var Deferred = /** @class */ (function () {
  7328. /**
  7329. * Constructor for this deferred object.
  7330. */
  7331. function Deferred() {
  7332. var _this = this;
  7333. this.promise = new Promise(function (resolve, reject) {
  7334. _this._resolve = resolve;
  7335. _this._reject = reject;
  7336. });
  7337. }
  7338. Object.defineProperty(Deferred.prototype, "resolve", {
  7339. /**
  7340. * The resolve method of the promise associated with this deferred object.
  7341. */
  7342. get: function () {
  7343. return this._resolve;
  7344. },
  7345. enumerable: true,
  7346. configurable: true
  7347. });
  7348. Object.defineProperty(Deferred.prototype, "reject", {
  7349. /**
  7350. * The reject method of the promise associated with this deferred object.
  7351. */
  7352. get: function () {
  7353. return this._reject;
  7354. },
  7355. enumerable: true,
  7356. configurable: true
  7357. });
  7358. return Deferred;
  7359. }());
  7360. BABYLON.Deferred = Deferred;
  7361. })(BABYLON || (BABYLON = {}));
  7362. //# sourceMappingURL=babylon.deferred.js.map
  7363. var BABYLON;
  7364. (function (BABYLON) {
  7365. /**
  7366. * A class serves as a medium between the observable and its observers
  7367. */
  7368. var EventState = /** @class */ (function () {
  7369. /**
  7370. * Create a new EventState
  7371. * @param mask defines the mask associated with this state
  7372. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7373. * @param target defines the original target of the state
  7374. * @param currentTarget defines the current target of the state
  7375. */
  7376. function EventState(mask, skipNextObservers, target, currentTarget) {
  7377. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7378. this.initalize(mask, skipNextObservers, target, currentTarget);
  7379. }
  7380. /**
  7381. * Initialize the current event state
  7382. * @param mask defines the mask associated with this state
  7383. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7384. * @param target defines the original target of the state
  7385. * @param currentTarget defines the current target of the state
  7386. * @returns the current event state
  7387. */
  7388. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7389. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7390. this.mask = mask;
  7391. this.skipNextObservers = skipNextObservers;
  7392. this.target = target;
  7393. this.currentTarget = currentTarget;
  7394. return this;
  7395. };
  7396. return EventState;
  7397. }());
  7398. BABYLON.EventState = EventState;
  7399. /**
  7400. * Represent an Observer registered to a given Observable object.
  7401. */
  7402. var Observer = /** @class */ (function () {
  7403. /**
  7404. * Creates a new observer
  7405. * @param callback defines the callback to call when the observer is notified
  7406. * @param mask defines the mask of the observer (used to filter notifications)
  7407. * @param scope defines the current scope used to restore the JS context
  7408. */
  7409. function Observer(
  7410. /**
  7411. * Defines the callback to call when the observer is notified
  7412. */
  7413. callback,
  7414. /**
  7415. * Defines the mask of the observer (used to filter notifications)
  7416. */
  7417. mask,
  7418. /**
  7419. * Defines the current scope used to restore the JS context
  7420. */
  7421. scope) {
  7422. if (scope === void 0) { scope = null; }
  7423. this.callback = callback;
  7424. this.mask = mask;
  7425. this.scope = scope;
  7426. /** @ignore */
  7427. this._willBeUnregistered = false;
  7428. /**
  7429. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7430. */
  7431. this.unregisterOnNextCall = false;
  7432. }
  7433. return Observer;
  7434. }());
  7435. BABYLON.Observer = Observer;
  7436. /**
  7437. * Represent a list of observers registered to multiple Observables object.
  7438. */
  7439. var MultiObserver = /** @class */ (function () {
  7440. function MultiObserver() {
  7441. }
  7442. /**
  7443. * Release associated resources
  7444. */
  7445. MultiObserver.prototype.dispose = function () {
  7446. if (this._observers && this._observables) {
  7447. for (var index = 0; index < this._observers.length; index++) {
  7448. this._observables[index].remove(this._observers[index]);
  7449. }
  7450. }
  7451. this._observers = null;
  7452. this._observables = null;
  7453. };
  7454. /**
  7455. * Raise a callback when one of the observable will notify
  7456. * @param observables defines a list of observables to watch
  7457. * @param callback defines the callback to call on notification
  7458. * @param mask defines the mask used to filter notifications
  7459. * @param scope defines the current scope used to restore the JS context
  7460. * @returns the new MultiObserver
  7461. */
  7462. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7463. if (mask === void 0) { mask = -1; }
  7464. if (scope === void 0) { scope = null; }
  7465. var result = new MultiObserver();
  7466. result._observers = new Array();
  7467. result._observables = observables;
  7468. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7469. var observable = observables_1[_i];
  7470. var observer = observable.add(callback, mask, false, scope);
  7471. if (observer) {
  7472. result._observers.push(observer);
  7473. }
  7474. }
  7475. return result;
  7476. };
  7477. return MultiObserver;
  7478. }());
  7479. BABYLON.MultiObserver = MultiObserver;
  7480. /**
  7481. * The Observable class is a simple implementation of the Observable pattern.
  7482. * 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.
  7483. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7484. * 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).
  7485. * 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.
  7486. */
  7487. var Observable = /** @class */ (function () {
  7488. /**
  7489. * Creates a new observable
  7490. * @param onObserverAdded defines a callback to call when a new observer is added
  7491. */
  7492. function Observable(onObserverAdded) {
  7493. this._observers = new Array();
  7494. this._eventState = new EventState(0);
  7495. if (onObserverAdded) {
  7496. this._onObserverAdded = onObserverAdded;
  7497. }
  7498. }
  7499. /**
  7500. * Create a new Observer with the specified callback
  7501. * @param callback the callback that will be executed for that Observer
  7502. * @param mask the mask used to filter observers
  7503. * @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.
  7504. * @param scope optional scope for the callback to be called from
  7505. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7506. * @returns the new observer created for the callback
  7507. */
  7508. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7509. if (mask === void 0) { mask = -1; }
  7510. if (insertFirst === void 0) { insertFirst = false; }
  7511. if (scope === void 0) { scope = null; }
  7512. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7513. if (!callback) {
  7514. return null;
  7515. }
  7516. var observer = new Observer(callback, mask, scope);
  7517. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7518. if (insertFirst) {
  7519. this._observers.unshift(observer);
  7520. }
  7521. else {
  7522. this._observers.push(observer);
  7523. }
  7524. if (this._onObserverAdded) {
  7525. this._onObserverAdded(observer);
  7526. }
  7527. return observer;
  7528. };
  7529. /**
  7530. * Remove an Observer from the Observable object
  7531. * @param observer the instance of the Observer to remove
  7532. * @returns false if it doesn't belong to this Observable
  7533. */
  7534. Observable.prototype.remove = function (observer) {
  7535. if (!observer) {
  7536. return false;
  7537. }
  7538. var index = this._observers.indexOf(observer);
  7539. if (index !== -1) {
  7540. this._observers.splice(index, 1);
  7541. return true;
  7542. }
  7543. return false;
  7544. };
  7545. /**
  7546. * Remove a callback from the Observable object
  7547. * @param callback the callback to remove
  7548. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7549. * @returns false if it doesn't belong to this Observable
  7550. */
  7551. Observable.prototype.removeCallback = function (callback, scope) {
  7552. for (var index = 0; index < this._observers.length; index++) {
  7553. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7554. this._observers.splice(index, 1);
  7555. return true;
  7556. }
  7557. }
  7558. return false;
  7559. };
  7560. Observable.prototype._deferUnregister = function (observer) {
  7561. var _this = this;
  7562. observer.unregisterOnNextCall = false;
  7563. observer._willBeUnregistered = true;
  7564. BABYLON.Tools.SetImmediate(function () {
  7565. _this.remove(observer);
  7566. });
  7567. };
  7568. /**
  7569. * Notify all Observers by calling their respective callback with the given data
  7570. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7571. * @param eventData defines the data to send to all observers
  7572. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7573. * @param target defines the original target of the state
  7574. * @param currentTarget defines the current target of the state
  7575. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7576. */
  7577. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7578. if (mask === void 0) { mask = -1; }
  7579. if (!this._observers.length) {
  7580. return true;
  7581. }
  7582. var state = this._eventState;
  7583. state.mask = mask;
  7584. state.target = target;
  7585. state.currentTarget = currentTarget;
  7586. state.skipNextObservers = false;
  7587. state.lastReturnValue = eventData;
  7588. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7589. var obs = _a[_i];
  7590. if (obs._willBeUnregistered) {
  7591. continue;
  7592. }
  7593. if (obs.mask & mask) {
  7594. if (obs.scope) {
  7595. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7596. }
  7597. else {
  7598. state.lastReturnValue = obs.callback(eventData, state);
  7599. }
  7600. if (obs.unregisterOnNextCall) {
  7601. this._deferUnregister(obs);
  7602. }
  7603. }
  7604. if (state.skipNextObservers) {
  7605. return false;
  7606. }
  7607. }
  7608. return true;
  7609. };
  7610. /**
  7611. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7612. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7613. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7614. * and it is crucial that all callbacks will be executed.
  7615. * The order of the callbacks is kept, callbacks are not executed parallel.
  7616. *
  7617. * @param eventData The data to be sent to each callback
  7618. * @param mask is used to filter observers defaults to -1
  7619. * @param target defines the callback target (see EventState)
  7620. * @param currentTarget defines he current object in the bubbling phase
  7621. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7622. */
  7623. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7624. var _this = this;
  7625. if (mask === void 0) { mask = -1; }
  7626. // create an empty promise
  7627. var p = Promise.resolve(eventData);
  7628. // no observers? return this promise.
  7629. if (!this._observers.length) {
  7630. return p;
  7631. }
  7632. var state = this._eventState;
  7633. state.mask = mask;
  7634. state.target = target;
  7635. state.currentTarget = currentTarget;
  7636. state.skipNextObservers = false;
  7637. // execute one callback after another (not using Promise.all, the order is important)
  7638. this._observers.forEach(function (obs) {
  7639. if (state.skipNextObservers) {
  7640. return;
  7641. }
  7642. if (obs._willBeUnregistered) {
  7643. return;
  7644. }
  7645. if (obs.mask & mask) {
  7646. if (obs.scope) {
  7647. p = p.then(function (lastReturnedValue) {
  7648. state.lastReturnValue = lastReturnedValue;
  7649. return obs.callback.apply(obs.scope, [eventData, state]);
  7650. });
  7651. }
  7652. else {
  7653. p = p.then(function (lastReturnedValue) {
  7654. state.lastReturnValue = lastReturnedValue;
  7655. return obs.callback(eventData, state);
  7656. });
  7657. }
  7658. if (obs.unregisterOnNextCall) {
  7659. _this._deferUnregister(obs);
  7660. }
  7661. }
  7662. });
  7663. // return the eventData
  7664. return p.then(function () { return eventData; });
  7665. };
  7666. /**
  7667. * Notify a specific observer
  7668. * @param observer defines the observer to notify
  7669. * @param eventData defines the data to be sent to each callback
  7670. * @param mask is used to filter observers defaults to -1
  7671. */
  7672. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7673. if (mask === void 0) { mask = -1; }
  7674. var state = this._eventState;
  7675. state.mask = mask;
  7676. state.skipNextObservers = false;
  7677. observer.callback(eventData, state);
  7678. };
  7679. /**
  7680. * Gets a boolean indicating if the observable has at least one observer
  7681. * @returns true is the Observable has at least one Observer registered
  7682. */
  7683. Observable.prototype.hasObservers = function () {
  7684. return this._observers.length > 0;
  7685. };
  7686. /**
  7687. * Clear the list of observers
  7688. */
  7689. Observable.prototype.clear = function () {
  7690. this._observers = new Array();
  7691. this._onObserverAdded = null;
  7692. };
  7693. /**
  7694. * Clone the current observable
  7695. * @returns a new observable
  7696. */
  7697. Observable.prototype.clone = function () {
  7698. var result = new Observable();
  7699. result._observers = this._observers.slice(0);
  7700. return result;
  7701. };
  7702. /**
  7703. * Does this observable handles observer registered with a given mask
  7704. * @param mask defines the mask to be tested
  7705. * @return whether or not one observer registered with the given mask is handeled
  7706. **/
  7707. Observable.prototype.hasSpecificMask = function (mask) {
  7708. if (mask === void 0) { mask = -1; }
  7709. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7710. var obs = _a[_i];
  7711. if (obs.mask & mask || obs.mask === mask) {
  7712. return true;
  7713. }
  7714. }
  7715. return false;
  7716. };
  7717. return Observable;
  7718. }());
  7719. BABYLON.Observable = Observable;
  7720. })(BABYLON || (BABYLON = {}));
  7721. //# sourceMappingURL=babylon.observable.js.map
  7722. var BABYLON;
  7723. (function (BABYLON) {
  7724. var SmartArray = /** @class */ (function () {
  7725. function SmartArray(capacity) {
  7726. this.length = 0;
  7727. this.data = new Array(capacity);
  7728. this._id = SmartArray._GlobalId++;
  7729. }
  7730. SmartArray.prototype.push = function (value) {
  7731. this.data[this.length++] = value;
  7732. if (this.length > this.data.length) {
  7733. this.data.length *= 2;
  7734. }
  7735. };
  7736. SmartArray.prototype.forEach = function (func) {
  7737. for (var index = 0; index < this.length; index++) {
  7738. func(this.data[index]);
  7739. }
  7740. };
  7741. SmartArray.prototype.sort = function (compareFn) {
  7742. this.data.sort(compareFn);
  7743. };
  7744. SmartArray.prototype.reset = function () {
  7745. this.length = 0;
  7746. };
  7747. SmartArray.prototype.dispose = function () {
  7748. this.reset();
  7749. if (this.data) {
  7750. this.data.length = 0;
  7751. this.data = [];
  7752. }
  7753. };
  7754. SmartArray.prototype.concat = function (array) {
  7755. if (array.length === 0) {
  7756. return;
  7757. }
  7758. if (this.length + array.length > this.data.length) {
  7759. this.data.length = (this.length + array.length) * 2;
  7760. }
  7761. for (var index = 0; index < array.length; index++) {
  7762. this.data[this.length++] = (array.data || array)[index];
  7763. }
  7764. };
  7765. SmartArray.prototype.indexOf = function (value) {
  7766. var position = this.data.indexOf(value);
  7767. if (position >= this.length) {
  7768. return -1;
  7769. }
  7770. return position;
  7771. };
  7772. SmartArray.prototype.contains = function (value) {
  7773. return this.data.indexOf(value) !== -1;
  7774. };
  7775. // Statics
  7776. SmartArray._GlobalId = 0;
  7777. return SmartArray;
  7778. }());
  7779. BABYLON.SmartArray = SmartArray;
  7780. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7781. __extends(SmartArrayNoDuplicate, _super);
  7782. function SmartArrayNoDuplicate() {
  7783. var _this = _super !== null && _super.apply(this, arguments) || this;
  7784. _this._duplicateId = 0;
  7785. return _this;
  7786. }
  7787. SmartArrayNoDuplicate.prototype.push = function (value) {
  7788. _super.prototype.push.call(this, value);
  7789. if (!value.__smartArrayFlags) {
  7790. value.__smartArrayFlags = {};
  7791. }
  7792. value.__smartArrayFlags[this._id] = this._duplicateId;
  7793. };
  7794. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7795. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7796. return false;
  7797. }
  7798. this.push(value);
  7799. return true;
  7800. };
  7801. SmartArrayNoDuplicate.prototype.reset = function () {
  7802. _super.prototype.reset.call(this);
  7803. this._duplicateId++;
  7804. };
  7805. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7806. if (array.length === 0) {
  7807. return;
  7808. }
  7809. if (this.length + array.length > this.data.length) {
  7810. this.data.length = (this.length + array.length) * 2;
  7811. }
  7812. for (var index = 0; index < array.length; index++) {
  7813. var item = (array.data || array)[index];
  7814. this.pushNoDuplicate(item);
  7815. }
  7816. };
  7817. return SmartArrayNoDuplicate;
  7818. }(SmartArray));
  7819. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7820. })(BABYLON || (BABYLON = {}));
  7821. //# sourceMappingURL=babylon.smartArray.js.map
  7822. var BABYLON;
  7823. (function (BABYLON) {
  7824. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7825. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7826. var LoadFileError = /** @class */ (function (_super) {
  7827. __extends(LoadFileError, _super);
  7828. function LoadFileError(message, request) {
  7829. var _this = _super.call(this, message) || this;
  7830. _this.request = request;
  7831. _this.name = "LoadFileError";
  7832. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7833. return _this;
  7834. }
  7835. // Polyfill for Object.setPrototypeOf if necessary.
  7836. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7837. return LoadFileError;
  7838. }(Error));
  7839. BABYLON.LoadFileError = LoadFileError;
  7840. var RetryStrategy = /** @class */ (function () {
  7841. function RetryStrategy() {
  7842. }
  7843. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7844. if (maxRetries === void 0) { maxRetries = 3; }
  7845. if (baseInterval === void 0) { baseInterval = 500; }
  7846. return function (url, request, retryIndex) {
  7847. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7848. return -1;
  7849. }
  7850. return Math.pow(2, retryIndex) * baseInterval;
  7851. };
  7852. };
  7853. return RetryStrategy;
  7854. }());
  7855. BABYLON.RetryStrategy = RetryStrategy;
  7856. // Screenshots
  7857. var screenshotCanvas;
  7858. var cloneValue = function (source, destinationObject) {
  7859. if (!source)
  7860. return null;
  7861. if (source instanceof BABYLON.Mesh) {
  7862. return null;
  7863. }
  7864. if (source instanceof BABYLON.SubMesh) {
  7865. return source.clone(destinationObject);
  7866. }
  7867. else if (source.clone) {
  7868. return source.clone();
  7869. }
  7870. return null;
  7871. };
  7872. var Tools = /** @class */ (function () {
  7873. function Tools() {
  7874. }
  7875. /**
  7876. * Interpolates between a and b via alpha
  7877. * @param a The lower value (returned when alpha = 0)
  7878. * @param b The upper value (returned when alpha = 1)
  7879. * @param alpha The interpolation-factor
  7880. * @return The mixed value
  7881. */
  7882. Tools.Mix = function (a, b, alpha) {
  7883. return a * (1 - alpha) + b * alpha;
  7884. };
  7885. Tools.Instantiate = function (className) {
  7886. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7887. return Tools.RegisteredExternalClasses[className];
  7888. }
  7889. var arr = className.split(".");
  7890. var fn = (window || this);
  7891. for (var i = 0, len = arr.length; i < len; i++) {
  7892. fn = fn[arr[i]];
  7893. }
  7894. if (typeof fn !== "function") {
  7895. return null;
  7896. }
  7897. return fn;
  7898. };
  7899. /**
  7900. * Provides a slice function that will work even on IE
  7901. * @param data defines the array to slice
  7902. * @returns the new sliced array
  7903. */
  7904. Tools.Slice = function (data) {
  7905. if (data.slice) {
  7906. return data.slice();
  7907. }
  7908. return Array.prototype.slice.call(data);
  7909. };
  7910. Tools.SetImmediate = function (action) {
  7911. if (window.setImmediate) {
  7912. window.setImmediate(action);
  7913. }
  7914. else {
  7915. setTimeout(action, 1);
  7916. }
  7917. };
  7918. Tools.IsExponentOfTwo = function (value) {
  7919. var count = 1;
  7920. do {
  7921. count *= 2;
  7922. } while (count < value);
  7923. return count === value;
  7924. };
  7925. /**
  7926. * Find the next highest power of two.
  7927. * @param x Number to start search from.
  7928. * @return Next highest power of two.
  7929. */
  7930. Tools.CeilingPOT = function (x) {
  7931. x--;
  7932. x |= x >> 1;
  7933. x |= x >> 2;
  7934. x |= x >> 4;
  7935. x |= x >> 8;
  7936. x |= x >> 16;
  7937. x++;
  7938. return x;
  7939. };
  7940. /**
  7941. * Find the next lowest power of two.
  7942. * @param x Number to start search from.
  7943. * @return Next lowest power of two.
  7944. */
  7945. Tools.FloorPOT = function (x) {
  7946. x = x | (x >> 1);
  7947. x = x | (x >> 2);
  7948. x = x | (x >> 4);
  7949. x = x | (x >> 8);
  7950. x = x | (x >> 16);
  7951. return x - (x >> 1);
  7952. };
  7953. /**
  7954. * Find the nearest power of two.
  7955. * @param x Number to start search from.
  7956. * @return Next nearest power of two.
  7957. */
  7958. Tools.NearestPOT = function (x) {
  7959. var c = Tools.CeilingPOT(x);
  7960. var f = Tools.FloorPOT(x);
  7961. return (c - x) > (x - f) ? f : c;
  7962. };
  7963. Tools.GetExponentOfTwo = function (value, max, mode) {
  7964. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7965. var pot;
  7966. switch (mode) {
  7967. case BABYLON.Engine.SCALEMODE_FLOOR:
  7968. pot = Tools.FloorPOT(value);
  7969. break;
  7970. case BABYLON.Engine.SCALEMODE_NEAREST:
  7971. pot = Tools.NearestPOT(value);
  7972. break;
  7973. case BABYLON.Engine.SCALEMODE_CEILING:
  7974. default:
  7975. pot = Tools.CeilingPOT(value);
  7976. break;
  7977. }
  7978. return Math.min(pot, max);
  7979. };
  7980. Tools.GetFilename = function (path) {
  7981. var index = path.lastIndexOf("/");
  7982. if (index < 0)
  7983. return path;
  7984. return path.substring(index + 1);
  7985. };
  7986. /**
  7987. * Extracts the "folder" part of a path (everything before the filename).
  7988. * @param uri The URI to extract the info from
  7989. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7990. * @returns The "folder" part of the path
  7991. */
  7992. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7993. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7994. var index = uri.lastIndexOf("/");
  7995. if (index < 0) {
  7996. if (returnUnchangedIfNoSlash) {
  7997. return uri;
  7998. }
  7999. return "";
  8000. }
  8001. return uri.substring(0, index + 1);
  8002. };
  8003. Tools.GetDOMTextContent = function (element) {
  8004. var result = "";
  8005. var child = element.firstChild;
  8006. while (child) {
  8007. if (child.nodeType === 3) {
  8008. result += child.textContent;
  8009. }
  8010. child = child.nextSibling;
  8011. }
  8012. return result;
  8013. };
  8014. Tools.ToDegrees = function (angle) {
  8015. return angle * 180 / Math.PI;
  8016. };
  8017. Tools.ToRadians = function (angle) {
  8018. return angle * Math.PI / 180;
  8019. };
  8020. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8021. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8022. var output = "";
  8023. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8024. var i = 0;
  8025. var bytes = new Uint8Array(buffer);
  8026. while (i < bytes.length) {
  8027. chr1 = bytes[i++];
  8028. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8029. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8030. enc1 = chr1 >> 2;
  8031. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8032. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8033. enc4 = chr3 & 63;
  8034. if (isNaN(chr2)) {
  8035. enc3 = enc4 = 64;
  8036. }
  8037. else if (isNaN(chr3)) {
  8038. enc4 = 64;
  8039. }
  8040. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8041. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8042. }
  8043. return "data:image/png;base64," + output;
  8044. };
  8045. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8046. if (bias === void 0) { bias = null; }
  8047. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8048. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8049. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8050. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8051. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8052. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8053. }
  8054. if (bias) {
  8055. minimum.x -= minimum.x * bias.x + bias.y;
  8056. minimum.y -= minimum.y * bias.x + bias.y;
  8057. minimum.z -= minimum.z * bias.x + bias.y;
  8058. maximum.x += maximum.x * bias.x + bias.y;
  8059. maximum.y += maximum.y * bias.x + bias.y;
  8060. maximum.z += maximum.z * bias.x + bias.y;
  8061. }
  8062. return {
  8063. minimum: minimum,
  8064. maximum: maximum
  8065. };
  8066. };
  8067. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8068. if (bias === void 0) { bias = null; }
  8069. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8070. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8071. if (!stride) {
  8072. stride = 3;
  8073. }
  8074. for (var index = start; index < start + count; index++) {
  8075. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8076. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8077. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8078. }
  8079. if (bias) {
  8080. minimum.x -= minimum.x * bias.x + bias.y;
  8081. minimum.y -= minimum.y * bias.x + bias.y;
  8082. minimum.z -= minimum.z * bias.x + bias.y;
  8083. maximum.x += maximum.x * bias.x + bias.y;
  8084. maximum.y += maximum.y * bias.x + bias.y;
  8085. maximum.z += maximum.z * bias.x + bias.y;
  8086. }
  8087. return {
  8088. minimum: minimum,
  8089. maximum: maximum
  8090. };
  8091. };
  8092. Tools.Vector2ArrayFeeder = function (array) {
  8093. return function (index) {
  8094. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8095. var length = isFloatArray ? array.length / 2 : array.length;
  8096. if (index >= length) {
  8097. return null;
  8098. }
  8099. if (isFloatArray) {
  8100. var fa = array;
  8101. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8102. }
  8103. var a = array;
  8104. return a[index];
  8105. };
  8106. };
  8107. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8108. if (bias === void 0) { bias = null; }
  8109. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8110. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8111. var i = 0;
  8112. var cur = feeder(i++);
  8113. while (cur) {
  8114. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8115. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8116. cur = feeder(i++);
  8117. }
  8118. if (bias) {
  8119. minimum.x -= minimum.x * bias.x + bias.y;
  8120. minimum.y -= minimum.y * bias.x + bias.y;
  8121. maximum.x += maximum.x * bias.x + bias.y;
  8122. maximum.y += maximum.y * bias.x + bias.y;
  8123. }
  8124. return {
  8125. minimum: minimum,
  8126. maximum: maximum
  8127. };
  8128. };
  8129. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8130. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8131. return null;
  8132. return Array.isArray(obj) ? obj : [obj];
  8133. };
  8134. // Misc.
  8135. Tools.GetPointerPrefix = function () {
  8136. var eventPrefix = "pointer";
  8137. // Check if pointer events are supported
  8138. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8139. eventPrefix = "mouse";
  8140. }
  8141. return eventPrefix;
  8142. };
  8143. /**
  8144. * @param func - the function to be called
  8145. * @param requester - the object that will request the next frame. Falls back to window.
  8146. */
  8147. Tools.QueueNewFrame = function (func, requester) {
  8148. if (!Tools.IsWindowObjectExist()) {
  8149. return setTimeout(func, 16);
  8150. }
  8151. if (!requester) {
  8152. requester = window;
  8153. }
  8154. if (requester.requestAnimationFrame) {
  8155. return requester.requestAnimationFrame(func);
  8156. }
  8157. else if (requester.msRequestAnimationFrame) {
  8158. return requester.msRequestAnimationFrame(func);
  8159. }
  8160. else if (requester.webkitRequestAnimationFrame) {
  8161. return requester.webkitRequestAnimationFrame(func);
  8162. }
  8163. else if (requester.mozRequestAnimationFrame) {
  8164. return requester.mozRequestAnimationFrame(func);
  8165. }
  8166. else if (requester.oRequestAnimationFrame) {
  8167. return requester.oRequestAnimationFrame(func);
  8168. }
  8169. else {
  8170. return window.setTimeout(func, 16);
  8171. }
  8172. };
  8173. Tools.RequestFullscreen = function (element) {
  8174. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8175. if (!requestFunction)
  8176. return;
  8177. requestFunction.call(element);
  8178. };
  8179. Tools.ExitFullscreen = function () {
  8180. if (document.exitFullscreen) {
  8181. document.exitFullscreen();
  8182. }
  8183. else if (document.mozCancelFullScreen) {
  8184. document.mozCancelFullScreen();
  8185. }
  8186. else if (document.webkitCancelFullScreen) {
  8187. document.webkitCancelFullScreen();
  8188. }
  8189. else if (document.msCancelFullScreen) {
  8190. document.msCancelFullScreen();
  8191. }
  8192. };
  8193. Tools.SetCorsBehavior = function (url, element) {
  8194. if (url && url.indexOf("data:") === 0) {
  8195. return;
  8196. }
  8197. if (Tools.CorsBehavior) {
  8198. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8199. element.crossOrigin = Tools.CorsBehavior;
  8200. }
  8201. else {
  8202. var result = Tools.CorsBehavior(url);
  8203. if (result) {
  8204. element.crossOrigin = result;
  8205. }
  8206. }
  8207. }
  8208. };
  8209. // External files
  8210. Tools.CleanUrl = function (url) {
  8211. url = url.replace(/#/mg, "%23");
  8212. return url;
  8213. };
  8214. Tools.LoadImage = function (url, onLoad, onError, database) {
  8215. if (url instanceof ArrayBuffer) {
  8216. url = Tools.EncodeArrayBufferTobase64(url);
  8217. }
  8218. url = Tools.CleanUrl(url);
  8219. url = Tools.PreprocessUrl(url);
  8220. var img = new Image();
  8221. Tools.SetCorsBehavior(url, img);
  8222. var loadHandler = function () {
  8223. img.removeEventListener("load", loadHandler);
  8224. img.removeEventListener("error", errorHandler);
  8225. onLoad(img);
  8226. };
  8227. var errorHandler = function (err) {
  8228. img.removeEventListener("load", loadHandler);
  8229. img.removeEventListener("error", errorHandler);
  8230. Tools.Error("Error while trying to load image: " + url);
  8231. if (onError) {
  8232. onError("Error while trying to load image: " + url, err);
  8233. }
  8234. };
  8235. img.addEventListener("load", loadHandler);
  8236. img.addEventListener("error", errorHandler);
  8237. var noIndexedDB = function () {
  8238. img.src = url;
  8239. };
  8240. var loadFromIndexedDB = function () {
  8241. if (database) {
  8242. database.loadImageFromDB(url, img);
  8243. }
  8244. };
  8245. //ANY database to do!
  8246. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8247. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8248. }
  8249. else {
  8250. if (url.indexOf("file:") !== -1) {
  8251. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8252. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8253. try {
  8254. var blobURL;
  8255. try {
  8256. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8257. }
  8258. catch (ex) {
  8259. // Chrome doesn't support oneTimeOnly parameter
  8260. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8261. }
  8262. img.src = blobURL;
  8263. }
  8264. catch (e) {
  8265. img.src = "";
  8266. }
  8267. return img;
  8268. }
  8269. }
  8270. noIndexedDB();
  8271. }
  8272. return img;
  8273. };
  8274. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8275. url = Tools.CleanUrl(url);
  8276. url = Tools.PreprocessUrl(url);
  8277. // If file and file input are set
  8278. if (url.indexOf("file:") !== -1) {
  8279. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8280. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8281. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8282. }
  8283. }
  8284. var loadUrl = Tools.BaseUrl + url;
  8285. var aborted = false;
  8286. var fileRequest = {
  8287. onCompleteObservable: new BABYLON.Observable(),
  8288. abort: function () { return aborted = true; },
  8289. };
  8290. var requestFile = function () {
  8291. var request = new XMLHttpRequest();
  8292. var retryHandle = null;
  8293. fileRequest.abort = function () {
  8294. aborted = true;
  8295. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8296. request.abort();
  8297. }
  8298. if (retryHandle !== null) {
  8299. clearTimeout(retryHandle);
  8300. retryHandle = null;
  8301. }
  8302. };
  8303. var retryLoop = function (retryIndex) {
  8304. request.open('GET', loadUrl, true);
  8305. if (useArrayBuffer) {
  8306. request.responseType = "arraybuffer";
  8307. }
  8308. if (onProgress) {
  8309. request.addEventListener("progress", onProgress);
  8310. }
  8311. var onLoadEnd = function () {
  8312. request.removeEventListener("loadend", onLoadEnd);
  8313. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8314. fileRequest.onCompleteObservable.clear();
  8315. };
  8316. request.addEventListener("loadend", onLoadEnd);
  8317. var onReadyStateChange = function () {
  8318. if (aborted) {
  8319. return;
  8320. }
  8321. // In case of undefined state in some browsers.
  8322. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8323. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8324. request.removeEventListener("readystatechange", onReadyStateChange);
  8325. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8326. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8327. return;
  8328. }
  8329. var retryStrategy = Tools.DefaultRetryStrategy;
  8330. if (retryStrategy) {
  8331. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8332. if (waitTime !== -1) {
  8333. // Prevent the request from completing for retry.
  8334. request.removeEventListener("loadend", onLoadEnd);
  8335. request = new XMLHttpRequest();
  8336. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8337. return;
  8338. }
  8339. }
  8340. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8341. if (onError) {
  8342. onError(request, e);
  8343. }
  8344. else {
  8345. throw e;
  8346. }
  8347. }
  8348. };
  8349. request.addEventListener("readystatechange", onReadyStateChange);
  8350. request.send();
  8351. };
  8352. retryLoop(0);
  8353. };
  8354. // Caching all files
  8355. if (database && database.enableSceneOffline) {
  8356. var noIndexedDB_1 = function () {
  8357. if (!aborted) {
  8358. requestFile();
  8359. }
  8360. };
  8361. var loadFromIndexedDB = function () {
  8362. // TODO: database needs to support aborting and should return a IFileRequest
  8363. if (aborted) {
  8364. return;
  8365. }
  8366. if (database) {
  8367. database.loadFileFromDB(url, function (data) {
  8368. if (!aborted) {
  8369. onSuccess(data);
  8370. }
  8371. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8372. }, onProgress ? function (event) {
  8373. if (!aborted) {
  8374. onProgress(event);
  8375. }
  8376. } : undefined, noIndexedDB_1, useArrayBuffer);
  8377. }
  8378. };
  8379. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8380. }
  8381. else {
  8382. requestFile();
  8383. }
  8384. return fileRequest;
  8385. };
  8386. /**
  8387. * Load a script (identified by an url). When the url returns, the
  8388. * content of this file is added into a new script element, attached to the DOM (body element)
  8389. */
  8390. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8391. var head = document.getElementsByTagName('head')[0];
  8392. var script = document.createElement('script');
  8393. script.type = 'text/javascript';
  8394. script.src = scriptUrl;
  8395. script.onload = function () {
  8396. if (onSuccess) {
  8397. onSuccess();
  8398. }
  8399. };
  8400. script.onerror = function (e) {
  8401. if (onError) {
  8402. onError("Unable to load script", e);
  8403. }
  8404. };
  8405. head.appendChild(script);
  8406. };
  8407. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8408. var reader = new FileReader();
  8409. var request = {
  8410. onCompleteObservable: new BABYLON.Observable(),
  8411. abort: function () { return reader.abort(); },
  8412. };
  8413. reader.onloadend = function (e) {
  8414. request.onCompleteObservable.notifyObservers(request);
  8415. };
  8416. reader.onload = function (e) {
  8417. //target doesn't have result from ts 1.3
  8418. callback(e.target['result']);
  8419. };
  8420. reader.onprogress = progressCallback;
  8421. reader.readAsDataURL(fileToLoad);
  8422. return request;
  8423. };
  8424. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8425. var reader = new FileReader();
  8426. var request = {
  8427. onCompleteObservable: new BABYLON.Observable(),
  8428. abort: function () { return reader.abort(); },
  8429. };
  8430. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8431. reader.onerror = function (e) {
  8432. Tools.Log("Error while reading file: " + fileToLoad.name);
  8433. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8434. };
  8435. reader.onload = function (e) {
  8436. //target doesn't have result from ts 1.3
  8437. callback(e.target['result']);
  8438. };
  8439. if (progressCallBack) {
  8440. reader.onprogress = progressCallBack;
  8441. }
  8442. if (!useArrayBuffer) {
  8443. // Asynchronous read
  8444. reader.readAsText(fileToLoad);
  8445. }
  8446. else {
  8447. reader.readAsArrayBuffer(fileToLoad);
  8448. }
  8449. return request;
  8450. };
  8451. //returns a downloadable url to a file content.
  8452. Tools.FileAsURL = function (content) {
  8453. var fileBlob = new Blob([content]);
  8454. var url = window.URL || window.webkitURL;
  8455. var link = url.createObjectURL(fileBlob);
  8456. return link;
  8457. };
  8458. // Misc.
  8459. Tools.Format = function (value, decimals) {
  8460. if (decimals === void 0) { decimals = 2; }
  8461. return value.toFixed(decimals);
  8462. };
  8463. Tools.CheckExtends = function (v, min, max) {
  8464. if (v.x < min.x)
  8465. min.x = v.x;
  8466. if (v.y < min.y)
  8467. min.y = v.y;
  8468. if (v.z < min.z)
  8469. min.z = v.z;
  8470. if (v.x > max.x)
  8471. max.x = v.x;
  8472. if (v.y > max.y)
  8473. max.y = v.y;
  8474. if (v.z > max.z)
  8475. max.z = v.z;
  8476. };
  8477. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8478. for (var prop in source) {
  8479. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8480. continue;
  8481. }
  8482. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8483. continue;
  8484. }
  8485. var sourceValue = source[prop];
  8486. var typeOfSourceValue = typeof sourceValue;
  8487. if (typeOfSourceValue === "function") {
  8488. continue;
  8489. }
  8490. if (typeOfSourceValue === "object") {
  8491. if (sourceValue instanceof Array) {
  8492. destination[prop] = [];
  8493. if (sourceValue.length > 0) {
  8494. if (typeof sourceValue[0] == "object") {
  8495. for (var index = 0; index < sourceValue.length; index++) {
  8496. var clonedValue = cloneValue(sourceValue[index], destination);
  8497. if (destination[prop].indexOf(clonedValue) === -1) {
  8498. destination[prop].push(clonedValue);
  8499. }
  8500. }
  8501. }
  8502. else {
  8503. destination[prop] = sourceValue.slice(0);
  8504. }
  8505. }
  8506. }
  8507. else {
  8508. destination[prop] = cloneValue(sourceValue, destination);
  8509. }
  8510. }
  8511. else {
  8512. destination[prop] = sourceValue;
  8513. }
  8514. }
  8515. };
  8516. Tools.IsEmpty = function (obj) {
  8517. for (var i in obj) {
  8518. if (obj.hasOwnProperty(i)) {
  8519. return false;
  8520. }
  8521. }
  8522. return true;
  8523. };
  8524. Tools.RegisterTopRootEvents = function (events) {
  8525. for (var index = 0; index < events.length; index++) {
  8526. var event = events[index];
  8527. window.addEventListener(event.name, event.handler, false);
  8528. try {
  8529. if (window.parent) {
  8530. window.parent.addEventListener(event.name, event.handler, false);
  8531. }
  8532. }
  8533. catch (e) {
  8534. // Silently fails...
  8535. }
  8536. }
  8537. };
  8538. Tools.UnregisterTopRootEvents = function (events) {
  8539. for (var index = 0; index < events.length; index++) {
  8540. var event = events[index];
  8541. window.removeEventListener(event.name, event.handler);
  8542. try {
  8543. if (window.parent) {
  8544. window.parent.removeEventListener(event.name, event.handler);
  8545. }
  8546. }
  8547. catch (e) {
  8548. // Silently fails...
  8549. }
  8550. }
  8551. };
  8552. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8553. if (mimeType === void 0) { mimeType = "image/png"; }
  8554. // Read the contents of the framebuffer
  8555. var numberOfChannelsByLine = width * 4;
  8556. var halfHeight = height / 2;
  8557. //Reading datas from WebGL
  8558. var data = engine.readPixels(0, 0, width, height);
  8559. //To flip image on Y axis.
  8560. for (var i = 0; i < halfHeight; i++) {
  8561. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8562. var currentCell = j + i * numberOfChannelsByLine;
  8563. var targetLine = height - i - 1;
  8564. var targetCell = j + targetLine * numberOfChannelsByLine;
  8565. var temp = data[currentCell];
  8566. data[currentCell] = data[targetCell];
  8567. data[targetCell] = temp;
  8568. }
  8569. }
  8570. // Create a 2D canvas to store the result
  8571. if (!screenshotCanvas) {
  8572. screenshotCanvas = document.createElement('canvas');
  8573. }
  8574. screenshotCanvas.width = width;
  8575. screenshotCanvas.height = height;
  8576. var context = screenshotCanvas.getContext('2d');
  8577. if (context) {
  8578. // Copy the pixels to a 2D canvas
  8579. var imageData = context.createImageData(width, height);
  8580. var castData = (imageData.data);
  8581. castData.set(data);
  8582. context.putImageData(imageData, 0, 0);
  8583. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8584. }
  8585. };
  8586. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8587. if (mimeType === void 0) { mimeType = "image/png"; }
  8588. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8589. if (successCallback) {
  8590. successCallback(base64Image);
  8591. }
  8592. else {
  8593. // We need HTMLCanvasElement.toBlob for HD screenshots
  8594. if (!screenshotCanvas.toBlob) {
  8595. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8596. screenshotCanvas.toBlob = function (callback, type, quality) {
  8597. var _this = this;
  8598. setTimeout(function () {
  8599. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8600. for (var i = 0; i < len; i++) {
  8601. arr[i] = binStr.charCodeAt(i);
  8602. }
  8603. callback(new Blob([arr], { type: type || 'image/png' }));
  8604. });
  8605. };
  8606. }
  8607. screenshotCanvas.toBlob(function (blob) {
  8608. var url = URL.createObjectURL(blob);
  8609. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8610. if (("download" in document.createElement("a"))) {
  8611. var a = window.document.createElement("a");
  8612. a.href = url;
  8613. if (fileName) {
  8614. a.setAttribute("download", fileName);
  8615. }
  8616. else {
  8617. var date = new Date();
  8618. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8619. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8620. }
  8621. window.document.body.appendChild(a);
  8622. a.addEventListener("click", function () {
  8623. if (a.parentElement) {
  8624. a.parentElement.removeChild(a);
  8625. }
  8626. });
  8627. a.click();
  8628. }
  8629. else {
  8630. var newWindow = window.open("");
  8631. if (!newWindow)
  8632. return;
  8633. var img = newWindow.document.createElement("img");
  8634. img.onload = function () {
  8635. // no longer need to read the blob so it's revoked
  8636. URL.revokeObjectURL(url);
  8637. };
  8638. img.src = url;
  8639. newWindow.document.body.appendChild(img);
  8640. }
  8641. });
  8642. }
  8643. };
  8644. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8645. if (mimeType === void 0) { mimeType = "image/png"; }
  8646. var width;
  8647. var height;
  8648. // If a precision value is specified
  8649. if (size.precision) {
  8650. width = Math.round(engine.getRenderWidth() * size.precision);
  8651. height = Math.round(width / engine.getAspectRatio(camera));
  8652. }
  8653. else if (size.width && size.height) {
  8654. width = size.width;
  8655. height = size.height;
  8656. }
  8657. else if (size.width && !size.height) {
  8658. width = size.width;
  8659. height = Math.round(width / engine.getAspectRatio(camera));
  8660. }
  8661. else if (size.height && !size.width) {
  8662. height = size.height;
  8663. width = Math.round(height * engine.getAspectRatio(camera));
  8664. }
  8665. else if (!isNaN(size)) {
  8666. height = size;
  8667. width = size;
  8668. }
  8669. else {
  8670. Tools.Error("Invalid 'size' parameter !");
  8671. return;
  8672. }
  8673. if (!screenshotCanvas) {
  8674. screenshotCanvas = document.createElement('canvas');
  8675. }
  8676. screenshotCanvas.width = width;
  8677. screenshotCanvas.height = height;
  8678. var renderContext = screenshotCanvas.getContext("2d");
  8679. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8680. var newWidth = width;
  8681. var newHeight = newWidth / ratio;
  8682. if (newHeight > height) {
  8683. newHeight = height;
  8684. newWidth = newHeight * ratio;
  8685. }
  8686. var offsetX = Math.max(0, width - newWidth) / 2;
  8687. var offsetY = Math.max(0, height - newHeight) / 2;
  8688. var renderingCanvas = engine.getRenderingCanvas();
  8689. if (renderContext && renderingCanvas) {
  8690. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8691. }
  8692. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8693. };
  8694. /**
  8695. * Generates an image screenshot from the specified camera.
  8696. *
  8697. * @param engine The engine to use for rendering
  8698. * @param camera The camera to use for rendering
  8699. * @param size This parameter can be set to a single number or to an object with the
  8700. * following (optional) properties: precision, width, height. If a single number is passed,
  8701. * it will be used for both width and height. If an object is passed, the screenshot size
  8702. * will be derived from the parameters. The precision property is a multiplier allowing
  8703. * rendering at a higher or lower resolution.
  8704. * @param successCallback The callback receives a single parameter which contains the
  8705. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8706. * src parameter of an <img> to display it.
  8707. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8708. * Check your browser for supported MIME types.
  8709. * @param samples Texture samples (default: 1)
  8710. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8711. * @param fileName A name for for the downloaded file.
  8712. * @constructor
  8713. */
  8714. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8715. if (mimeType === void 0) { mimeType = "image/png"; }
  8716. if (samples === void 0) { samples = 1; }
  8717. if (antialiasing === void 0) { antialiasing = false; }
  8718. var width;
  8719. var height;
  8720. //If a precision value is specified
  8721. if (size.precision) {
  8722. width = Math.round(engine.getRenderWidth() * size.precision);
  8723. height = Math.round(width / engine.getAspectRatio(camera));
  8724. size = { width: width, height: height };
  8725. }
  8726. else if (size.width && size.height) {
  8727. width = size.width;
  8728. height = size.height;
  8729. }
  8730. else if (size.width && !size.height) {
  8731. width = size.width;
  8732. height = Math.round(width / engine.getAspectRatio(camera));
  8733. size = { width: width, height: height };
  8734. }
  8735. else if (size.height && !size.width) {
  8736. height = size.height;
  8737. width = Math.round(height * engine.getAspectRatio(camera));
  8738. size = { width: width, height: height };
  8739. }
  8740. else if (!isNaN(size)) {
  8741. height = size;
  8742. width = size;
  8743. }
  8744. else {
  8745. Tools.Error("Invalid 'size' parameter !");
  8746. return;
  8747. }
  8748. var scene = camera.getScene();
  8749. var previousCamera = null;
  8750. if (scene.activeCamera !== camera) {
  8751. previousCamera = scene.activeCamera;
  8752. scene.activeCamera = camera;
  8753. }
  8754. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8755. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8756. texture.renderList = null;
  8757. texture.samples = samples;
  8758. if (antialiasing) {
  8759. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8760. }
  8761. texture.onAfterRenderObservable.add(function () {
  8762. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8763. });
  8764. scene.incrementRenderId();
  8765. scene.resetCachedMaterial();
  8766. texture.render(true);
  8767. texture.dispose();
  8768. if (previousCamera) {
  8769. scene.activeCamera = previousCamera;
  8770. }
  8771. camera.getProjectionMatrix(true); // Force cache refresh;
  8772. };
  8773. // XHR response validator for local file scenario
  8774. Tools.ValidateXHRData = function (xhr, dataType) {
  8775. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8776. if (dataType === void 0) { dataType = 7; }
  8777. try {
  8778. if (dataType & 1) {
  8779. if (xhr.responseText && xhr.responseText.length > 0) {
  8780. return true;
  8781. }
  8782. else if (dataType === 1) {
  8783. return false;
  8784. }
  8785. }
  8786. if (dataType & 2) {
  8787. // Check header width and height since there is no "TGA" magic number
  8788. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8789. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8790. return true;
  8791. }
  8792. else if (dataType === 2) {
  8793. return false;
  8794. }
  8795. }
  8796. if (dataType & 4) {
  8797. // Check for the "DDS" magic number
  8798. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8799. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8800. return true;
  8801. }
  8802. else {
  8803. return false;
  8804. }
  8805. }
  8806. }
  8807. catch (e) {
  8808. // Global protection
  8809. }
  8810. return false;
  8811. };
  8812. /**
  8813. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8814. * Be aware Math.random() could cause collisions, but:
  8815. * "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"
  8816. */
  8817. Tools.RandomId = function () {
  8818. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8819. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8820. return v.toString(16);
  8821. });
  8822. };
  8823. /**
  8824. * Test if the given uri is a base64 string.
  8825. * @param uri The uri to test
  8826. * @return True if the uri is a base64 string or false otherwise.
  8827. */
  8828. Tools.IsBase64 = function (uri) {
  8829. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8830. };
  8831. /**
  8832. * Decode the given base64 uri.
  8833. * @param uri The uri to decode
  8834. * @return The decoded base64 data.
  8835. */
  8836. Tools.DecodeBase64 = function (uri) {
  8837. var decodedString = atob(uri.split(",")[1]);
  8838. var bufferLength = decodedString.length;
  8839. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8840. for (var i = 0; i < bufferLength; i++) {
  8841. bufferView[i] = decodedString.charCodeAt(i);
  8842. }
  8843. return bufferView.buffer;
  8844. };
  8845. Object.defineProperty(Tools, "NoneLogLevel", {
  8846. get: function () {
  8847. return Tools._NoneLogLevel;
  8848. },
  8849. enumerable: true,
  8850. configurable: true
  8851. });
  8852. Object.defineProperty(Tools, "MessageLogLevel", {
  8853. get: function () {
  8854. return Tools._MessageLogLevel;
  8855. },
  8856. enumerable: true,
  8857. configurable: true
  8858. });
  8859. Object.defineProperty(Tools, "WarningLogLevel", {
  8860. get: function () {
  8861. return Tools._WarningLogLevel;
  8862. },
  8863. enumerable: true,
  8864. configurable: true
  8865. });
  8866. Object.defineProperty(Tools, "ErrorLogLevel", {
  8867. get: function () {
  8868. return Tools._ErrorLogLevel;
  8869. },
  8870. enumerable: true,
  8871. configurable: true
  8872. });
  8873. Object.defineProperty(Tools, "AllLogLevel", {
  8874. get: function () {
  8875. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8876. },
  8877. enumerable: true,
  8878. configurable: true
  8879. });
  8880. Tools._AddLogEntry = function (entry) {
  8881. Tools._LogCache = entry + Tools._LogCache;
  8882. if (Tools.OnNewCacheEntry) {
  8883. Tools.OnNewCacheEntry(entry);
  8884. }
  8885. };
  8886. Tools._FormatMessage = function (message) {
  8887. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8888. var date = new Date();
  8889. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8890. };
  8891. Tools._LogDisabled = function (message) {
  8892. // nothing to do
  8893. };
  8894. Tools._LogEnabled = function (message) {
  8895. var formattedMessage = Tools._FormatMessage(message);
  8896. console.log("BJS - " + formattedMessage);
  8897. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8898. Tools._AddLogEntry(entry);
  8899. };
  8900. Tools._WarnDisabled = function (message) {
  8901. // nothing to do
  8902. };
  8903. Tools._WarnEnabled = function (message) {
  8904. var formattedMessage = Tools._FormatMessage(message);
  8905. console.warn("BJS - " + formattedMessage);
  8906. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8907. Tools._AddLogEntry(entry);
  8908. };
  8909. Tools._ErrorDisabled = function (message) {
  8910. // nothing to do
  8911. };
  8912. Tools._ErrorEnabled = function (message) {
  8913. Tools.errorsCount++;
  8914. var formattedMessage = Tools._FormatMessage(message);
  8915. console.error("BJS - " + formattedMessage);
  8916. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8917. Tools._AddLogEntry(entry);
  8918. };
  8919. Object.defineProperty(Tools, "LogCache", {
  8920. get: function () {
  8921. return Tools._LogCache;
  8922. },
  8923. enumerable: true,
  8924. configurable: true
  8925. });
  8926. Tools.ClearLogCache = function () {
  8927. Tools._LogCache = "";
  8928. Tools.errorsCount = 0;
  8929. };
  8930. Object.defineProperty(Tools, "LogLevels", {
  8931. set: function (level) {
  8932. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8933. Tools.Log = Tools._LogEnabled;
  8934. }
  8935. else {
  8936. Tools.Log = Tools._LogDisabled;
  8937. }
  8938. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8939. Tools.Warn = Tools._WarnEnabled;
  8940. }
  8941. else {
  8942. Tools.Warn = Tools._WarnDisabled;
  8943. }
  8944. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8945. Tools.Error = Tools._ErrorEnabled;
  8946. }
  8947. else {
  8948. Tools.Error = Tools._ErrorDisabled;
  8949. }
  8950. },
  8951. enumerable: true,
  8952. configurable: true
  8953. });
  8954. Tools.IsWindowObjectExist = function () {
  8955. return (typeof window) !== "undefined";
  8956. };
  8957. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8958. get: function () {
  8959. return Tools._PerformanceNoneLogLevel;
  8960. },
  8961. enumerable: true,
  8962. configurable: true
  8963. });
  8964. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8965. get: function () {
  8966. return Tools._PerformanceUserMarkLogLevel;
  8967. },
  8968. enumerable: true,
  8969. configurable: true
  8970. });
  8971. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8972. get: function () {
  8973. return Tools._PerformanceConsoleLogLevel;
  8974. },
  8975. enumerable: true,
  8976. configurable: true
  8977. });
  8978. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8979. set: function (level) {
  8980. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8981. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8982. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8983. return;
  8984. }
  8985. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8986. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8987. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8988. return;
  8989. }
  8990. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8991. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8992. },
  8993. enumerable: true,
  8994. configurable: true
  8995. });
  8996. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8997. };
  8998. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8999. };
  9000. Tools._StartUserMark = function (counterName, condition) {
  9001. if (condition === void 0) { condition = true; }
  9002. if (!Tools._performance) {
  9003. if (!Tools.IsWindowObjectExist()) {
  9004. return;
  9005. }
  9006. Tools._performance = window.performance;
  9007. }
  9008. if (!condition || !Tools._performance.mark) {
  9009. return;
  9010. }
  9011. Tools._performance.mark(counterName + "-Begin");
  9012. };
  9013. Tools._EndUserMark = function (counterName, condition) {
  9014. if (condition === void 0) { condition = true; }
  9015. if (!condition || !Tools._performance.mark) {
  9016. return;
  9017. }
  9018. Tools._performance.mark(counterName + "-End");
  9019. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9020. };
  9021. Tools._StartPerformanceConsole = function (counterName, condition) {
  9022. if (condition === void 0) { condition = true; }
  9023. if (!condition) {
  9024. return;
  9025. }
  9026. Tools._StartUserMark(counterName, condition);
  9027. if (console.time) {
  9028. console.time(counterName);
  9029. }
  9030. };
  9031. Tools._EndPerformanceConsole = function (counterName, condition) {
  9032. if (condition === void 0) { condition = true; }
  9033. if (!condition) {
  9034. return;
  9035. }
  9036. Tools._EndUserMark(counterName, condition);
  9037. if (console.time) {
  9038. console.timeEnd(counterName);
  9039. }
  9040. };
  9041. Object.defineProperty(Tools, "Now", {
  9042. get: function () {
  9043. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9044. return window.performance.now();
  9045. }
  9046. return new Date().getTime();
  9047. },
  9048. enumerable: true,
  9049. configurable: true
  9050. });
  9051. /**
  9052. * This method will return the name of the class used to create the instance of the given object.
  9053. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9054. * @param object the object to get the class name from
  9055. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9056. */
  9057. Tools.GetClassName = function (object, isType) {
  9058. if (isType === void 0) { isType = false; }
  9059. var name = null;
  9060. if (!isType && object.getClassName) {
  9061. name = object.getClassName();
  9062. }
  9063. else {
  9064. if (object instanceof Object) {
  9065. var classObj = isType ? object : Object.getPrototypeOf(object);
  9066. name = classObj.constructor["__bjsclassName__"];
  9067. }
  9068. if (!name) {
  9069. name = typeof object;
  9070. }
  9071. }
  9072. return name;
  9073. };
  9074. Tools.First = function (array, predicate) {
  9075. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9076. var el = array_1[_i];
  9077. if (predicate(el)) {
  9078. return el;
  9079. }
  9080. }
  9081. return null;
  9082. };
  9083. /**
  9084. * This method will return the name of the full name of the class, including its owning module (if any).
  9085. * 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).
  9086. * @param object the object to get the class name from
  9087. * @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.
  9088. */
  9089. Tools.getFullClassName = function (object, isType) {
  9090. if (isType === void 0) { isType = false; }
  9091. var className = null;
  9092. var moduleName = null;
  9093. if (!isType && object.getClassName) {
  9094. className = object.getClassName();
  9095. }
  9096. else {
  9097. if (object instanceof Object) {
  9098. var classObj = isType ? object : Object.getPrototypeOf(object);
  9099. className = classObj.constructor["__bjsclassName__"];
  9100. moduleName = classObj.constructor["__bjsmoduleName__"];
  9101. }
  9102. if (!className) {
  9103. className = typeof object;
  9104. }
  9105. }
  9106. if (!className) {
  9107. return null;
  9108. }
  9109. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9110. };
  9111. /**
  9112. * 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.
  9113. * @param array
  9114. */
  9115. Tools.arrayOrStringFeeder = function (array) {
  9116. return function (index) {
  9117. if (index >= array.length) {
  9118. return null;
  9119. }
  9120. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9121. if (val && val.getHashCode) {
  9122. val = val.getHashCode();
  9123. }
  9124. if (typeof val === "string") {
  9125. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9126. }
  9127. return val;
  9128. };
  9129. };
  9130. /**
  9131. * Compute the hashCode of a stream of number
  9132. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9133. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9134. * @return the hash code computed
  9135. */
  9136. Tools.hashCodeFromStream = function (feeder) {
  9137. // Based from here: http://stackoverflow.com/a/7616484/802124
  9138. var hash = 0;
  9139. var index = 0;
  9140. var chr = feeder(index++);
  9141. while (chr != null) {
  9142. hash = ((hash << 5) - hash) + chr;
  9143. hash |= 0; // Convert to 32bit integer
  9144. chr = feeder(index++);
  9145. }
  9146. return hash;
  9147. };
  9148. /**
  9149. * Returns a promise that resolves after the given amount of time.
  9150. * @param delay Number of milliseconds to delay
  9151. * @returns Promise that resolves after the given amount of time
  9152. */
  9153. Tools.DelayAsync = function (delay) {
  9154. return new Promise(function (resolve) {
  9155. setTimeout(function () {
  9156. resolve();
  9157. }, delay);
  9158. });
  9159. };
  9160. Tools.BaseUrl = "";
  9161. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9162. /**
  9163. * Default behaviour for cors in the application.
  9164. * It can be a string if the expected behavior is identical in the entire app.
  9165. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9166. */
  9167. Tools.CorsBehavior = "anonymous";
  9168. Tools.UseFallbackTexture = true;
  9169. /**
  9170. * Use this object to register external classes like custom textures or material
  9171. * to allow the laoders to instantiate them
  9172. */
  9173. Tools.RegisteredExternalClasses = {};
  9174. // Used in case of a texture loading problem
  9175. 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";
  9176. Tools.PreprocessUrl = function (url) {
  9177. return url;
  9178. };
  9179. // Logs
  9180. Tools._NoneLogLevel = 0;
  9181. Tools._MessageLogLevel = 1;
  9182. Tools._WarningLogLevel = 2;
  9183. Tools._ErrorLogLevel = 4;
  9184. Tools._LogCache = "";
  9185. Tools.errorsCount = 0;
  9186. Tools.Log = Tools._LogEnabled;
  9187. Tools.Warn = Tools._WarnEnabled;
  9188. Tools.Error = Tools._ErrorEnabled;
  9189. // Performances
  9190. Tools._PerformanceNoneLogLevel = 0;
  9191. Tools._PerformanceUserMarkLogLevel = 1;
  9192. Tools._PerformanceConsoleLogLevel = 2;
  9193. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9194. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9195. return Tools;
  9196. }());
  9197. BABYLON.Tools = Tools;
  9198. /**
  9199. * This class is used to track a performance counter which is number based.
  9200. * The user has access to many properties which give statistics of different nature
  9201. *
  9202. * The implementer can track two kinds of Performance Counter: time and count
  9203. * 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.
  9204. * 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.
  9205. */
  9206. var PerfCounter = /** @class */ (function () {
  9207. function PerfCounter() {
  9208. this._startMonitoringTime = 0;
  9209. this._min = 0;
  9210. this._max = 0;
  9211. this._average = 0;
  9212. this._lastSecAverage = 0;
  9213. this._current = 0;
  9214. this._totalValueCount = 0;
  9215. this._totalAccumulated = 0;
  9216. this._lastSecAccumulated = 0;
  9217. this._lastSecTime = 0;
  9218. this._lastSecValueCount = 0;
  9219. }
  9220. Object.defineProperty(PerfCounter.prototype, "min", {
  9221. /**
  9222. * Returns the smallest value ever
  9223. */
  9224. get: function () {
  9225. return this._min;
  9226. },
  9227. enumerable: true,
  9228. configurable: true
  9229. });
  9230. Object.defineProperty(PerfCounter.prototype, "max", {
  9231. /**
  9232. * Returns the biggest value ever
  9233. */
  9234. get: function () {
  9235. return this._max;
  9236. },
  9237. enumerable: true,
  9238. configurable: true
  9239. });
  9240. Object.defineProperty(PerfCounter.prototype, "average", {
  9241. /**
  9242. * Returns the average value since the performance counter is running
  9243. */
  9244. get: function () {
  9245. return this._average;
  9246. },
  9247. enumerable: true,
  9248. configurable: true
  9249. });
  9250. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9251. /**
  9252. * Returns the average value of the last second the counter was monitored
  9253. */
  9254. get: function () {
  9255. return this._lastSecAverage;
  9256. },
  9257. enumerable: true,
  9258. configurable: true
  9259. });
  9260. Object.defineProperty(PerfCounter.prototype, "current", {
  9261. /**
  9262. * Returns the current value
  9263. */
  9264. get: function () {
  9265. return this._current;
  9266. },
  9267. enumerable: true,
  9268. configurable: true
  9269. });
  9270. Object.defineProperty(PerfCounter.prototype, "total", {
  9271. get: function () {
  9272. return this._totalAccumulated;
  9273. },
  9274. enumerable: true,
  9275. configurable: true
  9276. });
  9277. Object.defineProperty(PerfCounter.prototype, "count", {
  9278. get: function () {
  9279. return this._totalValueCount;
  9280. },
  9281. enumerable: true,
  9282. configurable: true
  9283. });
  9284. /**
  9285. * Call this method to start monitoring a new frame.
  9286. * 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.
  9287. */
  9288. PerfCounter.prototype.fetchNewFrame = function () {
  9289. this._totalValueCount++;
  9290. this._current = 0;
  9291. this._lastSecValueCount++;
  9292. };
  9293. /**
  9294. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9295. * @param newCount the count value to add to the monitored count
  9296. * @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.
  9297. */
  9298. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9299. if (!PerfCounter.Enabled) {
  9300. return;
  9301. }
  9302. this._current += newCount;
  9303. if (fetchResult) {
  9304. this._fetchResult();
  9305. }
  9306. };
  9307. /**
  9308. * Start monitoring this performance counter
  9309. */
  9310. PerfCounter.prototype.beginMonitoring = function () {
  9311. if (!PerfCounter.Enabled) {
  9312. return;
  9313. }
  9314. this._startMonitoringTime = Tools.Now;
  9315. };
  9316. /**
  9317. * Compute the time lapsed since the previous beginMonitoring() call.
  9318. * @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
  9319. */
  9320. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9321. if (newFrame === void 0) { newFrame = true; }
  9322. if (!PerfCounter.Enabled) {
  9323. return;
  9324. }
  9325. if (newFrame) {
  9326. this.fetchNewFrame();
  9327. }
  9328. var currentTime = Tools.Now;
  9329. this._current = currentTime - this._startMonitoringTime;
  9330. if (newFrame) {
  9331. this._fetchResult();
  9332. }
  9333. };
  9334. PerfCounter.prototype._fetchResult = function () {
  9335. this._totalAccumulated += this._current;
  9336. this._lastSecAccumulated += this._current;
  9337. // Min/Max update
  9338. this._min = Math.min(this._min, this._current);
  9339. this._max = Math.max(this._max, this._current);
  9340. this._average = this._totalAccumulated / this._totalValueCount;
  9341. // Reset last sec?
  9342. var now = Tools.Now;
  9343. if ((now - this._lastSecTime) > 1000) {
  9344. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9345. this._lastSecTime = now;
  9346. this._lastSecAccumulated = 0;
  9347. this._lastSecValueCount = 0;
  9348. }
  9349. };
  9350. PerfCounter.Enabled = true;
  9351. return PerfCounter;
  9352. }());
  9353. BABYLON.PerfCounter = PerfCounter;
  9354. /**
  9355. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9356. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9357. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9358. * @param name The name of the class, case should be preserved
  9359. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9360. */
  9361. function className(name, module) {
  9362. return function (target) {
  9363. target["__bjsclassName__"] = name;
  9364. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9365. };
  9366. }
  9367. BABYLON.className = className;
  9368. /**
  9369. * An implementation of a loop for asynchronous functions.
  9370. */
  9371. var AsyncLoop = /** @class */ (function () {
  9372. /**
  9373. * Constroctor.
  9374. * @param iterations the number of iterations.
  9375. * @param _fn the function to run each iteration
  9376. * @param _successCallback the callback that will be called upon succesful execution
  9377. * @param offset starting offset.
  9378. */
  9379. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9380. if (offset === void 0) { offset = 0; }
  9381. this.iterations = iterations;
  9382. this._fn = _fn;
  9383. this._successCallback = _successCallback;
  9384. this.index = offset - 1;
  9385. this._done = false;
  9386. }
  9387. /**
  9388. * Execute the next iteration. Must be called after the last iteration was finished.
  9389. */
  9390. AsyncLoop.prototype.executeNext = function () {
  9391. if (!this._done) {
  9392. if (this.index + 1 < this.iterations) {
  9393. ++this.index;
  9394. this._fn(this);
  9395. }
  9396. else {
  9397. this.breakLoop();
  9398. }
  9399. }
  9400. };
  9401. /**
  9402. * Break the loop and run the success callback.
  9403. */
  9404. AsyncLoop.prototype.breakLoop = function () {
  9405. this._done = true;
  9406. this._successCallback();
  9407. };
  9408. /**
  9409. * Helper function
  9410. */
  9411. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9412. if (offset === void 0) { offset = 0; }
  9413. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9414. loop.executeNext();
  9415. return loop;
  9416. };
  9417. /**
  9418. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9419. * @param iterations total number of iterations
  9420. * @param syncedIterations number of synchronous iterations in each async iteration.
  9421. * @param fn the function to call each iteration.
  9422. * @param callback a success call back that will be called when iterating stops.
  9423. * @param breakFunction a break condition (optional)
  9424. * @param timeout timeout settings for the setTimeout function. default - 0.
  9425. * @constructor
  9426. */
  9427. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9428. if (timeout === void 0) { timeout = 0; }
  9429. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9430. if (breakFunction && breakFunction())
  9431. loop.breakLoop();
  9432. else {
  9433. setTimeout(function () {
  9434. for (var i = 0; i < syncedIterations; ++i) {
  9435. var iteration = (loop.index * syncedIterations) + i;
  9436. if (iteration >= iterations)
  9437. break;
  9438. fn(iteration);
  9439. if (breakFunction && breakFunction()) {
  9440. loop.breakLoop();
  9441. break;
  9442. }
  9443. }
  9444. loop.executeNext();
  9445. }, timeout);
  9446. }
  9447. }, callback);
  9448. };
  9449. return AsyncLoop;
  9450. }());
  9451. BABYLON.AsyncLoop = AsyncLoop;
  9452. })(BABYLON || (BABYLON = {}));
  9453. //# sourceMappingURL=babylon.tools.js.map
  9454. var BABYLON;
  9455. (function (BABYLON) {
  9456. var PromiseStates;
  9457. (function (PromiseStates) {
  9458. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9459. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9460. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9461. })(PromiseStates || (PromiseStates = {}));
  9462. var FulFillmentAgregator = /** @class */ (function () {
  9463. function FulFillmentAgregator() {
  9464. this.count = 0;
  9465. this.target = 0;
  9466. this.results = [];
  9467. }
  9468. return FulFillmentAgregator;
  9469. }());
  9470. var InternalPromise = /** @class */ (function () {
  9471. function InternalPromise(resolver) {
  9472. var _this = this;
  9473. this._state = PromiseStates.Pending;
  9474. this._children = new Array();
  9475. this._rejectWasConsumed = false;
  9476. if (!resolver) {
  9477. return;
  9478. }
  9479. try {
  9480. resolver(function (value) {
  9481. _this._resolve(value);
  9482. }, function (reason) {
  9483. _this._reject(reason);
  9484. });
  9485. }
  9486. catch (e) {
  9487. this._reject(e);
  9488. }
  9489. }
  9490. InternalPromise.prototype.catch = function (onRejected) {
  9491. return this.then(undefined, onRejected);
  9492. };
  9493. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9494. var _this = this;
  9495. var newPromise = new InternalPromise();
  9496. newPromise._onFulfilled = onFulfilled;
  9497. newPromise._onRejected = onRejected;
  9498. // Composition
  9499. this._children.push(newPromise);
  9500. if (this._state !== PromiseStates.Pending) {
  9501. BABYLON.Tools.SetImmediate(function () {
  9502. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9503. var returnedValue = newPromise._resolve(_this._result);
  9504. if (returnedValue !== undefined && returnedValue !== null) {
  9505. if (returnedValue._state !== undefined) {
  9506. var returnedPromise = returnedValue;
  9507. newPromise._children.push(returnedPromise);
  9508. newPromise = returnedPromise;
  9509. }
  9510. else {
  9511. newPromise._result = returnedValue;
  9512. }
  9513. }
  9514. }
  9515. else {
  9516. newPromise._reject(_this._reason);
  9517. }
  9518. });
  9519. }
  9520. return newPromise;
  9521. };
  9522. InternalPromise.prototype._moveChildren = function (children) {
  9523. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9524. if (this._state === PromiseStates.Fulfilled) {
  9525. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9526. var child = _b[_i];
  9527. child._resolve(this._result);
  9528. }
  9529. }
  9530. else if (this._state === PromiseStates.Rejected) {
  9531. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9532. var child = _d[_c];
  9533. child._reject(this._reason);
  9534. }
  9535. }
  9536. var _a;
  9537. };
  9538. InternalPromise.prototype._resolve = function (value) {
  9539. try {
  9540. this._state = PromiseStates.Fulfilled;
  9541. this._result = value;
  9542. var returnedValue = null;
  9543. if (this._onFulfilled) {
  9544. returnedValue = this._onFulfilled(value);
  9545. }
  9546. if (returnedValue !== undefined && returnedValue !== null) {
  9547. if (returnedValue._state !== undefined) {
  9548. // Transmit children
  9549. var returnedPromise = returnedValue;
  9550. returnedPromise._moveChildren(this._children);
  9551. }
  9552. else {
  9553. value = returnedValue;
  9554. }
  9555. }
  9556. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9557. var child = _a[_i];
  9558. child._resolve(value);
  9559. }
  9560. this._children.length = 0;
  9561. delete this._onFulfilled;
  9562. delete this._onRejected;
  9563. return returnedValue;
  9564. }
  9565. catch (e) {
  9566. this._reject(e, true);
  9567. }
  9568. return null;
  9569. };
  9570. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9571. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9572. this._state = PromiseStates.Rejected;
  9573. this._reason = reason;
  9574. if (this._onRejected && !onLocalThrow) {
  9575. try {
  9576. this._onRejected(reason);
  9577. this._rejectWasConsumed = true;
  9578. }
  9579. catch (e) {
  9580. reason = e;
  9581. }
  9582. }
  9583. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9584. var child = _a[_i];
  9585. if (this._rejectWasConsumed) {
  9586. child._resolve(null);
  9587. }
  9588. else {
  9589. child._reject(reason);
  9590. }
  9591. }
  9592. this._children.length = 0;
  9593. delete this._onFulfilled;
  9594. delete this._onRejected;
  9595. };
  9596. InternalPromise.resolve = function (value) {
  9597. var newPromise = new InternalPromise();
  9598. newPromise._resolve(value);
  9599. return newPromise;
  9600. };
  9601. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9602. promise.then(function (value) {
  9603. agregator.results[index] = value;
  9604. agregator.count++;
  9605. if (agregator.count === agregator.target) {
  9606. agregator.rootPromise._resolve(agregator.results);
  9607. }
  9608. return null;
  9609. }, function (reason) {
  9610. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9611. agregator.rootPromise._reject(reason);
  9612. }
  9613. });
  9614. };
  9615. InternalPromise.all = function (promises) {
  9616. var newPromise = new InternalPromise();
  9617. var agregator = new FulFillmentAgregator();
  9618. agregator.target = promises.length;
  9619. agregator.rootPromise = newPromise;
  9620. if (promises.length) {
  9621. for (var index = 0; index < promises.length; index++) {
  9622. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9623. }
  9624. }
  9625. else {
  9626. newPromise._resolve([]);
  9627. }
  9628. return newPromise;
  9629. };
  9630. InternalPromise.race = function (promises) {
  9631. var newPromise = new InternalPromise();
  9632. if (promises.length) {
  9633. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9634. var promise = promises_1[_i];
  9635. promise.then(function (value) {
  9636. if (newPromise) {
  9637. newPromise._resolve(value);
  9638. newPromise = null;
  9639. }
  9640. return null;
  9641. }, function (reason) {
  9642. if (newPromise) {
  9643. newPromise._reject(reason);
  9644. newPromise = null;
  9645. }
  9646. });
  9647. }
  9648. }
  9649. return newPromise;
  9650. };
  9651. return InternalPromise;
  9652. }());
  9653. /**
  9654. * Helper class that provides a small promise polyfill
  9655. */
  9656. var PromisePolyfill = /** @class */ (function () {
  9657. function PromisePolyfill() {
  9658. }
  9659. /**
  9660. * Static function used to check if the polyfill is required
  9661. * If this is the case then the function will inject the polyfill to window.Promise
  9662. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9663. */
  9664. PromisePolyfill.Apply = function (force) {
  9665. if (force === void 0) { force = false; }
  9666. if (force || typeof Promise === 'undefined') {
  9667. var root = window;
  9668. root.Promise = InternalPromise;
  9669. }
  9670. };
  9671. return PromisePolyfill;
  9672. }());
  9673. BABYLON.PromisePolyfill = PromisePolyfill;
  9674. })(BABYLON || (BABYLON = {}));
  9675. //# sourceMappingURL=babylon.promise.js.map
  9676. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9677. var BABYLON;
  9678. (function (BABYLON) {
  9679. /**
  9680. * Helper class to push actions to a pool of workers.
  9681. */
  9682. var WorkerPool = /** @class */ (function () {
  9683. /**
  9684. * Constructor
  9685. * @param workers Array of workers to use for actions
  9686. */
  9687. function WorkerPool(workers) {
  9688. this._pendingActions = new Array();
  9689. this._workerInfos = workers.map(function (worker) { return ({
  9690. worker: worker,
  9691. active: false
  9692. }); });
  9693. }
  9694. /**
  9695. * Terminates all workers and clears any pending actions.
  9696. */
  9697. WorkerPool.prototype.dispose = function () {
  9698. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9699. var workerInfo = _a[_i];
  9700. workerInfo.worker.terminate();
  9701. }
  9702. delete this._workerInfos;
  9703. delete this._pendingActions;
  9704. };
  9705. /**
  9706. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9707. * pended until a worker has completed its action.
  9708. * @param action The action to perform. Call onComplete when the action is complete.
  9709. */
  9710. WorkerPool.prototype.push = function (action) {
  9711. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9712. var workerInfo = _a[_i];
  9713. if (!workerInfo.active) {
  9714. this._execute(workerInfo, action);
  9715. return;
  9716. }
  9717. }
  9718. this._pendingActions.push(action);
  9719. };
  9720. WorkerPool.prototype._execute = function (workerInfo, action) {
  9721. var _this = this;
  9722. workerInfo.active = true;
  9723. action(workerInfo.worker, function () {
  9724. workerInfo.active = false;
  9725. var nextAction = _this._pendingActions.shift();
  9726. if (nextAction) {
  9727. _this._execute(workerInfo, nextAction);
  9728. }
  9729. });
  9730. };
  9731. return WorkerPool;
  9732. }());
  9733. BABYLON.WorkerPool = WorkerPool;
  9734. })(BABYLON || (BABYLON = {}));
  9735. //# sourceMappingURL=babylon.workerPool.js.map
  9736. var BABYLON;
  9737. (function (BABYLON) {
  9738. var _AlphaState = /** @class */ (function () {
  9739. /**
  9740. * Initializes the state.
  9741. */
  9742. function _AlphaState() {
  9743. this._isAlphaBlendDirty = false;
  9744. this._isBlendFunctionParametersDirty = false;
  9745. this._isBlendEquationParametersDirty = false;
  9746. this._isBlendConstantsDirty = false;
  9747. this._alphaBlend = false;
  9748. this._blendFunctionParameters = new Array(4);
  9749. this._blendEquationParameters = new Array(2);
  9750. this._blendConstants = new Array(4);
  9751. this.reset();
  9752. }
  9753. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9754. get: function () {
  9755. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9756. },
  9757. enumerable: true,
  9758. configurable: true
  9759. });
  9760. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9761. get: function () {
  9762. return this._alphaBlend;
  9763. },
  9764. set: function (value) {
  9765. if (this._alphaBlend === value) {
  9766. return;
  9767. }
  9768. this._alphaBlend = value;
  9769. this._isAlphaBlendDirty = true;
  9770. },
  9771. enumerable: true,
  9772. configurable: true
  9773. });
  9774. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9775. if (this._blendConstants[0] === r &&
  9776. this._blendConstants[1] === g &&
  9777. this._blendConstants[2] === b &&
  9778. this._blendConstants[3] === a) {
  9779. return;
  9780. }
  9781. this._blendConstants[0] = r;
  9782. this._blendConstants[1] = g;
  9783. this._blendConstants[2] = b;
  9784. this._blendConstants[3] = a;
  9785. this._isBlendConstantsDirty = true;
  9786. };
  9787. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9788. if (this._blendFunctionParameters[0] === value0 &&
  9789. this._blendFunctionParameters[1] === value1 &&
  9790. this._blendFunctionParameters[2] === value2 &&
  9791. this._blendFunctionParameters[3] === value3) {
  9792. return;
  9793. }
  9794. this._blendFunctionParameters[0] = value0;
  9795. this._blendFunctionParameters[1] = value1;
  9796. this._blendFunctionParameters[2] = value2;
  9797. this._blendFunctionParameters[3] = value3;
  9798. this._isBlendFunctionParametersDirty = true;
  9799. };
  9800. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9801. if (this._blendEquationParameters[0] === rgb &&
  9802. this._blendEquationParameters[1] === alpha) {
  9803. return;
  9804. }
  9805. this._blendEquationParameters[0] = rgb;
  9806. this._blendEquationParameters[1] = alpha;
  9807. this._isBlendEquationParametersDirty = true;
  9808. };
  9809. _AlphaState.prototype.reset = function () {
  9810. this._alphaBlend = false;
  9811. this._blendFunctionParameters[0] = null;
  9812. this._blendFunctionParameters[1] = null;
  9813. this._blendFunctionParameters[2] = null;
  9814. this._blendFunctionParameters[3] = null;
  9815. this._blendEquationParameters[0] = null;
  9816. this._blendEquationParameters[1] = null;
  9817. this._blendConstants[0] = null;
  9818. this._blendConstants[1] = null;
  9819. this._blendConstants[2] = null;
  9820. this._blendConstants[3] = null;
  9821. this._isAlphaBlendDirty = true;
  9822. this._isBlendFunctionParametersDirty = false;
  9823. this._isBlendEquationParametersDirty = false;
  9824. this._isBlendConstantsDirty = false;
  9825. };
  9826. _AlphaState.prototype.apply = function (gl) {
  9827. if (!this.isDirty) {
  9828. return;
  9829. }
  9830. // Alpha blend
  9831. if (this._isAlphaBlendDirty) {
  9832. if (this._alphaBlend) {
  9833. gl.enable(gl.BLEND);
  9834. }
  9835. else {
  9836. gl.disable(gl.BLEND);
  9837. }
  9838. this._isAlphaBlendDirty = false;
  9839. }
  9840. // Alpha function
  9841. if (this._isBlendFunctionParametersDirty) {
  9842. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9843. this._isBlendFunctionParametersDirty = false;
  9844. }
  9845. // Alpha equation
  9846. if (this._isBlendEquationParametersDirty) {
  9847. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9848. this._isBlendEquationParametersDirty = false;
  9849. }
  9850. // Constants
  9851. if (this._isBlendConstantsDirty) {
  9852. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9853. this._isBlendConstantsDirty = false;
  9854. }
  9855. };
  9856. return _AlphaState;
  9857. }());
  9858. BABYLON._AlphaState = _AlphaState;
  9859. })(BABYLON || (BABYLON = {}));
  9860. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9861. var BABYLON;
  9862. (function (BABYLON) {
  9863. var _DepthCullingState = /** @class */ (function () {
  9864. /**
  9865. * Initializes the state.
  9866. */
  9867. function _DepthCullingState() {
  9868. this._isDepthTestDirty = false;
  9869. this._isDepthMaskDirty = false;
  9870. this._isDepthFuncDirty = false;
  9871. this._isCullFaceDirty = false;
  9872. this._isCullDirty = false;
  9873. this._isZOffsetDirty = false;
  9874. this._isFrontFaceDirty = false;
  9875. this.reset();
  9876. }
  9877. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9878. get: function () {
  9879. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9880. },
  9881. enumerable: true,
  9882. configurable: true
  9883. });
  9884. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9885. get: function () {
  9886. return this._zOffset;
  9887. },
  9888. set: function (value) {
  9889. if (this._zOffset === value) {
  9890. return;
  9891. }
  9892. this._zOffset = value;
  9893. this._isZOffsetDirty = true;
  9894. },
  9895. enumerable: true,
  9896. configurable: true
  9897. });
  9898. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9899. get: function () {
  9900. return this._cullFace;
  9901. },
  9902. set: function (value) {
  9903. if (this._cullFace === value) {
  9904. return;
  9905. }
  9906. this._cullFace = value;
  9907. this._isCullFaceDirty = true;
  9908. },
  9909. enumerable: true,
  9910. configurable: true
  9911. });
  9912. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9913. get: function () {
  9914. return this._cull;
  9915. },
  9916. set: function (value) {
  9917. if (this._cull === value) {
  9918. return;
  9919. }
  9920. this._cull = value;
  9921. this._isCullDirty = true;
  9922. },
  9923. enumerable: true,
  9924. configurable: true
  9925. });
  9926. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9927. get: function () {
  9928. return this._depthFunc;
  9929. },
  9930. set: function (value) {
  9931. if (this._depthFunc === value) {
  9932. return;
  9933. }
  9934. this._depthFunc = value;
  9935. this._isDepthFuncDirty = true;
  9936. },
  9937. enumerable: true,
  9938. configurable: true
  9939. });
  9940. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9941. get: function () {
  9942. return this._depthMask;
  9943. },
  9944. set: function (value) {
  9945. if (this._depthMask === value) {
  9946. return;
  9947. }
  9948. this._depthMask = value;
  9949. this._isDepthMaskDirty = true;
  9950. },
  9951. enumerable: true,
  9952. configurable: true
  9953. });
  9954. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9955. get: function () {
  9956. return this._depthTest;
  9957. },
  9958. set: function (value) {
  9959. if (this._depthTest === value) {
  9960. return;
  9961. }
  9962. this._depthTest = value;
  9963. this._isDepthTestDirty = true;
  9964. },
  9965. enumerable: true,
  9966. configurable: true
  9967. });
  9968. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9969. get: function () {
  9970. return this._frontFace;
  9971. },
  9972. set: function (value) {
  9973. if (this._frontFace === value) {
  9974. return;
  9975. }
  9976. this._frontFace = value;
  9977. this._isFrontFaceDirty = true;
  9978. },
  9979. enumerable: true,
  9980. configurable: true
  9981. });
  9982. _DepthCullingState.prototype.reset = function () {
  9983. this._depthMask = true;
  9984. this._depthTest = true;
  9985. this._depthFunc = null;
  9986. this._cullFace = null;
  9987. this._cull = null;
  9988. this._zOffset = 0;
  9989. this._frontFace = null;
  9990. this._isDepthTestDirty = true;
  9991. this._isDepthMaskDirty = true;
  9992. this._isDepthFuncDirty = false;
  9993. this._isCullFaceDirty = false;
  9994. this._isCullDirty = false;
  9995. this._isZOffsetDirty = false;
  9996. this._isFrontFaceDirty = false;
  9997. };
  9998. _DepthCullingState.prototype.apply = function (gl) {
  9999. if (!this.isDirty) {
  10000. return;
  10001. }
  10002. // Cull
  10003. if (this._isCullDirty) {
  10004. if (this.cull) {
  10005. gl.enable(gl.CULL_FACE);
  10006. }
  10007. else {
  10008. gl.disable(gl.CULL_FACE);
  10009. }
  10010. this._isCullDirty = false;
  10011. }
  10012. // Cull face
  10013. if (this._isCullFaceDirty) {
  10014. gl.cullFace(this.cullFace);
  10015. this._isCullFaceDirty = false;
  10016. }
  10017. // Depth mask
  10018. if (this._isDepthMaskDirty) {
  10019. gl.depthMask(this.depthMask);
  10020. this._isDepthMaskDirty = false;
  10021. }
  10022. // Depth test
  10023. if (this._isDepthTestDirty) {
  10024. if (this.depthTest) {
  10025. gl.enable(gl.DEPTH_TEST);
  10026. }
  10027. else {
  10028. gl.disable(gl.DEPTH_TEST);
  10029. }
  10030. this._isDepthTestDirty = false;
  10031. }
  10032. // Depth func
  10033. if (this._isDepthFuncDirty) {
  10034. gl.depthFunc(this.depthFunc);
  10035. this._isDepthFuncDirty = false;
  10036. }
  10037. // zOffset
  10038. if (this._isZOffsetDirty) {
  10039. if (this.zOffset) {
  10040. gl.enable(gl.POLYGON_OFFSET_FILL);
  10041. gl.polygonOffset(this.zOffset, 0);
  10042. }
  10043. else {
  10044. gl.disable(gl.POLYGON_OFFSET_FILL);
  10045. }
  10046. this._isZOffsetDirty = false;
  10047. }
  10048. // Front face
  10049. if (this._isFrontFaceDirty) {
  10050. gl.frontFace(this.frontFace);
  10051. this._isFrontFaceDirty = false;
  10052. }
  10053. };
  10054. return _DepthCullingState;
  10055. }());
  10056. BABYLON._DepthCullingState = _DepthCullingState;
  10057. })(BABYLON || (BABYLON = {}));
  10058. //# sourceMappingURL=babylon.depthCullingState.js.map
  10059. var BABYLON;
  10060. (function (BABYLON) {
  10061. var _StencilState = /** @class */ (function () {
  10062. function _StencilState() {
  10063. this._isStencilTestDirty = false;
  10064. this._isStencilMaskDirty = false;
  10065. this._isStencilFuncDirty = false;
  10066. this._isStencilOpDirty = false;
  10067. this.reset();
  10068. }
  10069. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10070. get: function () {
  10071. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10072. },
  10073. enumerable: true,
  10074. configurable: true
  10075. });
  10076. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10077. get: function () {
  10078. return this._stencilFunc;
  10079. },
  10080. set: function (value) {
  10081. if (this._stencilFunc === value) {
  10082. return;
  10083. }
  10084. this._stencilFunc = value;
  10085. this._isStencilFuncDirty = true;
  10086. },
  10087. enumerable: true,
  10088. configurable: true
  10089. });
  10090. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10091. get: function () {
  10092. return this._stencilFuncRef;
  10093. },
  10094. set: function (value) {
  10095. if (this._stencilFuncRef === value) {
  10096. return;
  10097. }
  10098. this._stencilFuncRef = value;
  10099. this._isStencilFuncDirty = true;
  10100. },
  10101. enumerable: true,
  10102. configurable: true
  10103. });
  10104. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10105. get: function () {
  10106. return this._stencilFuncMask;
  10107. },
  10108. set: function (value) {
  10109. if (this._stencilFuncMask === value) {
  10110. return;
  10111. }
  10112. this._stencilFuncMask = value;
  10113. this._isStencilFuncDirty = true;
  10114. },
  10115. enumerable: true,
  10116. configurable: true
  10117. });
  10118. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10119. get: function () {
  10120. return this._stencilOpStencilFail;
  10121. },
  10122. set: function (value) {
  10123. if (this._stencilOpStencilFail === value) {
  10124. return;
  10125. }
  10126. this._stencilOpStencilFail = value;
  10127. this._isStencilOpDirty = true;
  10128. },
  10129. enumerable: true,
  10130. configurable: true
  10131. });
  10132. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10133. get: function () {
  10134. return this._stencilOpDepthFail;
  10135. },
  10136. set: function (value) {
  10137. if (this._stencilOpDepthFail === value) {
  10138. return;
  10139. }
  10140. this._stencilOpDepthFail = value;
  10141. this._isStencilOpDirty = true;
  10142. },
  10143. enumerable: true,
  10144. configurable: true
  10145. });
  10146. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10147. get: function () {
  10148. return this._stencilOpStencilDepthPass;
  10149. },
  10150. set: function (value) {
  10151. if (this._stencilOpStencilDepthPass === value) {
  10152. return;
  10153. }
  10154. this._stencilOpStencilDepthPass = value;
  10155. this._isStencilOpDirty = true;
  10156. },
  10157. enumerable: true,
  10158. configurable: true
  10159. });
  10160. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10161. get: function () {
  10162. return this._stencilMask;
  10163. },
  10164. set: function (value) {
  10165. if (this._stencilMask === value) {
  10166. return;
  10167. }
  10168. this._stencilMask = value;
  10169. this._isStencilMaskDirty = true;
  10170. },
  10171. enumerable: true,
  10172. configurable: true
  10173. });
  10174. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10175. get: function () {
  10176. return this._stencilTest;
  10177. },
  10178. set: function (value) {
  10179. if (this._stencilTest === value) {
  10180. return;
  10181. }
  10182. this._stencilTest = value;
  10183. this._isStencilTestDirty = true;
  10184. },
  10185. enumerable: true,
  10186. configurable: true
  10187. });
  10188. _StencilState.prototype.reset = function () {
  10189. this._stencilTest = false;
  10190. this._stencilMask = 0xFF;
  10191. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10192. this._stencilFuncRef = 1;
  10193. this._stencilFuncMask = 0xFF;
  10194. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10195. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10196. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10197. this._isStencilTestDirty = true;
  10198. this._isStencilMaskDirty = true;
  10199. this._isStencilFuncDirty = true;
  10200. this._isStencilOpDirty = true;
  10201. };
  10202. _StencilState.prototype.apply = function (gl) {
  10203. if (!this.isDirty) {
  10204. return;
  10205. }
  10206. // Stencil test
  10207. if (this._isStencilTestDirty) {
  10208. if (this.stencilTest) {
  10209. gl.enable(gl.STENCIL_TEST);
  10210. }
  10211. else {
  10212. gl.disable(gl.STENCIL_TEST);
  10213. }
  10214. this._isStencilTestDirty = false;
  10215. }
  10216. // Stencil mask
  10217. if (this._isStencilMaskDirty) {
  10218. gl.stencilMask(this.stencilMask);
  10219. this._isStencilMaskDirty = false;
  10220. }
  10221. // Stencil func
  10222. if (this._isStencilFuncDirty) {
  10223. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10224. this._isStencilFuncDirty = false;
  10225. }
  10226. // Stencil op
  10227. if (this._isStencilOpDirty) {
  10228. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10229. this._isStencilOpDirty = false;
  10230. }
  10231. };
  10232. return _StencilState;
  10233. }());
  10234. BABYLON._StencilState = _StencilState;
  10235. })(BABYLON || (BABYLON = {}));
  10236. //# sourceMappingURL=babylon.stencilState.js.map
  10237. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10238. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10239. s = arguments[i];
  10240. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10241. t[p] = s[p];
  10242. }
  10243. return t;
  10244. };
  10245. var BABYLON;
  10246. (function (BABYLON) {
  10247. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10248. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10249. };
  10250. var compileRawShader = function (gl, source, type) {
  10251. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10252. gl.shaderSource(shader, source);
  10253. gl.compileShader(shader);
  10254. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10255. var log = gl.getShaderInfoLog(shader);
  10256. if (log) {
  10257. throw new Error(log);
  10258. }
  10259. }
  10260. if (!shader) {
  10261. throw new Error("Something went wrong while compile the shader.");
  10262. }
  10263. return shader;
  10264. };
  10265. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10266. var magFilter = gl.NEAREST;
  10267. var minFilter = gl.NEAREST;
  10268. switch (samplingMode) {
  10269. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10270. magFilter = gl.LINEAR;
  10271. if (generateMipMaps) {
  10272. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10273. }
  10274. else {
  10275. minFilter = gl.LINEAR;
  10276. }
  10277. break;
  10278. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10279. magFilter = gl.LINEAR;
  10280. if (generateMipMaps) {
  10281. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10282. }
  10283. else {
  10284. minFilter = gl.LINEAR;
  10285. }
  10286. break;
  10287. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10288. magFilter = gl.NEAREST;
  10289. if (generateMipMaps) {
  10290. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10291. }
  10292. else {
  10293. minFilter = gl.NEAREST;
  10294. }
  10295. break;
  10296. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10297. magFilter = gl.NEAREST;
  10298. if (generateMipMaps) {
  10299. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10300. }
  10301. else {
  10302. minFilter = gl.NEAREST;
  10303. }
  10304. break;
  10305. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10306. magFilter = gl.NEAREST;
  10307. if (generateMipMaps) {
  10308. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10309. }
  10310. else {
  10311. minFilter = gl.LINEAR;
  10312. }
  10313. break;
  10314. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10315. magFilter = gl.NEAREST;
  10316. if (generateMipMaps) {
  10317. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10318. }
  10319. else {
  10320. minFilter = gl.LINEAR;
  10321. }
  10322. break;
  10323. case BABYLON.Texture.NEAREST_LINEAR:
  10324. magFilter = gl.NEAREST;
  10325. minFilter = gl.LINEAR;
  10326. break;
  10327. case BABYLON.Texture.NEAREST_NEAREST:
  10328. magFilter = gl.NEAREST;
  10329. minFilter = gl.NEAREST;
  10330. break;
  10331. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10332. magFilter = gl.LINEAR;
  10333. if (generateMipMaps) {
  10334. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10335. }
  10336. else {
  10337. minFilter = gl.NEAREST;
  10338. }
  10339. break;
  10340. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10341. magFilter = gl.LINEAR;
  10342. if (generateMipMaps) {
  10343. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10344. }
  10345. else {
  10346. minFilter = gl.NEAREST;
  10347. }
  10348. break;
  10349. case BABYLON.Texture.LINEAR_LINEAR:
  10350. magFilter = gl.LINEAR;
  10351. minFilter = gl.LINEAR;
  10352. break;
  10353. case BABYLON.Texture.LINEAR_NEAREST:
  10354. magFilter = gl.LINEAR;
  10355. minFilter = gl.NEAREST;
  10356. break;
  10357. }
  10358. return {
  10359. min: minFilter,
  10360. mag: magFilter
  10361. };
  10362. };
  10363. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10364. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10365. var img;
  10366. var onload = function () {
  10367. loadedImages[index] = img;
  10368. loadedImages._internalCount++;
  10369. if (scene) {
  10370. scene._removePendingData(img);
  10371. }
  10372. if (loadedImages._internalCount === 6) {
  10373. onfinish(loadedImages);
  10374. }
  10375. };
  10376. var onerror = function (message, exception) {
  10377. if (scene) {
  10378. scene._removePendingData(img);
  10379. }
  10380. if (onErrorCallBack) {
  10381. onErrorCallBack(message, exception);
  10382. }
  10383. };
  10384. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10385. if (scene) {
  10386. scene._addPendingData(img);
  10387. }
  10388. };
  10389. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10390. if (onError === void 0) { onError = null; }
  10391. var loadedImages = [];
  10392. loadedImages._internalCount = 0;
  10393. for (var index = 0; index < 6; index++) {
  10394. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10395. }
  10396. };
  10397. var BufferPointer = /** @class */ (function () {
  10398. function BufferPointer() {
  10399. }
  10400. return BufferPointer;
  10401. }());
  10402. var InstancingAttributeInfo = /** @class */ (function () {
  10403. function InstancingAttributeInfo() {
  10404. }
  10405. return InstancingAttributeInfo;
  10406. }());
  10407. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10408. /**
  10409. * Define options used to create a render target texture
  10410. */
  10411. var RenderTargetCreationOptions = /** @class */ (function () {
  10412. function RenderTargetCreationOptions() {
  10413. }
  10414. return RenderTargetCreationOptions;
  10415. }());
  10416. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10417. /**
  10418. * Define options used to create a depth texture
  10419. */
  10420. var DepthTextureCreationOptions = /** @class */ (function () {
  10421. function DepthTextureCreationOptions() {
  10422. }
  10423. return DepthTextureCreationOptions;
  10424. }());
  10425. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10426. /**
  10427. * Regroup several parameters relative to the browser in use
  10428. */
  10429. var EngineCapabilities = /** @class */ (function () {
  10430. function EngineCapabilities() {
  10431. }
  10432. return EngineCapabilities;
  10433. }());
  10434. BABYLON.EngineCapabilities = EngineCapabilities;
  10435. /**
  10436. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10437. */
  10438. var Engine = /** @class */ (function () {
  10439. /**
  10440. * @constructor
  10441. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10442. * @param antialias defines enable antialiasing (default: false)
  10443. * @param options defines further options to be sent to the getContext() function
  10444. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10445. */
  10446. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10447. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10448. var _this = this;
  10449. // Public members
  10450. this.forcePOTTextures = false;
  10451. this.isFullscreen = false;
  10452. this.isPointerLock = false;
  10453. this.cullBackFaces = true;
  10454. this.renderEvenInBackground = true;
  10455. this.preventCacheWipeBetweenFrames = false;
  10456. // To enable/disable IDB support and avoid XHR on .manifest
  10457. this.enableOfflineSupport = false;
  10458. this.scenes = new Array();
  10459. this.postProcesses = new Array();
  10460. // Observables
  10461. /**
  10462. * Observable event triggered each time the rendering canvas is resized
  10463. */
  10464. this.onResizeObservable = new BABYLON.Observable();
  10465. /**
  10466. * Observable event triggered each time the canvas loses focus
  10467. */
  10468. this.onCanvasBlurObservable = new BABYLON.Observable();
  10469. /**
  10470. * Observable event triggered each time the canvas gains focus
  10471. */
  10472. this.onCanvasFocusObservable = new BABYLON.Observable();
  10473. /**
  10474. * Observable event triggered each time the canvas receives pointerout event
  10475. */
  10476. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10477. /**
  10478. * Observable event triggered before each texture is initialized
  10479. */
  10480. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10481. //WebVR
  10482. this._vrDisplay = undefined;
  10483. this._vrSupported = false;
  10484. this._vrExclusivePointerMode = false;
  10485. // Uniform buffers list
  10486. this.disableUniformBuffers = false;
  10487. this._uniformBuffers = new Array();
  10488. // Observables
  10489. /**
  10490. * Observable raised when the engine begins a new frame
  10491. */
  10492. this.onBeginFrameObservable = new BABYLON.Observable();
  10493. /**
  10494. * Observable raised when the engine ends the current frame
  10495. */
  10496. this.onEndFrameObservable = new BABYLON.Observable();
  10497. /**
  10498. * Observable raised when the engine is about to compile a shader
  10499. */
  10500. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10501. /**
  10502. * Observable raised when the engine has jsut compiled a shader
  10503. */
  10504. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10505. this._windowIsBackground = false;
  10506. this._webGLVersion = 1.0;
  10507. this._badOS = false;
  10508. this._badDesktopOS = false;
  10509. /**
  10510. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10511. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10512. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10513. */
  10514. this.disableTextureBindingOptimization = false;
  10515. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10516. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10517. this.onVRRequestPresentStart = new BABYLON.Observable();
  10518. this._colorWrite = true;
  10519. this._drawCalls = new BABYLON.PerfCounter();
  10520. this._textureCollisions = new BABYLON.PerfCounter();
  10521. this._renderingQueueLaunched = false;
  10522. this._activeRenderLoops = new Array();
  10523. // Deterministic lockstepMaxSteps
  10524. this._deterministicLockstep = false;
  10525. this._lockstepMaxSteps = 4;
  10526. // Lost context
  10527. this.onContextLostObservable = new BABYLON.Observable();
  10528. this.onContextRestoredObservable = new BABYLON.Observable();
  10529. this._contextWasLost = false;
  10530. this._doNotHandleContextLost = false;
  10531. // FPS
  10532. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10533. this._fps = 60;
  10534. this._deltaTime = 0;
  10535. /**
  10536. * Turn this value on if you want to pause FPS computation when in background
  10537. */
  10538. this.disablePerformanceMonitorInBackground = false;
  10539. // States
  10540. this._depthCullingState = new BABYLON._DepthCullingState();
  10541. this._stencilState = new BABYLON._StencilState();
  10542. this._alphaState = new BABYLON._AlphaState();
  10543. this._alphaMode = Engine.ALPHA_DISABLE;
  10544. // Cache
  10545. this._internalTexturesCache = new Array();
  10546. this._activeChannel = 0;
  10547. this._currentTextureChannel = -1;
  10548. this._boundTexturesCache = {};
  10549. this._compiledEffects = {};
  10550. this._vertexAttribArraysEnabled = [];
  10551. this._uintIndicesCurrentlySet = false;
  10552. this._currentBoundBuffer = new Array();
  10553. this._currentBufferPointers = new Array();
  10554. this._currentInstanceLocations = new Array();
  10555. this._currentInstanceBuffers = new Array();
  10556. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10557. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10558. this._vaoRecordInProgress = false;
  10559. this._mustWipeVertexAttributes = false;
  10560. this._nextFreeTextureSlots = new Array();
  10561. this._maxSimultaneousTextures = 0;
  10562. this._activeRequests = new Array();
  10563. // Hardware supported Compressed Textures
  10564. this._texturesSupported = new Array();
  10565. this._onVRFullScreenTriggered = function () {
  10566. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10567. //get the old size before we change
  10568. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10569. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10570. //get the width and height, change the render size
  10571. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10572. _this.setHardwareScalingLevel(1);
  10573. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10574. }
  10575. else {
  10576. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10577. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10578. }
  10579. };
  10580. this._boundUniforms = {};
  10581. // Register promises
  10582. BABYLON.PromisePolyfill.Apply();
  10583. var canvas = null;
  10584. Engine.Instances.push(this);
  10585. if (!canvasOrContext) {
  10586. return;
  10587. }
  10588. options = options || {};
  10589. if (canvasOrContext.getContext) {
  10590. canvas = canvasOrContext;
  10591. this._renderingCanvas = canvas;
  10592. if (antialias != null) {
  10593. options.antialias = antialias;
  10594. }
  10595. if (options.deterministicLockstep === undefined) {
  10596. options.deterministicLockstep = false;
  10597. }
  10598. if (options.lockstepMaxSteps === undefined) {
  10599. options.lockstepMaxSteps = 4;
  10600. }
  10601. if (options.preserveDrawingBuffer === undefined) {
  10602. options.preserveDrawingBuffer = false;
  10603. }
  10604. if (options.audioEngine === undefined) {
  10605. options.audioEngine = true;
  10606. }
  10607. if (options.stencil === undefined) {
  10608. options.stencil = true;
  10609. }
  10610. this._deterministicLockstep = options.deterministicLockstep;
  10611. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10612. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10613. // Exceptions
  10614. if (navigator && navigator.userAgent) {
  10615. var ua = navigator.userAgent;
  10616. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10617. var exception = _a[_i];
  10618. var key = exception.key;
  10619. var targets = exception.targets;
  10620. if (ua.indexOf(key) > -1) {
  10621. if (exception.capture && exception.captureConstraint) {
  10622. var capture = exception.capture;
  10623. var constraint = exception.captureConstraint;
  10624. var regex = new RegExp(capture);
  10625. var matches = regex.exec(ua);
  10626. if (matches && matches.length > 0) {
  10627. var capturedValue = parseInt(matches[matches.length - 1]);
  10628. if (capturedValue >= constraint) {
  10629. continue;
  10630. }
  10631. }
  10632. }
  10633. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10634. var target = targets_1[_b];
  10635. switch (target) {
  10636. case "uniformBuffer":
  10637. this.disableUniformBuffers = true;
  10638. break;
  10639. case "textureBindingOptimization":
  10640. this.disableTextureBindingOptimization = true;
  10641. break;
  10642. }
  10643. }
  10644. }
  10645. }
  10646. }
  10647. // GL
  10648. if (!options.disableWebGL2Support) {
  10649. try {
  10650. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10651. if (this._gl) {
  10652. this._webGLVersion = 2.0;
  10653. }
  10654. }
  10655. catch (e) {
  10656. // Do nothing
  10657. }
  10658. }
  10659. if (!this._gl) {
  10660. if (!canvas) {
  10661. throw new Error("The provided canvas is null or undefined.");
  10662. }
  10663. try {
  10664. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10665. }
  10666. catch (e) {
  10667. throw new Error("WebGL not supported");
  10668. }
  10669. }
  10670. if (!this._gl) {
  10671. throw new Error("WebGL not supported");
  10672. }
  10673. this._onCanvasFocus = function () {
  10674. _this.onCanvasFocusObservable.notifyObservers(_this);
  10675. };
  10676. this._onCanvasBlur = function () {
  10677. _this.onCanvasBlurObservable.notifyObservers(_this);
  10678. };
  10679. canvas.addEventListener("focus", this._onCanvasFocus);
  10680. canvas.addEventListener("blur", this._onCanvasBlur);
  10681. this._onBlur = function () {
  10682. if (_this.disablePerformanceMonitorInBackground) {
  10683. _this._performanceMonitor.disable();
  10684. }
  10685. _this._windowIsBackground = true;
  10686. };
  10687. this._onFocus = function () {
  10688. if (_this.disablePerformanceMonitorInBackground) {
  10689. _this._performanceMonitor.enable();
  10690. }
  10691. _this._windowIsBackground = false;
  10692. };
  10693. this._onCanvasPointerOut = function (ev) {
  10694. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10695. };
  10696. window.addEventListener("blur", this._onBlur);
  10697. window.addEventListener("focus", this._onFocus);
  10698. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10699. // Context lost
  10700. if (!this._doNotHandleContextLost) {
  10701. this._onContextLost = function (evt) {
  10702. evt.preventDefault();
  10703. _this._contextWasLost = true;
  10704. BABYLON.Tools.Warn("WebGL context lost.");
  10705. _this.onContextLostObservable.notifyObservers(_this);
  10706. };
  10707. this._onContextRestored = function (evt) {
  10708. // Adding a timeout to avoid race condition at browser level
  10709. setTimeout(function () {
  10710. // Rebuild gl context
  10711. _this._initGLContext();
  10712. // Rebuild effects
  10713. _this._rebuildEffects();
  10714. // Rebuild textures
  10715. _this._rebuildInternalTextures();
  10716. // Rebuild buffers
  10717. _this._rebuildBuffers();
  10718. // Cache
  10719. _this.wipeCaches(true);
  10720. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10721. _this.onContextRestoredObservable.notifyObservers(_this);
  10722. _this._contextWasLost = false;
  10723. }, 0);
  10724. };
  10725. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10726. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10727. }
  10728. }
  10729. else {
  10730. this._gl = canvasOrContext;
  10731. this._renderingCanvas = this._gl.canvas;
  10732. if (this._gl.renderbufferStorageMultisample) {
  10733. this._webGLVersion = 2.0;
  10734. }
  10735. options.stencil = this._gl.getContextAttributes().stencil;
  10736. }
  10737. // Viewport
  10738. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10739. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10740. this.resize();
  10741. this._isStencilEnable = options.stencil ? true : false;
  10742. this._initGLContext();
  10743. if (canvas) {
  10744. // Fullscreen
  10745. this._onFullscreenChange = function () {
  10746. if (document.fullscreen !== undefined) {
  10747. _this.isFullscreen = document.fullscreen;
  10748. }
  10749. else if (document.mozFullScreen !== undefined) {
  10750. _this.isFullscreen = document.mozFullScreen;
  10751. }
  10752. else if (document.webkitIsFullScreen !== undefined) {
  10753. _this.isFullscreen = document.webkitIsFullScreen;
  10754. }
  10755. else if (document.msIsFullScreen !== undefined) {
  10756. _this.isFullscreen = document.msIsFullScreen;
  10757. }
  10758. // Pointer lock
  10759. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10760. canvas.requestPointerLock = canvas.requestPointerLock ||
  10761. canvas.msRequestPointerLock ||
  10762. canvas.mozRequestPointerLock ||
  10763. canvas.webkitRequestPointerLock;
  10764. if (canvas.requestPointerLock) {
  10765. canvas.requestPointerLock();
  10766. }
  10767. }
  10768. };
  10769. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10770. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10771. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10772. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10773. // Pointer lock
  10774. this._onPointerLockChange = function () {
  10775. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10776. document.webkitPointerLockElement === canvas ||
  10777. document.msPointerLockElement === canvas ||
  10778. document.pointerLockElement === canvas);
  10779. };
  10780. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10781. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10782. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10783. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10784. this._onVRDisplayPointerRestricted = function () {
  10785. if (canvas) {
  10786. canvas.requestPointerLock();
  10787. }
  10788. };
  10789. this._onVRDisplayPointerUnrestricted = function () {
  10790. document.exitPointerLock();
  10791. };
  10792. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10793. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10794. }
  10795. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10796. Engine.audioEngine = new BABYLON.AudioEngine();
  10797. }
  10798. // Prepare buffer pointers
  10799. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10800. this._currentBufferPointers[i] = new BufferPointer();
  10801. }
  10802. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10803. // Load WebVR Devices
  10804. if (options.autoEnableWebVR) {
  10805. this.initWebVR();
  10806. }
  10807. // Detect if we are running on a faulty buggy OS.
  10808. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10809. // Detect if we are running on a faulty buggy desktop OS.
  10810. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10811. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10812. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10813. }
  10814. Object.defineProperty(Engine, "LastCreatedEngine", {
  10815. get: function () {
  10816. if (Engine.Instances.length === 0) {
  10817. return null;
  10818. }
  10819. return Engine.Instances[Engine.Instances.length - 1];
  10820. },
  10821. enumerable: true,
  10822. configurable: true
  10823. });
  10824. Object.defineProperty(Engine, "LastCreatedScene", {
  10825. get: function () {
  10826. var lastCreatedEngine = Engine.LastCreatedEngine;
  10827. if (!lastCreatedEngine) {
  10828. return null;
  10829. }
  10830. if (lastCreatedEngine.scenes.length === 0) {
  10831. return null;
  10832. }
  10833. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10834. },
  10835. enumerable: true,
  10836. configurable: true
  10837. });
  10838. /**
  10839. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10840. */
  10841. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10842. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10843. var engine = Engine.Instances[engineIndex];
  10844. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10845. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10846. }
  10847. }
  10848. };
  10849. Object.defineProperty(Engine, "NEVER", {
  10850. get: function () {
  10851. return Engine._NEVER;
  10852. },
  10853. enumerable: true,
  10854. configurable: true
  10855. });
  10856. Object.defineProperty(Engine, "ALWAYS", {
  10857. get: function () {
  10858. return Engine._ALWAYS;
  10859. },
  10860. enumerable: true,
  10861. configurable: true
  10862. });
  10863. Object.defineProperty(Engine, "LESS", {
  10864. get: function () {
  10865. return Engine._LESS;
  10866. },
  10867. enumerable: true,
  10868. configurable: true
  10869. });
  10870. Object.defineProperty(Engine, "EQUAL", {
  10871. get: function () {
  10872. return Engine._EQUAL;
  10873. },
  10874. enumerable: true,
  10875. configurable: true
  10876. });
  10877. Object.defineProperty(Engine, "LEQUAL", {
  10878. get: function () {
  10879. return Engine._LEQUAL;
  10880. },
  10881. enumerable: true,
  10882. configurable: true
  10883. });
  10884. Object.defineProperty(Engine, "GREATER", {
  10885. get: function () {
  10886. return Engine._GREATER;
  10887. },
  10888. enumerable: true,
  10889. configurable: true
  10890. });
  10891. Object.defineProperty(Engine, "GEQUAL", {
  10892. get: function () {
  10893. return Engine._GEQUAL;
  10894. },
  10895. enumerable: true,
  10896. configurable: true
  10897. });
  10898. Object.defineProperty(Engine, "NOTEQUAL", {
  10899. get: function () {
  10900. return Engine._NOTEQUAL;
  10901. },
  10902. enumerable: true,
  10903. configurable: true
  10904. });
  10905. Object.defineProperty(Engine, "KEEP", {
  10906. get: function () {
  10907. return Engine._KEEP;
  10908. },
  10909. enumerable: true,
  10910. configurable: true
  10911. });
  10912. Object.defineProperty(Engine, "REPLACE", {
  10913. get: function () {
  10914. return Engine._REPLACE;
  10915. },
  10916. enumerable: true,
  10917. configurable: true
  10918. });
  10919. Object.defineProperty(Engine, "INCR", {
  10920. get: function () {
  10921. return Engine._INCR;
  10922. },
  10923. enumerable: true,
  10924. configurable: true
  10925. });
  10926. Object.defineProperty(Engine, "DECR", {
  10927. get: function () {
  10928. return Engine._DECR;
  10929. },
  10930. enumerable: true,
  10931. configurable: true
  10932. });
  10933. Object.defineProperty(Engine, "INVERT", {
  10934. get: function () {
  10935. return Engine._INVERT;
  10936. },
  10937. enumerable: true,
  10938. configurable: true
  10939. });
  10940. Object.defineProperty(Engine, "INCR_WRAP", {
  10941. get: function () {
  10942. return Engine._INCR_WRAP;
  10943. },
  10944. enumerable: true,
  10945. configurable: true
  10946. });
  10947. Object.defineProperty(Engine, "DECR_WRAP", {
  10948. get: function () {
  10949. return Engine._DECR_WRAP;
  10950. },
  10951. enumerable: true,
  10952. configurable: true
  10953. });
  10954. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10955. get: function () {
  10956. return Engine._ALPHA_DISABLE;
  10957. },
  10958. enumerable: true,
  10959. configurable: true
  10960. });
  10961. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10962. get: function () {
  10963. return Engine._ALPHA_ONEONE;
  10964. },
  10965. enumerable: true,
  10966. configurable: true
  10967. });
  10968. Object.defineProperty(Engine, "ALPHA_ADD", {
  10969. get: function () {
  10970. return Engine._ALPHA_ADD;
  10971. },
  10972. enumerable: true,
  10973. configurable: true
  10974. });
  10975. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10976. get: function () {
  10977. return Engine._ALPHA_COMBINE;
  10978. },
  10979. enumerable: true,
  10980. configurable: true
  10981. });
  10982. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10983. get: function () {
  10984. return Engine._ALPHA_SUBTRACT;
  10985. },
  10986. enumerable: true,
  10987. configurable: true
  10988. });
  10989. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10990. get: function () {
  10991. return Engine._ALPHA_MULTIPLY;
  10992. },
  10993. enumerable: true,
  10994. configurable: true
  10995. });
  10996. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10997. get: function () {
  10998. return Engine._ALPHA_MAXIMIZED;
  10999. },
  11000. enumerable: true,
  11001. configurable: true
  11002. });
  11003. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11004. get: function () {
  11005. return Engine._ALPHA_PREMULTIPLIED;
  11006. },
  11007. enumerable: true,
  11008. configurable: true
  11009. });
  11010. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11011. get: function () {
  11012. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11013. },
  11014. enumerable: true,
  11015. configurable: true
  11016. });
  11017. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11018. get: function () {
  11019. return Engine._ALPHA_INTERPOLATE;
  11020. },
  11021. enumerable: true,
  11022. configurable: true
  11023. });
  11024. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11025. get: function () {
  11026. return Engine._ALPHA_SCREENMODE;
  11027. },
  11028. enumerable: true,
  11029. configurable: true
  11030. });
  11031. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11032. get: function () {
  11033. return Engine._DELAYLOADSTATE_NONE;
  11034. },
  11035. enumerable: true,
  11036. configurable: true
  11037. });
  11038. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11039. get: function () {
  11040. return Engine._DELAYLOADSTATE_LOADED;
  11041. },
  11042. enumerable: true,
  11043. configurable: true
  11044. });
  11045. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11046. get: function () {
  11047. return Engine._DELAYLOADSTATE_LOADING;
  11048. },
  11049. enumerable: true,
  11050. configurable: true
  11051. });
  11052. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11053. get: function () {
  11054. return Engine._DELAYLOADSTATE_NOTLOADED;
  11055. },
  11056. enumerable: true,
  11057. configurable: true
  11058. });
  11059. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11060. get: function () {
  11061. return Engine._TEXTUREFORMAT_ALPHA;
  11062. },
  11063. enumerable: true,
  11064. configurable: true
  11065. });
  11066. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11067. get: function () {
  11068. return Engine._TEXTUREFORMAT_LUMINANCE;
  11069. },
  11070. enumerable: true,
  11071. configurable: true
  11072. });
  11073. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11074. /**
  11075. * R32F
  11076. */
  11077. get: function () {
  11078. return Engine._TEXTUREFORMAT_R32F;
  11079. },
  11080. enumerable: true,
  11081. configurable: true
  11082. });
  11083. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11084. /**
  11085. * RG32F
  11086. */
  11087. get: function () {
  11088. return Engine._TEXTUREFORMAT_RG32F;
  11089. },
  11090. enumerable: true,
  11091. configurable: true
  11092. });
  11093. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11094. /**
  11095. * RGB32F
  11096. */
  11097. get: function () {
  11098. return Engine._TEXTUREFORMAT_RGB32F;
  11099. },
  11100. enumerable: true,
  11101. configurable: true
  11102. });
  11103. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11104. /**
  11105. * RGBA32F
  11106. */
  11107. get: function () {
  11108. return Engine._TEXTUREFORMAT_RGBA32F;
  11109. },
  11110. enumerable: true,
  11111. configurable: true
  11112. });
  11113. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11114. get: function () {
  11115. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11116. },
  11117. enumerable: true,
  11118. configurable: true
  11119. });
  11120. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11121. get: function () {
  11122. return Engine._TEXTUREFORMAT_RGB;
  11123. },
  11124. enumerable: true,
  11125. configurable: true
  11126. });
  11127. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11128. get: function () {
  11129. return Engine._TEXTUREFORMAT_RGBA;
  11130. },
  11131. enumerable: true,
  11132. configurable: true
  11133. });
  11134. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11135. get: function () {
  11136. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11137. },
  11138. enumerable: true,
  11139. configurable: true
  11140. });
  11141. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11142. get: function () {
  11143. return Engine._TEXTURETYPE_FLOAT;
  11144. },
  11145. enumerable: true,
  11146. configurable: true
  11147. });
  11148. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11149. get: function () {
  11150. return Engine._TEXTURETYPE_HALF_FLOAT;
  11151. },
  11152. enumerable: true,
  11153. configurable: true
  11154. });
  11155. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11156. get: function () {
  11157. return Engine._SCALEMODE_FLOOR;
  11158. },
  11159. enumerable: true,
  11160. configurable: true
  11161. });
  11162. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11163. get: function () {
  11164. return Engine._SCALEMODE_NEAREST;
  11165. },
  11166. enumerable: true,
  11167. configurable: true
  11168. });
  11169. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11170. get: function () {
  11171. return Engine._SCALEMODE_CEILING;
  11172. },
  11173. enumerable: true,
  11174. configurable: true
  11175. });
  11176. Object.defineProperty(Engine, "Version", {
  11177. get: function () {
  11178. return "3.2.0-alphaC";
  11179. },
  11180. enumerable: true,
  11181. configurable: true
  11182. });
  11183. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11184. get: function () {
  11185. return this._vrExclusivePointerMode;
  11186. },
  11187. enumerable: true,
  11188. configurable: true
  11189. });
  11190. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11191. get: function () {
  11192. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11193. },
  11194. enumerable: true,
  11195. configurable: true
  11196. });
  11197. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11198. get: function () {
  11199. return this._webGLVersion < 2 || this.forcePOTTextures;
  11200. },
  11201. enumerable: true,
  11202. configurable: true
  11203. });
  11204. Object.defineProperty(Engine.prototype, "badOS", {
  11205. get: function () {
  11206. return this._badOS;
  11207. },
  11208. enumerable: true,
  11209. configurable: true
  11210. });
  11211. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11212. get: function () {
  11213. return this._badDesktopOS;
  11214. },
  11215. enumerable: true,
  11216. configurable: true
  11217. });
  11218. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11219. get: function () {
  11220. return this._performanceMonitor;
  11221. },
  11222. enumerable: true,
  11223. configurable: true
  11224. });
  11225. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11226. get: function () {
  11227. return this._texturesSupported;
  11228. },
  11229. enumerable: true,
  11230. configurable: true
  11231. });
  11232. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11233. get: function () {
  11234. return this._textureFormatInUse;
  11235. },
  11236. enumerable: true,
  11237. configurable: true
  11238. });
  11239. Object.defineProperty(Engine.prototype, "currentViewport", {
  11240. get: function () {
  11241. return this._cachedViewport;
  11242. },
  11243. enumerable: true,
  11244. configurable: true
  11245. });
  11246. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11247. // Empty texture
  11248. get: function () {
  11249. if (!this._emptyTexture) {
  11250. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11251. }
  11252. return this._emptyTexture;
  11253. },
  11254. enumerable: true,
  11255. configurable: true
  11256. });
  11257. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11258. get: function () {
  11259. if (!this._emptyTexture3D) {
  11260. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11261. }
  11262. return this._emptyTexture3D;
  11263. },
  11264. enumerable: true,
  11265. configurable: true
  11266. });
  11267. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11268. get: function () {
  11269. if (!this._emptyCubeTexture) {
  11270. var faceData = new Uint8Array(4);
  11271. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11272. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11273. }
  11274. return this._emptyCubeTexture;
  11275. },
  11276. enumerable: true,
  11277. configurable: true
  11278. });
  11279. Engine.prototype._rebuildInternalTextures = function () {
  11280. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11281. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11282. var internalTexture = currentState_1[_i];
  11283. internalTexture._rebuild();
  11284. }
  11285. };
  11286. Engine.prototype._rebuildEffects = function () {
  11287. for (var key in this._compiledEffects) {
  11288. var effect = this._compiledEffects[key];
  11289. effect._prepareEffect();
  11290. }
  11291. BABYLON.Effect.ResetCache();
  11292. };
  11293. Engine.prototype._rebuildBuffers = function () {
  11294. // Index / Vertex
  11295. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11296. var scene = _a[_i];
  11297. scene.resetCachedMaterial();
  11298. scene._rebuildGeometries();
  11299. scene._rebuildTextures();
  11300. }
  11301. // Uniforms
  11302. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11303. var uniformBuffer = _c[_b];
  11304. uniformBuffer._rebuild();
  11305. }
  11306. };
  11307. Engine.prototype._initGLContext = function () {
  11308. // Caps
  11309. this._caps = new EngineCapabilities();
  11310. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11311. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11312. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11313. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11314. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11315. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11316. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11317. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11318. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11319. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11320. // Infos
  11321. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11322. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11323. if (rendererInfo != null) {
  11324. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11325. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11326. }
  11327. if (!this._glVendor) {
  11328. this._glVendor = "Unknown vendor";
  11329. }
  11330. if (!this._glRenderer) {
  11331. this._glRenderer = "Unknown renderer";
  11332. }
  11333. // Constants
  11334. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11335. if (this._gl.RGBA16F !== 0x881A) {
  11336. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11337. }
  11338. if (this._gl.RGBA32F !== 0x8814) {
  11339. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11340. }
  11341. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11342. this._gl.DEPTH24_STENCIL8 = 35056;
  11343. }
  11344. // Extensions
  11345. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11346. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11347. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11348. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11349. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11350. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11351. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11352. 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');
  11353. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11354. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11355. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11356. this._caps.highPrecisionShaderSupported = true;
  11357. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11358. if (this._caps.timerQuery) {
  11359. if (this._webGLVersion === 1) {
  11360. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11361. }
  11362. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11363. }
  11364. // Checks if some of the format renders first to allow the use of webgl inspector.
  11365. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11366. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11367. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11368. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11369. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11370. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11371. if (this._webGLVersion > 1) {
  11372. this._gl.HALF_FLOAT_OES = 0x140B;
  11373. }
  11374. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11375. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11376. // Draw buffers
  11377. if (this._webGLVersion > 1) {
  11378. this._caps.drawBuffersExtension = true;
  11379. }
  11380. else {
  11381. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11382. if (drawBuffersExtension !== null) {
  11383. this._caps.drawBuffersExtension = true;
  11384. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11385. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11386. for (var i = 0; i < 16; i++) {
  11387. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11388. }
  11389. }
  11390. else {
  11391. this._caps.drawBuffersExtension = false;
  11392. }
  11393. }
  11394. // Depth Texture
  11395. if (this._webGLVersion > 1) {
  11396. this._caps.depthTextureExtension = true;
  11397. }
  11398. else {
  11399. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11400. if (depthTextureExtension != null) {
  11401. this._caps.depthTextureExtension = true;
  11402. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11403. }
  11404. }
  11405. // Vertex array object
  11406. if (this._webGLVersion > 1) {
  11407. this._caps.vertexArrayObject = true;
  11408. }
  11409. else {
  11410. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11411. if (vertexArrayObjectExtension != null) {
  11412. this._caps.vertexArrayObject = true;
  11413. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11414. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11415. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11416. }
  11417. else {
  11418. this._caps.vertexArrayObject = false;
  11419. }
  11420. }
  11421. // Instances count
  11422. if (this._webGLVersion > 1) {
  11423. this._caps.instancedArrays = true;
  11424. }
  11425. else {
  11426. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11427. if (instanceExtension != null) {
  11428. this._caps.instancedArrays = true;
  11429. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11430. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11431. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11432. }
  11433. else {
  11434. this._caps.instancedArrays = false;
  11435. }
  11436. }
  11437. // Intelligently add supported compressed formats in order to check for.
  11438. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11439. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11440. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11441. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11442. if (this._caps.astc)
  11443. this.texturesSupported.push('-astc.ktx');
  11444. if (this._caps.s3tc)
  11445. this.texturesSupported.push('-dxt.ktx');
  11446. if (this._caps.pvrtc)
  11447. this.texturesSupported.push('-pvrtc.ktx');
  11448. if (this._caps.etc2)
  11449. this.texturesSupported.push('-etc2.ktx');
  11450. if (this._caps.etc1)
  11451. this.texturesSupported.push('-etc1.ktx');
  11452. if (this._gl.getShaderPrecisionFormat) {
  11453. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11454. if (highp) {
  11455. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11456. }
  11457. }
  11458. // Depth buffer
  11459. this.setDepthBuffer(true);
  11460. this.setDepthFunctionToLessOrEqual();
  11461. this.setDepthWrite(true);
  11462. // Texture maps
  11463. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11464. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11465. this._nextFreeTextureSlots.push(slot);
  11466. }
  11467. };
  11468. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11469. get: function () {
  11470. return this._webGLVersion;
  11471. },
  11472. enumerable: true,
  11473. configurable: true
  11474. });
  11475. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11476. /**
  11477. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11478. */
  11479. get: function () {
  11480. return this._isStencilEnable;
  11481. },
  11482. enumerable: true,
  11483. configurable: true
  11484. });
  11485. Engine.prototype._prepareWorkingCanvas = function () {
  11486. if (this._workingCanvas) {
  11487. return;
  11488. }
  11489. this._workingCanvas = document.createElement("canvas");
  11490. var context = this._workingCanvas.getContext("2d");
  11491. if (context) {
  11492. this._workingContext = context;
  11493. }
  11494. };
  11495. Engine.prototype.resetTextureCache = function () {
  11496. for (var key in this._boundTexturesCache) {
  11497. var boundTexture = this._boundTexturesCache[key];
  11498. if (boundTexture) {
  11499. this._removeDesignatedSlot(boundTexture);
  11500. }
  11501. this._boundTexturesCache[key] = null;
  11502. }
  11503. if (!this.disableTextureBindingOptimization) {
  11504. this._nextFreeTextureSlots = [];
  11505. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11506. this._nextFreeTextureSlots.push(slot);
  11507. }
  11508. }
  11509. this._currentTextureChannel = -1;
  11510. };
  11511. Engine.prototype.isDeterministicLockStep = function () {
  11512. return this._deterministicLockstep;
  11513. };
  11514. Engine.prototype.getLockstepMaxSteps = function () {
  11515. return this._lockstepMaxSteps;
  11516. };
  11517. Engine.prototype.getGlInfo = function () {
  11518. return {
  11519. vendor: this._glVendor,
  11520. renderer: this._glRenderer,
  11521. version: this._glVersion
  11522. };
  11523. };
  11524. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11525. if (useScreen === void 0) { useScreen = false; }
  11526. var viewport = camera.viewport;
  11527. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11528. };
  11529. Engine.prototype.getRenderWidth = function (useScreen) {
  11530. if (useScreen === void 0) { useScreen = false; }
  11531. if (!useScreen && this._currentRenderTarget) {
  11532. return this._currentRenderTarget.width;
  11533. }
  11534. return this._gl.drawingBufferWidth;
  11535. };
  11536. Engine.prototype.getRenderHeight = function (useScreen) {
  11537. if (useScreen === void 0) { useScreen = false; }
  11538. if (!useScreen && this._currentRenderTarget) {
  11539. return this._currentRenderTarget.height;
  11540. }
  11541. return this._gl.drawingBufferHeight;
  11542. };
  11543. Engine.prototype.getRenderingCanvas = function () {
  11544. return this._renderingCanvas;
  11545. };
  11546. Engine.prototype.getRenderingCanvasClientRect = function () {
  11547. if (!this._renderingCanvas) {
  11548. return null;
  11549. }
  11550. return this._renderingCanvas.getBoundingClientRect();
  11551. };
  11552. Engine.prototype.setHardwareScalingLevel = function (level) {
  11553. this._hardwareScalingLevel = level;
  11554. this.resize();
  11555. };
  11556. Engine.prototype.getHardwareScalingLevel = function () {
  11557. return this._hardwareScalingLevel;
  11558. };
  11559. Engine.prototype.getLoadedTexturesCache = function () {
  11560. return this._internalTexturesCache;
  11561. };
  11562. Engine.prototype.getCaps = function () {
  11563. return this._caps;
  11564. };
  11565. Object.defineProperty(Engine.prototype, "drawCalls", {
  11566. /** The number of draw calls submitted last frame */
  11567. get: function () {
  11568. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11569. return 0;
  11570. },
  11571. enumerable: true,
  11572. configurable: true
  11573. });
  11574. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11575. get: function () {
  11576. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11577. return null;
  11578. },
  11579. enumerable: true,
  11580. configurable: true
  11581. });
  11582. Engine.prototype.getDepthFunction = function () {
  11583. return this._depthCullingState.depthFunc;
  11584. };
  11585. Engine.prototype.setDepthFunction = function (depthFunc) {
  11586. this._depthCullingState.depthFunc = depthFunc;
  11587. };
  11588. Engine.prototype.setDepthFunctionToGreater = function () {
  11589. this._depthCullingState.depthFunc = this._gl.GREATER;
  11590. };
  11591. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11592. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11593. };
  11594. Engine.prototype.setDepthFunctionToLess = function () {
  11595. this._depthCullingState.depthFunc = this._gl.LESS;
  11596. };
  11597. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11598. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11599. };
  11600. Engine.prototype.getStencilBuffer = function () {
  11601. return this._stencilState.stencilTest;
  11602. };
  11603. Engine.prototype.setStencilBuffer = function (enable) {
  11604. this._stencilState.stencilTest = enable;
  11605. };
  11606. Engine.prototype.getStencilMask = function () {
  11607. return this._stencilState.stencilMask;
  11608. };
  11609. Engine.prototype.setStencilMask = function (mask) {
  11610. this._stencilState.stencilMask = mask;
  11611. };
  11612. Engine.prototype.getStencilFunction = function () {
  11613. return this._stencilState.stencilFunc;
  11614. };
  11615. Engine.prototype.getStencilFunctionReference = function () {
  11616. return this._stencilState.stencilFuncRef;
  11617. };
  11618. Engine.prototype.getStencilFunctionMask = function () {
  11619. return this._stencilState.stencilFuncMask;
  11620. };
  11621. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11622. this._stencilState.stencilFunc = stencilFunc;
  11623. };
  11624. Engine.prototype.setStencilFunctionReference = function (reference) {
  11625. this._stencilState.stencilFuncRef = reference;
  11626. };
  11627. Engine.prototype.setStencilFunctionMask = function (mask) {
  11628. this._stencilState.stencilFuncMask = mask;
  11629. };
  11630. Engine.prototype.getStencilOperationFail = function () {
  11631. return this._stencilState.stencilOpStencilFail;
  11632. };
  11633. Engine.prototype.getStencilOperationDepthFail = function () {
  11634. return this._stencilState.stencilOpDepthFail;
  11635. };
  11636. Engine.prototype.getStencilOperationPass = function () {
  11637. return this._stencilState.stencilOpStencilDepthPass;
  11638. };
  11639. Engine.prototype.setStencilOperationFail = function (operation) {
  11640. this._stencilState.stencilOpStencilFail = operation;
  11641. };
  11642. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11643. this._stencilState.stencilOpDepthFail = operation;
  11644. };
  11645. Engine.prototype.setStencilOperationPass = function (operation) {
  11646. this._stencilState.stencilOpStencilDepthPass = operation;
  11647. };
  11648. Engine.prototype.setDitheringState = function (value) {
  11649. if (value) {
  11650. this._gl.enable(this._gl.DITHER);
  11651. }
  11652. else {
  11653. this._gl.disable(this._gl.DITHER);
  11654. }
  11655. };
  11656. Engine.prototype.setRasterizerState = function (value) {
  11657. if (value) {
  11658. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11659. }
  11660. else {
  11661. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11662. }
  11663. };
  11664. /**
  11665. * stop executing a render loop function and remove it from the execution array
  11666. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11667. */
  11668. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11669. if (!renderFunction) {
  11670. this._activeRenderLoops = [];
  11671. return;
  11672. }
  11673. var index = this._activeRenderLoops.indexOf(renderFunction);
  11674. if (index >= 0) {
  11675. this._activeRenderLoops.splice(index, 1);
  11676. }
  11677. };
  11678. Engine.prototype._renderLoop = function () {
  11679. if (!this._contextWasLost) {
  11680. var shouldRender = true;
  11681. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11682. shouldRender = false;
  11683. }
  11684. if (shouldRender) {
  11685. // Start new frame
  11686. this.beginFrame();
  11687. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11688. var renderFunction = this._activeRenderLoops[index];
  11689. renderFunction();
  11690. }
  11691. // Present
  11692. this.endFrame();
  11693. }
  11694. }
  11695. if (this._activeRenderLoops.length > 0) {
  11696. // Register new frame
  11697. var requester = null;
  11698. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11699. requester = this._vrDisplay;
  11700. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11701. }
  11702. else {
  11703. this._renderingQueueLaunched = false;
  11704. }
  11705. };
  11706. /**
  11707. * Register and execute a render loop. The engine can have more than one render function.
  11708. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11709. * @example
  11710. * engine.runRenderLoop(function () {
  11711. * scene.render()
  11712. * })
  11713. */
  11714. Engine.prototype.runRenderLoop = function (renderFunction) {
  11715. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11716. return;
  11717. }
  11718. this._activeRenderLoops.push(renderFunction);
  11719. if (!this._renderingQueueLaunched) {
  11720. this._renderingQueueLaunched = true;
  11721. this._bindedRenderFunction = this._renderLoop.bind(this);
  11722. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11723. }
  11724. };
  11725. /**
  11726. * Toggle full screen mode.
  11727. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11728. * @param {any} options - an options object to be sent to the requestFullscreen function
  11729. */
  11730. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11731. if (this.isFullscreen) {
  11732. BABYLON.Tools.ExitFullscreen();
  11733. }
  11734. else {
  11735. this._pointerLockRequested = requestPointerLock;
  11736. if (this._renderingCanvas) {
  11737. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11738. }
  11739. }
  11740. };
  11741. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11742. if (stencil === void 0) { stencil = false; }
  11743. this.applyStates();
  11744. var mode = 0;
  11745. if (backBuffer && color) {
  11746. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11747. mode |= this._gl.COLOR_BUFFER_BIT;
  11748. }
  11749. if (depth) {
  11750. this._gl.clearDepth(1.0);
  11751. mode |= this._gl.DEPTH_BUFFER_BIT;
  11752. }
  11753. if (stencil) {
  11754. this._gl.clearStencil(0);
  11755. mode |= this._gl.STENCIL_BUFFER_BIT;
  11756. }
  11757. this._gl.clear(mode);
  11758. };
  11759. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11760. var gl = this._gl;
  11761. // Save state
  11762. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11763. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11764. // Change state
  11765. gl.enable(gl.SCISSOR_TEST);
  11766. gl.scissor(x, y, width, height);
  11767. // Clear
  11768. this.clear(clearColor, true, true, true);
  11769. // Restore state
  11770. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11771. if (curScissor === true) {
  11772. gl.enable(gl.SCISSOR_TEST);
  11773. }
  11774. else {
  11775. gl.disable(gl.SCISSOR_TEST);
  11776. }
  11777. };
  11778. /**
  11779. * Set the WebGL's viewport
  11780. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11781. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11782. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11783. */
  11784. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11785. var width = requiredWidth || this.getRenderWidth();
  11786. var height = requiredHeight || this.getRenderHeight();
  11787. var x = viewport.x || 0;
  11788. var y = viewport.y || 0;
  11789. this._cachedViewport = viewport;
  11790. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11791. };
  11792. /**
  11793. * Directly set the WebGL Viewport
  11794. * The x, y, width & height are directly passed to the WebGL call
  11795. * @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.
  11796. */
  11797. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11798. var currentViewport = this._cachedViewport;
  11799. this._cachedViewport = null;
  11800. this._gl.viewport(x, y, width, height);
  11801. return currentViewport;
  11802. };
  11803. Engine.prototype.beginFrame = function () {
  11804. this.onBeginFrameObservable.notifyObservers(this);
  11805. this._measureFps();
  11806. };
  11807. Engine.prototype.endFrame = function () {
  11808. //force a flush in case we are using a bad OS.
  11809. if (this._badOS) {
  11810. this.flushFramebuffer();
  11811. }
  11812. //submit frame to the vr device, if enabled
  11813. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11814. // TODO: We should only submit the frame if we read frameData successfully.
  11815. this._vrDisplay.submitFrame();
  11816. }
  11817. this.onEndFrameObservable.notifyObservers(this);
  11818. };
  11819. /**
  11820. * resize the view according to the canvas' size.
  11821. * @example
  11822. * window.addEventListener("resize", function () {
  11823. * engine.resize();
  11824. * });
  11825. */
  11826. Engine.prototype.resize = function () {
  11827. // We're not resizing the size of the canvas while in VR mode & presenting
  11828. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11829. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11830. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11831. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11832. }
  11833. };
  11834. /**
  11835. * force a specific size of the canvas
  11836. * @param {number} width - the new canvas' width
  11837. * @param {number} height - the new canvas' height
  11838. */
  11839. Engine.prototype.setSize = function (width, height) {
  11840. if (!this._renderingCanvas) {
  11841. return;
  11842. }
  11843. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11844. return;
  11845. }
  11846. this._renderingCanvas.width = width;
  11847. this._renderingCanvas.height = height;
  11848. for (var index = 0; index < this.scenes.length; index++) {
  11849. var scene = this.scenes[index];
  11850. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11851. var cam = scene.cameras[camIndex];
  11852. cam._currentRenderId = 0;
  11853. }
  11854. }
  11855. if (this.onResizeObservable.hasObservers) {
  11856. this.onResizeObservable.notifyObservers(this);
  11857. }
  11858. };
  11859. // WebVR functions
  11860. Engine.prototype.isVRDevicePresent = function () {
  11861. return !!this._vrDisplay;
  11862. };
  11863. Engine.prototype.getVRDevice = function () {
  11864. return this._vrDisplay;
  11865. };
  11866. /**
  11867. * Initializes a webVR display and starts listening to display change events.
  11868. * The onVRDisplayChangedObservable will be notified upon these changes.
  11869. * @returns The onVRDisplayChangedObservable.
  11870. */
  11871. Engine.prototype.initWebVR = function () {
  11872. this.initWebVRAsync();
  11873. return this.onVRDisplayChangedObservable;
  11874. };
  11875. /**
  11876. * Initializes a webVR display and starts listening to display change events.
  11877. * The onVRDisplayChangedObservable will be notified upon these changes.
  11878. * @returns A promise containing a VRDisplay and if vr is supported.
  11879. */
  11880. Engine.prototype.initWebVRAsync = function () {
  11881. var _this = this;
  11882. var notifyObservers = function () {
  11883. var eventArgs = {
  11884. vrDisplay: _this._vrDisplay,
  11885. vrSupported: _this._vrSupported
  11886. };
  11887. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11888. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11889. };
  11890. if (!this._onVrDisplayConnect) {
  11891. this._onVrDisplayConnect = function (event) {
  11892. _this._vrDisplay = event.display;
  11893. notifyObservers();
  11894. };
  11895. this._onVrDisplayDisconnect = function () {
  11896. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11897. _this._vrDisplay = undefined;
  11898. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11899. notifyObservers();
  11900. };
  11901. this._onVrDisplayPresentChange = function () {
  11902. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11903. };
  11904. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11905. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11906. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11907. }
  11908. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11909. this._webVRInitPromise.then(notifyObservers);
  11910. return this._webVRInitPromise;
  11911. };
  11912. Engine.prototype.enableVR = function () {
  11913. var _this = this;
  11914. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11915. var onResolved = function () {
  11916. _this.onVRRequestPresentComplete.notifyObservers(true);
  11917. _this._onVRFullScreenTriggered();
  11918. };
  11919. var onRejected = function () {
  11920. _this.onVRRequestPresentComplete.notifyObservers(false);
  11921. };
  11922. this.onVRRequestPresentStart.notifyObservers(this);
  11923. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11924. }
  11925. };
  11926. Engine.prototype.disableVR = function () {
  11927. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11928. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11929. }
  11930. };
  11931. Engine.prototype._getVRDisplaysAsync = function () {
  11932. var _this = this;
  11933. return new Promise(function (res, rej) {
  11934. if (navigator.getVRDisplays) {
  11935. navigator.getVRDisplays().then(function (devices) {
  11936. _this._vrSupported = true;
  11937. // note that devices may actually be an empty array. This is fine;
  11938. // we expect this._vrDisplay to be undefined in this case.
  11939. _this._vrDisplay = devices[0];
  11940. res({
  11941. vrDisplay: _this._vrDisplay,
  11942. vrSupported: _this._vrSupported
  11943. });
  11944. });
  11945. }
  11946. else {
  11947. _this._vrDisplay = undefined;
  11948. _this._vrSupported = false;
  11949. res({
  11950. vrDisplay: _this._vrDisplay,
  11951. vrSupported: _this._vrSupported
  11952. });
  11953. }
  11954. });
  11955. };
  11956. /**
  11957. * Binds the frame buffer to the specified texture.
  11958. * @param texture The texture to render to or null for the default canvas
  11959. * @param faceIndex The face of the texture to render to in case of cube texture
  11960. * @param requiredWidth The width of the target to render to
  11961. * @param requiredHeight The height of the target to render to
  11962. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11963. * @param depthStencilTexture The depth stencil texture to use to render
  11964. */
  11965. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11966. if (this._currentRenderTarget) {
  11967. this.unBindFramebuffer(this._currentRenderTarget);
  11968. }
  11969. this._currentRenderTarget = texture;
  11970. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11971. var gl = this._gl;
  11972. if (texture.isCube) {
  11973. if (faceIndex === undefined) {
  11974. faceIndex = 0;
  11975. }
  11976. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11977. if (depthStencilTexture) {
  11978. if (depthStencilTexture._generateStencilBuffer) {
  11979. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  11980. }
  11981. else {
  11982. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  11983. }
  11984. }
  11985. }
  11986. if (this._cachedViewport && !forceFullscreenViewport) {
  11987. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11988. }
  11989. else {
  11990. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11991. }
  11992. this.wipeCaches();
  11993. };
  11994. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11995. if (this._currentFramebuffer !== framebuffer) {
  11996. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11997. this._currentFramebuffer = framebuffer;
  11998. }
  11999. };
  12000. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12001. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12002. this._currentRenderTarget = null;
  12003. // If MSAA, we need to bitblt back to main texture
  12004. var gl = this._gl;
  12005. if (texture._MSAAFramebuffer) {
  12006. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12007. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12008. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12009. }
  12010. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12011. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12012. gl.generateMipmap(gl.TEXTURE_2D);
  12013. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12014. }
  12015. if (onBeforeUnbind) {
  12016. if (texture._MSAAFramebuffer) {
  12017. // Bind the correct framebuffer
  12018. this.bindUnboundFramebuffer(texture._framebuffer);
  12019. }
  12020. onBeforeUnbind();
  12021. }
  12022. this.bindUnboundFramebuffer(null);
  12023. };
  12024. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12025. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12026. this._currentRenderTarget = null;
  12027. // If MSAA, we need to bitblt back to main texture
  12028. var gl = this._gl;
  12029. if (textures[0]._MSAAFramebuffer) {
  12030. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12031. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12032. var attachments = textures[0]._attachments;
  12033. if (!attachments) {
  12034. attachments = new Array(textures.length);
  12035. textures[0]._attachments = attachments;
  12036. }
  12037. for (var i = 0; i < textures.length; i++) {
  12038. var texture = textures[i];
  12039. for (var j = 0; j < attachments.length; j++) {
  12040. attachments[j] = gl.NONE;
  12041. }
  12042. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12043. gl.readBuffer(attachments[i]);
  12044. gl.drawBuffers(attachments);
  12045. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12046. }
  12047. for (var i = 0; i < attachments.length; i++) {
  12048. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12049. }
  12050. gl.drawBuffers(attachments);
  12051. }
  12052. for (var i = 0; i < textures.length; i++) {
  12053. var texture = textures[i];
  12054. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12055. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12056. gl.generateMipmap(gl.TEXTURE_2D);
  12057. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12058. }
  12059. }
  12060. if (onBeforeUnbind) {
  12061. if (textures[0]._MSAAFramebuffer) {
  12062. // Bind the correct framebuffer
  12063. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12064. }
  12065. onBeforeUnbind();
  12066. }
  12067. this.bindUnboundFramebuffer(null);
  12068. };
  12069. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12070. if (texture.generateMipMaps) {
  12071. var gl = this._gl;
  12072. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12073. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12074. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12075. }
  12076. };
  12077. Engine.prototype.flushFramebuffer = function () {
  12078. this._gl.flush();
  12079. };
  12080. Engine.prototype.restoreDefaultFramebuffer = function () {
  12081. if (this._currentRenderTarget) {
  12082. this.unBindFramebuffer(this._currentRenderTarget);
  12083. }
  12084. else {
  12085. this.bindUnboundFramebuffer(null);
  12086. }
  12087. if (this._cachedViewport) {
  12088. this.setViewport(this._cachedViewport);
  12089. }
  12090. this.wipeCaches();
  12091. };
  12092. // UBOs
  12093. Engine.prototype.createUniformBuffer = function (elements) {
  12094. var ubo = this._gl.createBuffer();
  12095. if (!ubo) {
  12096. throw new Error("Unable to create uniform buffer");
  12097. }
  12098. this.bindUniformBuffer(ubo);
  12099. if (elements instanceof Float32Array) {
  12100. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12101. }
  12102. else {
  12103. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12104. }
  12105. this.bindUniformBuffer(null);
  12106. ubo.references = 1;
  12107. return ubo;
  12108. };
  12109. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12110. var ubo = this._gl.createBuffer();
  12111. if (!ubo) {
  12112. throw new Error("Unable to create dynamic uniform buffer");
  12113. }
  12114. this.bindUniformBuffer(ubo);
  12115. if (elements instanceof Float32Array) {
  12116. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12117. }
  12118. else {
  12119. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12120. }
  12121. this.bindUniformBuffer(null);
  12122. ubo.references = 1;
  12123. return ubo;
  12124. };
  12125. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12126. this.bindUniformBuffer(uniformBuffer);
  12127. if (offset === undefined) {
  12128. offset = 0;
  12129. }
  12130. if (count === undefined) {
  12131. if (elements instanceof Float32Array) {
  12132. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12133. }
  12134. else {
  12135. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12136. }
  12137. }
  12138. else {
  12139. if (elements instanceof Float32Array) {
  12140. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12141. }
  12142. else {
  12143. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12144. }
  12145. }
  12146. this.bindUniformBuffer(null);
  12147. };
  12148. // VBOs
  12149. Engine.prototype._resetVertexBufferBinding = function () {
  12150. this.bindArrayBuffer(null);
  12151. this._cachedVertexBuffers = null;
  12152. };
  12153. Engine.prototype.createVertexBuffer = function (vertices) {
  12154. var vbo = this._gl.createBuffer();
  12155. if (!vbo) {
  12156. throw new Error("Unable to create vertex buffer");
  12157. }
  12158. this.bindArrayBuffer(vbo);
  12159. if (vertices instanceof Float32Array) {
  12160. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12161. }
  12162. else {
  12163. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12164. }
  12165. this._resetVertexBufferBinding();
  12166. vbo.references = 1;
  12167. return vbo;
  12168. };
  12169. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12170. var vbo = this._gl.createBuffer();
  12171. if (!vbo) {
  12172. throw new Error("Unable to create dynamic vertex buffer");
  12173. }
  12174. this.bindArrayBuffer(vbo);
  12175. if (vertices instanceof Float32Array) {
  12176. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12177. }
  12178. else {
  12179. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12180. }
  12181. this._resetVertexBufferBinding();
  12182. vbo.references = 1;
  12183. return vbo;
  12184. };
  12185. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12186. if (offset === void 0) { offset = 0; }
  12187. // Force cache update
  12188. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12189. this.bindIndexBuffer(indexBuffer);
  12190. var arrayBuffer;
  12191. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12192. arrayBuffer = indices;
  12193. }
  12194. else {
  12195. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12196. }
  12197. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12198. this._resetIndexBufferBinding();
  12199. };
  12200. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12201. this.bindArrayBuffer(vertexBuffer);
  12202. if (offset === undefined) {
  12203. offset = 0;
  12204. }
  12205. if (count === undefined) {
  12206. if (vertices instanceof Float32Array) {
  12207. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12208. }
  12209. else {
  12210. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12211. }
  12212. }
  12213. else {
  12214. if (vertices instanceof Float32Array) {
  12215. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12216. }
  12217. else {
  12218. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12219. }
  12220. }
  12221. this._resetVertexBufferBinding();
  12222. };
  12223. Engine.prototype._resetIndexBufferBinding = function () {
  12224. this.bindIndexBuffer(null);
  12225. this._cachedIndexBuffer = null;
  12226. };
  12227. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12228. var vbo = this._gl.createBuffer();
  12229. if (!vbo) {
  12230. throw new Error("Unable to create index buffer");
  12231. }
  12232. this.bindIndexBuffer(vbo);
  12233. // Check for 32 bits indices
  12234. var arrayBuffer;
  12235. var need32Bits = false;
  12236. if (indices instanceof Uint16Array) {
  12237. arrayBuffer = indices;
  12238. }
  12239. else {
  12240. //check 32 bit support
  12241. if (this._caps.uintIndices) {
  12242. if (indices instanceof Uint32Array) {
  12243. arrayBuffer = indices;
  12244. need32Bits = true;
  12245. }
  12246. else {
  12247. //number[] or Int32Array, check if 32 bit is necessary
  12248. for (var index = 0; index < indices.length; index++) {
  12249. if (indices[index] > 65535) {
  12250. need32Bits = true;
  12251. break;
  12252. }
  12253. }
  12254. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12255. }
  12256. }
  12257. else {
  12258. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12259. arrayBuffer = new Uint16Array(indices);
  12260. }
  12261. }
  12262. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12263. this._resetIndexBufferBinding();
  12264. vbo.references = 1;
  12265. vbo.is32Bits = need32Bits;
  12266. return vbo;
  12267. };
  12268. Engine.prototype.bindArrayBuffer = function (buffer) {
  12269. if (!this._vaoRecordInProgress) {
  12270. this._unbindVertexArrayObject();
  12271. }
  12272. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12273. };
  12274. Engine.prototype.bindUniformBuffer = function (buffer) {
  12275. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12276. };
  12277. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12278. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12279. };
  12280. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12281. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12282. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12283. };
  12284. ;
  12285. Engine.prototype.bindIndexBuffer = function (buffer) {
  12286. if (!this._vaoRecordInProgress) {
  12287. this._unbindVertexArrayObject();
  12288. }
  12289. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12290. };
  12291. Engine.prototype.bindBuffer = function (buffer, target) {
  12292. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12293. this._gl.bindBuffer(target, buffer);
  12294. this._currentBoundBuffer[target] = buffer;
  12295. }
  12296. };
  12297. Engine.prototype.updateArrayBuffer = function (data) {
  12298. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12299. };
  12300. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12301. var pointer = this._currentBufferPointers[indx];
  12302. var changed = false;
  12303. if (!pointer.active) {
  12304. changed = true;
  12305. pointer.active = true;
  12306. pointer.index = indx;
  12307. pointer.size = size;
  12308. pointer.type = type;
  12309. pointer.normalized = normalized;
  12310. pointer.stride = stride;
  12311. pointer.offset = offset;
  12312. pointer.buffer = buffer;
  12313. }
  12314. else {
  12315. if (pointer.buffer !== buffer) {
  12316. pointer.buffer = buffer;
  12317. changed = true;
  12318. }
  12319. if (pointer.size !== size) {
  12320. pointer.size = size;
  12321. changed = true;
  12322. }
  12323. if (pointer.type !== type) {
  12324. pointer.type = type;
  12325. changed = true;
  12326. }
  12327. if (pointer.normalized !== normalized) {
  12328. pointer.normalized = normalized;
  12329. changed = true;
  12330. }
  12331. if (pointer.stride !== stride) {
  12332. pointer.stride = stride;
  12333. changed = true;
  12334. }
  12335. if (pointer.offset !== offset) {
  12336. pointer.offset = offset;
  12337. changed = true;
  12338. }
  12339. }
  12340. if (changed || this._vaoRecordInProgress) {
  12341. this.bindArrayBuffer(buffer);
  12342. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12343. }
  12344. };
  12345. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12346. if (indexBuffer == null) {
  12347. return;
  12348. }
  12349. if (this._cachedIndexBuffer !== indexBuffer) {
  12350. this._cachedIndexBuffer = indexBuffer;
  12351. this.bindIndexBuffer(indexBuffer);
  12352. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12353. }
  12354. };
  12355. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12356. var attributes = effect.getAttributesNames();
  12357. if (!this._vaoRecordInProgress) {
  12358. this._unbindVertexArrayObject();
  12359. }
  12360. this.unbindAllAttributes();
  12361. for (var index = 0; index < attributes.length; index++) {
  12362. var order = effect.getAttributeLocation(index);
  12363. if (order >= 0) {
  12364. var vertexBuffer = vertexBuffers[attributes[index]];
  12365. if (!vertexBuffer) {
  12366. continue;
  12367. }
  12368. this._gl.enableVertexAttribArray(order);
  12369. if (!this._vaoRecordInProgress) {
  12370. this._vertexAttribArraysEnabled[order] = true;
  12371. }
  12372. var buffer = vertexBuffer.getBuffer();
  12373. if (buffer) {
  12374. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12375. if (vertexBuffer.getIsInstanced()) {
  12376. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12377. if (!this._vaoRecordInProgress) {
  12378. this._currentInstanceLocations.push(order);
  12379. this._currentInstanceBuffers.push(buffer);
  12380. }
  12381. }
  12382. }
  12383. }
  12384. }
  12385. };
  12386. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12387. var vao = this._gl.createVertexArray();
  12388. this._vaoRecordInProgress = true;
  12389. this._gl.bindVertexArray(vao);
  12390. this._mustWipeVertexAttributes = true;
  12391. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12392. this.bindIndexBuffer(indexBuffer);
  12393. this._vaoRecordInProgress = false;
  12394. this._gl.bindVertexArray(null);
  12395. return vao;
  12396. };
  12397. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12398. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12399. this._cachedVertexArrayObject = vertexArrayObject;
  12400. this._gl.bindVertexArray(vertexArrayObject);
  12401. this._cachedVertexBuffers = null;
  12402. this._cachedIndexBuffer = null;
  12403. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12404. this._mustWipeVertexAttributes = true;
  12405. }
  12406. };
  12407. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12408. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12409. this._cachedVertexBuffers = vertexBuffer;
  12410. this._cachedEffectForVertexBuffers = effect;
  12411. var attributesCount = effect.getAttributesCount();
  12412. this._unbindVertexArrayObject();
  12413. this.unbindAllAttributes();
  12414. var offset = 0;
  12415. for (var index = 0; index < attributesCount; index++) {
  12416. if (index < vertexDeclaration.length) {
  12417. var order = effect.getAttributeLocation(index);
  12418. if (order >= 0) {
  12419. this._gl.enableVertexAttribArray(order);
  12420. this._vertexAttribArraysEnabled[order] = true;
  12421. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12422. }
  12423. offset += vertexDeclaration[index] * 4;
  12424. }
  12425. }
  12426. }
  12427. this._bindIndexBufferWithCache(indexBuffer);
  12428. };
  12429. Engine.prototype._unbindVertexArrayObject = function () {
  12430. if (!this._cachedVertexArrayObject) {
  12431. return;
  12432. }
  12433. this._cachedVertexArrayObject = null;
  12434. this._gl.bindVertexArray(null);
  12435. };
  12436. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12437. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12438. this._cachedVertexBuffers = vertexBuffers;
  12439. this._cachedEffectForVertexBuffers = effect;
  12440. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12441. }
  12442. this._bindIndexBufferWithCache(indexBuffer);
  12443. };
  12444. Engine.prototype.unbindInstanceAttributes = function () {
  12445. var boundBuffer;
  12446. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12447. var instancesBuffer = this._currentInstanceBuffers[i];
  12448. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12449. boundBuffer = instancesBuffer;
  12450. this.bindArrayBuffer(instancesBuffer);
  12451. }
  12452. var offsetLocation = this._currentInstanceLocations[i];
  12453. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12454. }
  12455. this._currentInstanceBuffers.length = 0;
  12456. this._currentInstanceLocations.length = 0;
  12457. };
  12458. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12459. this._gl.deleteVertexArray(vao);
  12460. };
  12461. Engine.prototype._releaseBuffer = function (buffer) {
  12462. buffer.references--;
  12463. if (buffer.references === 0) {
  12464. this._gl.deleteBuffer(buffer);
  12465. return true;
  12466. }
  12467. return false;
  12468. };
  12469. Engine.prototype.createInstancesBuffer = function (capacity) {
  12470. var buffer = this._gl.createBuffer();
  12471. if (!buffer) {
  12472. throw new Error("Unable to create instance buffer");
  12473. }
  12474. buffer.capacity = capacity;
  12475. this.bindArrayBuffer(buffer);
  12476. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12477. return buffer;
  12478. };
  12479. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12480. this._gl.deleteBuffer(buffer);
  12481. };
  12482. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12483. this.bindArrayBuffer(instancesBuffer);
  12484. if (data) {
  12485. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12486. }
  12487. if (offsetLocations[0].index !== undefined) {
  12488. var stride = 0;
  12489. for (var i = 0; i < offsetLocations.length; i++) {
  12490. var ai = offsetLocations[i];
  12491. stride += ai.attributeSize * 4;
  12492. }
  12493. for (var i = 0; i < offsetLocations.length; i++) {
  12494. var ai = offsetLocations[i];
  12495. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12496. this._gl.enableVertexAttribArray(ai.index);
  12497. this._vertexAttribArraysEnabled[ai.index] = true;
  12498. }
  12499. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12500. this._gl.vertexAttribDivisor(ai.index, 1);
  12501. this._currentInstanceLocations.push(ai.index);
  12502. this._currentInstanceBuffers.push(instancesBuffer);
  12503. }
  12504. }
  12505. else {
  12506. for (var index = 0; index < 4; index++) {
  12507. var offsetLocation = offsetLocations[index];
  12508. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12509. this._gl.enableVertexAttribArray(offsetLocation);
  12510. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12511. }
  12512. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12513. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12514. this._currentInstanceLocations.push(offsetLocation);
  12515. this._currentInstanceBuffers.push(instancesBuffer);
  12516. }
  12517. }
  12518. };
  12519. Engine.prototype.applyStates = function () {
  12520. this._depthCullingState.apply(this._gl);
  12521. this._stencilState.apply(this._gl);
  12522. this._alphaState.apply(this._gl);
  12523. };
  12524. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12525. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12526. };
  12527. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12528. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12529. };
  12530. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12531. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12532. };
  12533. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12534. // Apply states
  12535. this.applyStates();
  12536. this._drawCalls.addCount(1, false);
  12537. // Render
  12538. var drawMode = this.DrawMode(fillMode);
  12539. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12540. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12541. if (instancesCount) {
  12542. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12543. }
  12544. else {
  12545. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12546. }
  12547. };
  12548. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12549. // Apply states
  12550. this.applyStates();
  12551. this._drawCalls.addCount(1, false);
  12552. var drawMode = this.DrawMode(fillMode);
  12553. if (instancesCount) {
  12554. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12555. }
  12556. else {
  12557. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12558. }
  12559. };
  12560. Engine.prototype.DrawMode = function (fillMode) {
  12561. switch (fillMode) {
  12562. // Triangle views
  12563. case BABYLON.Material.TriangleFillMode:
  12564. return this._gl.TRIANGLES;
  12565. case BABYLON.Material.PointFillMode:
  12566. return this._gl.POINTS;
  12567. case BABYLON.Material.WireFrameFillMode:
  12568. return this._gl.LINES;
  12569. // Draw modes
  12570. case BABYLON.Material.PointListDrawMode:
  12571. return this._gl.POINTS;
  12572. case BABYLON.Material.LineListDrawMode:
  12573. return this._gl.LINES;
  12574. case BABYLON.Material.LineLoopDrawMode:
  12575. return this._gl.LINE_LOOP;
  12576. case BABYLON.Material.LineStripDrawMode:
  12577. return this._gl.LINE_STRIP;
  12578. case BABYLON.Material.TriangleStripDrawMode:
  12579. return this._gl.TRIANGLE_STRIP;
  12580. case BABYLON.Material.TriangleFanDrawMode:
  12581. return this._gl.TRIANGLE_FAN;
  12582. default:
  12583. return this._gl.TRIANGLES;
  12584. }
  12585. };
  12586. // Shaders
  12587. Engine.prototype._releaseEffect = function (effect) {
  12588. if (this._compiledEffects[effect._key]) {
  12589. delete this._compiledEffects[effect._key];
  12590. this._deleteProgram(effect.getProgram());
  12591. }
  12592. };
  12593. Engine.prototype._deleteProgram = function (program) {
  12594. if (program) {
  12595. program.__SPECTOR_rebuildProgram = null;
  12596. if (program.transformFeedback) {
  12597. this.deleteTransformFeedback(program.transformFeedback);
  12598. program.transformFeedback = null;
  12599. }
  12600. this._gl.deleteProgram(program);
  12601. }
  12602. };
  12603. /**
  12604. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12605. * @param samplers An array of string used to represent textures
  12606. */
  12607. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12608. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12609. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12610. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12611. if (this._compiledEffects[name]) {
  12612. var compiledEffect = this._compiledEffects[name];
  12613. if (onCompiled && compiledEffect.isReady()) {
  12614. onCompiled(compiledEffect);
  12615. }
  12616. return compiledEffect;
  12617. }
  12618. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12619. effect._key = name;
  12620. this._compiledEffects[name] = effect;
  12621. return effect;
  12622. };
  12623. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12624. if (uniformsNames === void 0) { uniformsNames = []; }
  12625. if (samplers === void 0) { samplers = []; }
  12626. if (defines === void 0) { defines = ""; }
  12627. return this.createEffect({
  12628. vertex: "particles",
  12629. fragmentElement: fragmentName
  12630. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12631. };
  12632. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12633. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12634. context = context || this._gl;
  12635. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12636. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12637. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12638. };
  12639. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12640. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12641. context = context || this._gl;
  12642. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12643. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  12644. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12645. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12646. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12647. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12648. return program;
  12649. };
  12650. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12651. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12652. var shaderProgram = context.createProgram();
  12653. if (!shaderProgram) {
  12654. throw new Error("Unable to create program");
  12655. }
  12656. context.attachShader(shaderProgram, vertexShader);
  12657. context.attachShader(shaderProgram, fragmentShader);
  12658. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12659. var transformFeedback = this.createTransformFeedback();
  12660. this.bindTransformFeedback(transformFeedback);
  12661. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12662. shaderProgram.transformFeedback = transformFeedback;
  12663. }
  12664. context.linkProgram(shaderProgram);
  12665. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12666. this.bindTransformFeedback(null);
  12667. }
  12668. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12669. if (!linked) {
  12670. context.validateProgram(shaderProgram);
  12671. var error = context.getProgramInfoLog(shaderProgram);
  12672. if (error) {
  12673. throw new Error(error);
  12674. }
  12675. }
  12676. context.deleteShader(vertexShader);
  12677. context.deleteShader(fragmentShader);
  12678. return shaderProgram;
  12679. };
  12680. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12681. var results = new Array();
  12682. for (var index = 0; index < uniformsNames.length; index++) {
  12683. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12684. }
  12685. return results;
  12686. };
  12687. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12688. var results = [];
  12689. for (var index = 0; index < attributesNames.length; index++) {
  12690. try {
  12691. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12692. }
  12693. catch (e) {
  12694. results.push(-1);
  12695. }
  12696. }
  12697. return results;
  12698. };
  12699. Engine.prototype.enableEffect = function (effect) {
  12700. if (!effect) {
  12701. return;
  12702. }
  12703. // Use program
  12704. this.bindSamplers(effect);
  12705. this._currentEffect = effect;
  12706. if (effect.onBind) {
  12707. effect.onBind(effect);
  12708. }
  12709. effect.onBindObservable.notifyObservers(effect);
  12710. };
  12711. Engine.prototype.setIntArray = function (uniform, array) {
  12712. if (!uniform)
  12713. return;
  12714. this._gl.uniform1iv(uniform, array);
  12715. };
  12716. Engine.prototype.setIntArray2 = function (uniform, array) {
  12717. if (!uniform || array.length % 2 !== 0)
  12718. return;
  12719. this._gl.uniform2iv(uniform, array);
  12720. };
  12721. Engine.prototype.setIntArray3 = function (uniform, array) {
  12722. if (!uniform || array.length % 3 !== 0)
  12723. return;
  12724. this._gl.uniform3iv(uniform, array);
  12725. };
  12726. Engine.prototype.setIntArray4 = function (uniform, array) {
  12727. if (!uniform || array.length % 4 !== 0)
  12728. return;
  12729. this._gl.uniform4iv(uniform, array);
  12730. };
  12731. Engine.prototype.setFloatArray = function (uniform, array) {
  12732. if (!uniform)
  12733. return;
  12734. this._gl.uniform1fv(uniform, array);
  12735. };
  12736. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12737. if (!uniform || array.length % 2 !== 0)
  12738. return;
  12739. this._gl.uniform2fv(uniform, array);
  12740. };
  12741. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12742. if (!uniform || array.length % 3 !== 0)
  12743. return;
  12744. this._gl.uniform3fv(uniform, array);
  12745. };
  12746. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12747. if (!uniform || array.length % 4 !== 0)
  12748. return;
  12749. this._gl.uniform4fv(uniform, array);
  12750. };
  12751. Engine.prototype.setArray = function (uniform, array) {
  12752. if (!uniform)
  12753. return;
  12754. this._gl.uniform1fv(uniform, array);
  12755. };
  12756. Engine.prototype.setArray2 = function (uniform, array) {
  12757. if (!uniform || array.length % 2 !== 0)
  12758. return;
  12759. this._gl.uniform2fv(uniform, array);
  12760. };
  12761. Engine.prototype.setArray3 = function (uniform, array) {
  12762. if (!uniform || array.length % 3 !== 0)
  12763. return;
  12764. this._gl.uniform3fv(uniform, array);
  12765. };
  12766. Engine.prototype.setArray4 = function (uniform, array) {
  12767. if (!uniform || array.length % 4 !== 0)
  12768. return;
  12769. this._gl.uniform4fv(uniform, array);
  12770. };
  12771. Engine.prototype.setMatrices = function (uniform, matrices) {
  12772. if (!uniform)
  12773. return;
  12774. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12775. };
  12776. Engine.prototype.setMatrix = function (uniform, matrix) {
  12777. if (!uniform)
  12778. return;
  12779. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12780. };
  12781. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12782. if (!uniform)
  12783. return;
  12784. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12785. };
  12786. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12787. if (!uniform)
  12788. return;
  12789. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12790. };
  12791. Engine.prototype.setInt = function (uniform, value) {
  12792. if (!uniform)
  12793. return;
  12794. this._gl.uniform1i(uniform, value);
  12795. };
  12796. Engine.prototype.setFloat = function (uniform, value) {
  12797. if (!uniform)
  12798. return;
  12799. this._gl.uniform1f(uniform, value);
  12800. };
  12801. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12802. if (!uniform)
  12803. return;
  12804. this._gl.uniform2f(uniform, x, y);
  12805. };
  12806. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12807. if (!uniform)
  12808. return;
  12809. this._gl.uniform3f(uniform, x, y, z);
  12810. };
  12811. Engine.prototype.setBool = function (uniform, bool) {
  12812. if (!uniform)
  12813. return;
  12814. this._gl.uniform1i(uniform, bool);
  12815. };
  12816. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12817. if (!uniform)
  12818. return;
  12819. this._gl.uniform4f(uniform, x, y, z, w);
  12820. };
  12821. Engine.prototype.setColor3 = function (uniform, color3) {
  12822. if (!uniform)
  12823. return;
  12824. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12825. };
  12826. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12827. if (!uniform)
  12828. return;
  12829. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12830. };
  12831. /**
  12832. * Sets a Color4 on a uniform variable
  12833. * @param uniform defines the uniform location
  12834. * @param color4 defines the value to be set
  12835. */
  12836. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12837. if (!uniform)
  12838. return;
  12839. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12840. };
  12841. // States
  12842. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12843. if (zOffset === void 0) { zOffset = 0; }
  12844. if (reverseSide === void 0) { reverseSide = false; }
  12845. // Culling
  12846. if (this._depthCullingState.cull !== culling || force) {
  12847. this._depthCullingState.cull = culling;
  12848. }
  12849. // Cull face
  12850. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12851. if (this._depthCullingState.cullFace !== cullFace || force) {
  12852. this._depthCullingState.cullFace = cullFace;
  12853. }
  12854. // Z offset
  12855. this.setZOffset(zOffset);
  12856. // Front face
  12857. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12858. if (this._depthCullingState.frontFace !== frontFace || force) {
  12859. this._depthCullingState.frontFace = frontFace;
  12860. }
  12861. };
  12862. Engine.prototype.setZOffset = function (value) {
  12863. this._depthCullingState.zOffset = value;
  12864. };
  12865. Engine.prototype.getZOffset = function () {
  12866. return this._depthCullingState.zOffset;
  12867. };
  12868. Engine.prototype.setDepthBuffer = function (enable) {
  12869. this._depthCullingState.depthTest = enable;
  12870. };
  12871. Engine.prototype.getDepthWrite = function () {
  12872. return this._depthCullingState.depthMask;
  12873. };
  12874. Engine.prototype.setDepthWrite = function (enable) {
  12875. this._depthCullingState.depthMask = enable;
  12876. };
  12877. Engine.prototype.setColorWrite = function (enable) {
  12878. this._gl.colorMask(enable, enable, enable, enable);
  12879. this._colorWrite = enable;
  12880. };
  12881. Engine.prototype.getColorWrite = function () {
  12882. return this._colorWrite;
  12883. };
  12884. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12885. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12886. };
  12887. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12888. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12889. if (this._alphaMode === mode) {
  12890. return;
  12891. }
  12892. switch (mode) {
  12893. case Engine.ALPHA_DISABLE:
  12894. this._alphaState.alphaBlend = false;
  12895. break;
  12896. case Engine.ALPHA_PREMULTIPLIED:
  12897. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12898. this._alphaState.alphaBlend = true;
  12899. break;
  12900. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12901. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12902. this._alphaState.alphaBlend = true;
  12903. break;
  12904. case Engine.ALPHA_COMBINE:
  12905. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12906. this._alphaState.alphaBlend = true;
  12907. break;
  12908. case Engine.ALPHA_ONEONE:
  12909. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12910. this._alphaState.alphaBlend = true;
  12911. break;
  12912. case Engine.ALPHA_ADD:
  12913. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12914. this._alphaState.alphaBlend = true;
  12915. break;
  12916. case Engine.ALPHA_SUBTRACT:
  12917. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12918. this._alphaState.alphaBlend = true;
  12919. break;
  12920. case Engine.ALPHA_MULTIPLY:
  12921. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12922. this._alphaState.alphaBlend = true;
  12923. break;
  12924. case Engine.ALPHA_MAXIMIZED:
  12925. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12926. this._alphaState.alphaBlend = true;
  12927. break;
  12928. case Engine.ALPHA_INTERPOLATE:
  12929. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12930. this._alphaState.alphaBlend = true;
  12931. break;
  12932. case Engine.ALPHA_SCREENMODE:
  12933. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12934. this._alphaState.alphaBlend = true;
  12935. break;
  12936. }
  12937. if (!noDepthWriteChange) {
  12938. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12939. }
  12940. this._alphaMode = mode;
  12941. };
  12942. Engine.prototype.getAlphaMode = function () {
  12943. return this._alphaMode;
  12944. };
  12945. // Textures
  12946. Engine.prototype.wipeCaches = function (bruteForce) {
  12947. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12948. return;
  12949. }
  12950. this._currentEffect = null;
  12951. // 6/8/2017: deltakosh: Should not be required anymore.
  12952. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12953. if (bruteForce) {
  12954. this.resetTextureCache();
  12955. this._currentProgram = null;
  12956. this._stencilState.reset();
  12957. this._depthCullingState.reset();
  12958. this.setDepthFunctionToLessOrEqual();
  12959. this._alphaState.reset();
  12960. }
  12961. this._resetVertexBufferBinding();
  12962. this._cachedIndexBuffer = null;
  12963. this._cachedEffectForVertexBuffers = null;
  12964. this._unbindVertexArrayObject();
  12965. this.bindIndexBuffer(null);
  12966. };
  12967. /**
  12968. * Set the compressed texture format to use, based on the formats you have, and the formats
  12969. * supported by the hardware / browser.
  12970. *
  12971. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12972. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12973. * to API arguments needed to compressed textures. This puts the burden on the container
  12974. * generator to house the arcane code for determining these for current & future formats.
  12975. *
  12976. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12977. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12978. *
  12979. * Note: The result of this call is not taken into account when a texture is base64.
  12980. *
  12981. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12982. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12983. *
  12984. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12985. * @returns The extension selected.
  12986. */
  12987. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12988. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12989. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12990. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12991. return this._textureFormatInUse = this._texturesSupported[i];
  12992. }
  12993. }
  12994. }
  12995. // actively set format to nothing, to allow this to be called more than once
  12996. // and possibly fail the 2nd time
  12997. this._textureFormatInUse = null;
  12998. return null;
  12999. };
  13000. Engine.prototype._createTexture = function () {
  13001. var texture = this._gl.createTexture();
  13002. if (!texture) {
  13003. throw new Error("Unable to create texture");
  13004. }
  13005. return texture;
  13006. };
  13007. /**
  13008. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  13009. * @param {string} urlArg- This contains one of the following:
  13010. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  13011. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13012. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13013. *
  13014. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  13015. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  13016. * @param {Scene} scene- Needed for loading to the correct scene.
  13017. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  13018. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  13019. * @param {callback} onError- Optional callback to be called upon failure.
  13020. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13021. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  13022. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  13023. *
  13024. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  13025. */
  13026. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  13027. var _this = this;
  13028. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13029. if (onLoad === void 0) { onLoad = null; }
  13030. if (onError === void 0) { onError = null; }
  13031. if (buffer === void 0) { buffer = null; }
  13032. if (fallBack === void 0) { fallBack = null; }
  13033. if (format === void 0) { format = null; }
  13034. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13035. var fromData = url.substr(0, 5) === "data:";
  13036. var fromBlob = url.substr(0, 5) === "blob:";
  13037. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13038. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13039. // establish the file extension, if possible
  13040. var lastDot = url.lastIndexOf('.');
  13041. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13042. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13043. var isTGA = (extension.indexOf(".tga") === 0);
  13044. // determine if a ktx file should be substituted
  13045. var isKTX = false;
  13046. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  13047. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13048. isKTX = true;
  13049. }
  13050. if (scene) {
  13051. scene._addPendingData(texture);
  13052. }
  13053. texture.url = url;
  13054. texture.generateMipMaps = !noMipmap;
  13055. texture.samplingMode = samplingMode;
  13056. texture.invertY = invertY;
  13057. if (!this._doNotHandleContextLost) {
  13058. // Keep a link to the buffer only if we plan to handle context lost
  13059. texture._buffer = buffer;
  13060. }
  13061. var onLoadObserver = null;
  13062. if (onLoad && !fallBack) {
  13063. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13064. }
  13065. if (!fallBack)
  13066. this._internalTexturesCache.push(texture);
  13067. var onerror = function (message, exception) {
  13068. if (scene) {
  13069. scene._removePendingData(texture);
  13070. }
  13071. if (onLoadObserver) {
  13072. texture.onLoadedObservable.remove(onLoadObserver);
  13073. }
  13074. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13075. if (isKTX) {
  13076. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13077. }
  13078. else if (BABYLON.Tools.UseFallbackTexture) {
  13079. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13080. }
  13081. if (onError) {
  13082. onError(message || "Unknown error", exception);
  13083. }
  13084. };
  13085. var callback = null;
  13086. // processing for non-image formats
  13087. if (isKTX || isTGA || isDDS) {
  13088. if (isKTX) {
  13089. callback = function (data) {
  13090. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13091. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13092. ktx.uploadLevels(_this._gl, !noMipmap);
  13093. return false;
  13094. }, samplingMode);
  13095. };
  13096. }
  13097. else if (isTGA) {
  13098. callback = function (arrayBuffer) {
  13099. var data = new Uint8Array(arrayBuffer);
  13100. var header = BABYLON.TGATools.GetTGAHeader(data);
  13101. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13102. BABYLON.TGATools.UploadContent(_this._gl, data);
  13103. return false;
  13104. }, samplingMode);
  13105. };
  13106. }
  13107. else if (isDDS) {
  13108. callback = function (data) {
  13109. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13110. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13111. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13112. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13113. return false;
  13114. }, samplingMode);
  13115. };
  13116. }
  13117. if (!buffer) {
  13118. this._loadFile(url, function (data) {
  13119. if (callback) {
  13120. callback(data);
  13121. }
  13122. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13123. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13124. });
  13125. }
  13126. else {
  13127. if (callback) {
  13128. callback(buffer);
  13129. }
  13130. }
  13131. // image format processing
  13132. }
  13133. else {
  13134. var onload = function (img) {
  13135. if (fromBlob && !_this._doNotHandleContextLost) {
  13136. // We need to store the image if we need to rebuild the texture
  13137. // in case of a webgl context lost
  13138. texture._buffer = img;
  13139. }
  13140. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13141. var gl = _this._gl;
  13142. var isPot = (img.width === potWidth && img.height === potHeight);
  13143. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13144. if (isPot) {
  13145. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13146. return false;
  13147. }
  13148. // Using shaders to rescale because canvas.drawImage is lossy
  13149. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13150. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13151. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13152. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13153. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13154. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13155. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13156. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13157. _this._releaseTexture(source);
  13158. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13159. continuationCallback();
  13160. });
  13161. return true;
  13162. }, samplingMode);
  13163. };
  13164. if (!fromData || isBase64)
  13165. if (buffer instanceof HTMLImageElement) {
  13166. onload(buffer);
  13167. }
  13168. else {
  13169. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13170. }
  13171. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13172. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13173. else
  13174. onload(buffer);
  13175. }
  13176. return texture;
  13177. };
  13178. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13179. var _this = this;
  13180. var rtt = this.createRenderTargetTexture({
  13181. width: destination.width,
  13182. height: destination.height,
  13183. }, {
  13184. generateMipMaps: false,
  13185. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13186. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13187. generateDepthBuffer: false,
  13188. generateStencilBuffer: false
  13189. });
  13190. if (!this._rescalePostProcess) {
  13191. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13192. }
  13193. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13194. _this._rescalePostProcess.onApply = function (effect) {
  13195. effect._bindTexture("textureSampler", source);
  13196. };
  13197. var hostingScene = scene;
  13198. if (!hostingScene) {
  13199. hostingScene = _this.scenes[_this.scenes.length - 1];
  13200. }
  13201. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13202. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13203. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13204. _this.unBindFramebuffer(rtt);
  13205. _this._releaseTexture(rtt);
  13206. if (onComplete) {
  13207. onComplete();
  13208. }
  13209. });
  13210. };
  13211. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13212. if (compression === void 0) { compression = null; }
  13213. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13214. if (!texture) {
  13215. return;
  13216. }
  13217. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13218. var internalFormat = this._getInternalFormat(format);
  13219. var textureType = this._getWebGLTextureType(type);
  13220. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13221. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13222. if (!this._doNotHandleContextLost) {
  13223. texture._bufferView = data;
  13224. texture.format = format;
  13225. texture.type = type;
  13226. texture.invertY = invertY;
  13227. texture._compression = compression;
  13228. }
  13229. if (texture.width % 4 !== 0) {
  13230. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13231. }
  13232. if (compression && data) {
  13233. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13234. }
  13235. else {
  13236. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13237. }
  13238. if (texture.generateMipMaps) {
  13239. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13240. }
  13241. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13242. // this.resetTextureCache();
  13243. texture.isReady = true;
  13244. };
  13245. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13246. if (compression === void 0) { compression = null; }
  13247. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13248. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13249. texture.baseWidth = width;
  13250. texture.baseHeight = height;
  13251. texture.width = width;
  13252. texture.height = height;
  13253. texture.format = format;
  13254. texture.generateMipMaps = generateMipMaps;
  13255. texture.samplingMode = samplingMode;
  13256. texture.invertY = invertY;
  13257. texture._compression = compression;
  13258. texture.type = type;
  13259. if (!this._doNotHandleContextLost) {
  13260. texture._bufferView = data;
  13261. }
  13262. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13263. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13264. // Filters
  13265. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13266. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13267. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13268. if (generateMipMaps) {
  13269. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13270. }
  13271. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13272. this._internalTexturesCache.push(texture);
  13273. return texture;
  13274. };
  13275. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13276. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13277. texture.baseWidth = width;
  13278. texture.baseHeight = height;
  13279. if (generateMipMaps) {
  13280. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13281. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13282. }
  13283. // this.resetTextureCache();
  13284. texture.width = width;
  13285. texture.height = height;
  13286. texture.isReady = false;
  13287. texture.generateMipMaps = generateMipMaps;
  13288. texture.samplingMode = samplingMode;
  13289. this.updateTextureSamplingMode(samplingMode, texture);
  13290. this._internalTexturesCache.push(texture);
  13291. return texture;
  13292. };
  13293. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13294. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13295. if (texture.isCube) {
  13296. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13297. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13298. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13299. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13300. }
  13301. else if (texture.is3D) {
  13302. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13303. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13304. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13305. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13306. }
  13307. else {
  13308. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13309. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13310. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13311. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13312. }
  13313. texture.samplingMode = samplingMode;
  13314. };
  13315. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13316. if (premulAlpha === void 0) { premulAlpha = false; }
  13317. if (!texture) {
  13318. return;
  13319. }
  13320. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13321. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13322. if (premulAlpha) {
  13323. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13324. }
  13325. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13326. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13327. if (texture.generateMipMaps) {
  13328. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13329. }
  13330. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13331. if (premulAlpha) {
  13332. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13333. }
  13334. texture.isReady = true;
  13335. };
  13336. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13337. if (!texture || texture._isDisabled) {
  13338. return;
  13339. }
  13340. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13341. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13342. try {
  13343. // Testing video texture support
  13344. if (this._videoTextureSupported === undefined) {
  13345. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13346. if (this._gl.getError() !== 0) {
  13347. this._videoTextureSupported = false;
  13348. }
  13349. else {
  13350. this._videoTextureSupported = true;
  13351. }
  13352. }
  13353. // Copy video through the current working canvas if video texture is not supported
  13354. if (!this._videoTextureSupported) {
  13355. if (!texture._workingCanvas) {
  13356. texture._workingCanvas = document.createElement("canvas");
  13357. var context = texture._workingCanvas.getContext("2d");
  13358. if (!context) {
  13359. throw new Error("Unable to get 2d context");
  13360. }
  13361. texture._workingContext = context;
  13362. texture._workingCanvas.width = texture.width;
  13363. texture._workingCanvas.height = texture.height;
  13364. }
  13365. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13366. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13367. }
  13368. else {
  13369. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13370. }
  13371. if (texture.generateMipMaps) {
  13372. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13373. }
  13374. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13375. // this.resetTextureCache();
  13376. texture.isReady = true;
  13377. }
  13378. catch (ex) {
  13379. // Something unexpected
  13380. // Let's disable the texture
  13381. texture._isDisabled = true;
  13382. }
  13383. };
  13384. /**
  13385. * Updates a depth texture Comparison Mode and Function.
  13386. * If the comparison Function is equal to 0, the mode will be set to none.
  13387. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13388. * @param texture The texture to set the comparison function for
  13389. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13390. */
  13391. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13392. if (this.webGLVersion === 1) {
  13393. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13394. return;
  13395. }
  13396. var gl = this._gl;
  13397. if (texture.isCube) {
  13398. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13399. if (comparisonFunction === 0) {
  13400. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13401. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13402. }
  13403. else {
  13404. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13405. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13406. }
  13407. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13408. }
  13409. else {
  13410. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13411. if (comparisonFunction === 0) {
  13412. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13413. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13414. }
  13415. else {
  13416. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13417. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13418. }
  13419. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13420. }
  13421. texture._comparisonFunction = comparisonFunction;
  13422. };
  13423. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13424. var width = size.width || size;
  13425. var height = size.height || size;
  13426. internalTexture.baseWidth = width;
  13427. internalTexture.baseHeight = height;
  13428. internalTexture.width = width;
  13429. internalTexture.height = height;
  13430. internalTexture.isReady = true;
  13431. internalTexture.samples = 1;
  13432. internalTexture.generateMipMaps = false;
  13433. internalTexture._generateDepthBuffer = true;
  13434. internalTexture._generateStencilBuffer = generateStencil;
  13435. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13436. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13437. internalTexture._comparisonFunction = comparisonFunction;
  13438. var gl = this._gl;
  13439. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13440. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13441. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13442. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13443. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13444. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13445. if (comparisonFunction === 0) {
  13446. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13447. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13448. }
  13449. else {
  13450. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13451. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13452. }
  13453. };
  13454. /**
  13455. * Creates a depth stencil texture.
  13456. * This is only available in WebGL 2 or with the depth texture extension available.
  13457. * @param size The size of face edge in the texture.
  13458. * @param options The options defining the texture.
  13459. * @returns The texture
  13460. */
  13461. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13462. if (options.isCube) {
  13463. var width = size.width || size;
  13464. return this._createDepthStencilCubeTexture(width, options);
  13465. }
  13466. else {
  13467. return this._createDepthStencilTexture(size, options);
  13468. }
  13469. };
  13470. /**
  13471. * Creates a depth stencil texture.
  13472. * This is only available in WebGL 2 or with the depth texture extension available.
  13473. * @param size The size of face edge in the texture.
  13474. * @param options The options defining the texture.
  13475. * @returns The texture
  13476. */
  13477. Engine.prototype._createDepthStencilTexture = function (size, options) {
  13478. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13479. if (!this._caps.depthTextureExtension) {
  13480. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13481. return internalTexture;
  13482. }
  13483. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13484. var gl = this._gl;
  13485. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13486. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13487. if (this.webGLVersion > 1) {
  13488. if (internalOptions.generateStencil) {
  13489. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13490. }
  13491. else {
  13492. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13493. }
  13494. }
  13495. else {
  13496. if (internalOptions.generateStencil) {
  13497. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13498. }
  13499. else {
  13500. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13501. }
  13502. }
  13503. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13504. return internalTexture;
  13505. };
  13506. /**
  13507. * Creates a depth stencil cube texture.
  13508. * This is only available in WebGL 2.
  13509. * @param size The size of face edge in the cube texture.
  13510. * @param options The options defining the cube texture.
  13511. * @returns The cube texture
  13512. */
  13513. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  13514. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13515. internalTexture.isCube = true;
  13516. if (this.webGLVersion === 1) {
  13517. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13518. return internalTexture;
  13519. }
  13520. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13521. var gl = this._gl;
  13522. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13523. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13524. // Create the depth/stencil buffer
  13525. for (var face = 0; face < 6; face++) {
  13526. if (internalOptions.generateStencil) {
  13527. 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);
  13528. }
  13529. else {
  13530. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13531. }
  13532. }
  13533. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13534. return internalTexture;
  13535. };
  13536. /**
  13537. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13538. * @param renderTarget The render target to set the frame buffer for
  13539. */
  13540. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13541. // Create the framebuffer
  13542. var internalTexture = renderTarget.getInternalTexture();
  13543. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13544. return;
  13545. }
  13546. var gl = this._gl;
  13547. var depthStencilTexture = renderTarget.depthStencilTexture;
  13548. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13549. if (depthStencilTexture.isCube) {
  13550. if (depthStencilTexture._generateStencilBuffer) {
  13551. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13552. }
  13553. else {
  13554. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13555. }
  13556. }
  13557. else {
  13558. if (depthStencilTexture._generateStencilBuffer) {
  13559. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13560. }
  13561. else {
  13562. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13563. }
  13564. }
  13565. this.bindUnboundFramebuffer(null);
  13566. };
  13567. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13568. var fullOptions = new RenderTargetCreationOptions();
  13569. if (options !== undefined && typeof options === "object") {
  13570. fullOptions.generateMipMaps = options.generateMipMaps;
  13571. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13572. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13573. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13574. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13575. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  13576. }
  13577. else {
  13578. fullOptions.generateMipMaps = options;
  13579. fullOptions.generateDepthBuffer = true;
  13580. fullOptions.generateStencilBuffer = false;
  13581. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13582. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13583. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  13584. }
  13585. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13586. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13587. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13588. }
  13589. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13590. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13591. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13592. }
  13593. var gl = this._gl;
  13594. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13595. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13596. var width = size.width || size;
  13597. var height = size.height || size;
  13598. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13599. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13600. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13601. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13602. }
  13603. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13604. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13605. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13606. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13607. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13608. // Create the framebuffer
  13609. var framebuffer = gl.createFramebuffer();
  13610. this.bindUnboundFramebuffer(framebuffer);
  13611. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13612. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13613. if (fullOptions.generateMipMaps) {
  13614. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13615. }
  13616. // Unbind
  13617. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13618. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13619. this.bindUnboundFramebuffer(null);
  13620. texture._framebuffer = framebuffer;
  13621. texture.baseWidth = width;
  13622. texture.baseHeight = height;
  13623. texture.width = width;
  13624. texture.height = height;
  13625. texture.isReady = true;
  13626. texture.samples = 1;
  13627. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13628. texture.samplingMode = fullOptions.samplingMode;
  13629. texture.type = fullOptions.type;
  13630. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13631. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13632. // this.resetTextureCache();
  13633. this._internalTexturesCache.push(texture);
  13634. return texture;
  13635. };
  13636. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13637. var generateMipMaps = false;
  13638. var generateDepthBuffer = true;
  13639. var generateStencilBuffer = false;
  13640. var generateDepthTexture = false;
  13641. var textureCount = 1;
  13642. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13643. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13644. var types = [], samplingModes = [];
  13645. if (options !== undefined) {
  13646. generateMipMaps = options.generateMipMaps;
  13647. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13648. generateStencilBuffer = options.generateStencilBuffer;
  13649. generateDepthTexture = options.generateDepthTexture;
  13650. textureCount = options.textureCount || 1;
  13651. if (options.types) {
  13652. types = options.types;
  13653. }
  13654. if (options.samplingModes) {
  13655. samplingModes = options.samplingModes;
  13656. }
  13657. }
  13658. var gl = this._gl;
  13659. // Create the framebuffer
  13660. var framebuffer = gl.createFramebuffer();
  13661. this.bindUnboundFramebuffer(framebuffer);
  13662. var width = size.width || size;
  13663. var height = size.height || size;
  13664. var textures = [];
  13665. var attachments = [];
  13666. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13667. for (var i = 0; i < textureCount; i++) {
  13668. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13669. var type = types[i] || defaultType;
  13670. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13671. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13672. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13673. }
  13674. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13675. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13676. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13677. }
  13678. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13679. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13680. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13681. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13682. }
  13683. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13684. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13685. textures.push(texture);
  13686. attachments.push(attachment);
  13687. gl.activeTexture(gl["TEXTURE" + i]);
  13688. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13689. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13690. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13691. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13692. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13693. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13694. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13695. if (generateMipMaps) {
  13696. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13697. }
  13698. // Unbind
  13699. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13700. texture._framebuffer = framebuffer;
  13701. texture._depthStencilBuffer = depthStencilBuffer;
  13702. texture.baseWidth = width;
  13703. texture.baseHeight = height;
  13704. texture.width = width;
  13705. texture.height = height;
  13706. texture.isReady = true;
  13707. texture.samples = 1;
  13708. texture.generateMipMaps = generateMipMaps;
  13709. texture.samplingMode = samplingMode;
  13710. texture.type = type;
  13711. texture._generateDepthBuffer = generateDepthBuffer;
  13712. texture._generateStencilBuffer = generateStencilBuffer;
  13713. texture._attachments = attachments;
  13714. this._internalTexturesCache.push(texture);
  13715. }
  13716. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13717. // Depth texture
  13718. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13719. gl.activeTexture(gl.TEXTURE0);
  13720. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13721. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13722. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13723. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13724. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13725. 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);
  13726. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13727. depthTexture._framebuffer = framebuffer;
  13728. depthTexture.baseWidth = width;
  13729. depthTexture.baseHeight = height;
  13730. depthTexture.width = width;
  13731. depthTexture.height = height;
  13732. depthTexture.isReady = true;
  13733. depthTexture.samples = 1;
  13734. depthTexture.generateMipMaps = generateMipMaps;
  13735. depthTexture.samplingMode = gl.NEAREST;
  13736. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13737. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13738. textures.push(depthTexture);
  13739. this._internalTexturesCache.push(depthTexture);
  13740. }
  13741. gl.drawBuffers(attachments);
  13742. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13743. this.bindUnboundFramebuffer(null);
  13744. this.resetTextureCache();
  13745. return textures;
  13746. };
  13747. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13748. if (samples === void 0) { samples = 1; }
  13749. var depthStencilBuffer = null;
  13750. var gl = this._gl;
  13751. // Create the depth/stencil buffer
  13752. if (generateStencilBuffer) {
  13753. depthStencilBuffer = gl.createRenderbuffer();
  13754. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13755. if (samples > 1) {
  13756. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13757. }
  13758. else {
  13759. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13760. }
  13761. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13762. }
  13763. else if (generateDepthBuffer) {
  13764. depthStencilBuffer = gl.createRenderbuffer();
  13765. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13766. if (samples > 1) {
  13767. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13768. }
  13769. else {
  13770. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13771. }
  13772. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13773. }
  13774. return depthStencilBuffer;
  13775. };
  13776. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13777. if (this.webGLVersion < 2 || !texture) {
  13778. return 1;
  13779. }
  13780. if (texture.samples === samples) {
  13781. return samples;
  13782. }
  13783. var gl = this._gl;
  13784. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13785. // Dispose previous render buffers
  13786. if (texture._depthStencilBuffer) {
  13787. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13788. texture._depthStencilBuffer = null;
  13789. }
  13790. if (texture._MSAAFramebuffer) {
  13791. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13792. texture._MSAAFramebuffer = null;
  13793. }
  13794. if (texture._MSAARenderBuffer) {
  13795. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13796. texture._MSAARenderBuffer = null;
  13797. }
  13798. if (samples > 1) {
  13799. var framebuffer = gl.createFramebuffer();
  13800. if (!framebuffer) {
  13801. throw new Error("Unable to create multi sampled framebuffer");
  13802. }
  13803. texture._MSAAFramebuffer = framebuffer;
  13804. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13805. var colorRenderbuffer = gl.createRenderbuffer();
  13806. if (!colorRenderbuffer) {
  13807. throw new Error("Unable to create multi sampled framebuffer");
  13808. }
  13809. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13810. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13811. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13812. texture._MSAARenderBuffer = colorRenderbuffer;
  13813. }
  13814. else {
  13815. this.bindUnboundFramebuffer(texture._framebuffer);
  13816. }
  13817. texture.samples = samples;
  13818. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13819. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13820. this.bindUnboundFramebuffer(null);
  13821. return samples;
  13822. };
  13823. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13824. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13825. return 1;
  13826. }
  13827. if (textures[0].samples === samples) {
  13828. return samples;
  13829. }
  13830. var gl = this._gl;
  13831. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13832. // Dispose previous render buffers
  13833. if (textures[0]._depthStencilBuffer) {
  13834. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13835. textures[0]._depthStencilBuffer = null;
  13836. }
  13837. if (textures[0]._MSAAFramebuffer) {
  13838. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13839. textures[0]._MSAAFramebuffer = null;
  13840. }
  13841. for (var i = 0; i < textures.length; i++) {
  13842. if (textures[i]._MSAARenderBuffer) {
  13843. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13844. textures[i]._MSAARenderBuffer = null;
  13845. }
  13846. }
  13847. if (samples > 1) {
  13848. var framebuffer = gl.createFramebuffer();
  13849. if (!framebuffer) {
  13850. throw new Error("Unable to create multi sampled framebuffer");
  13851. }
  13852. this.bindUnboundFramebuffer(framebuffer);
  13853. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13854. var attachments = [];
  13855. for (var i = 0; i < textures.length; i++) {
  13856. var texture = textures[i];
  13857. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13858. var colorRenderbuffer = gl.createRenderbuffer();
  13859. if (!colorRenderbuffer) {
  13860. throw new Error("Unable to create multi sampled framebuffer");
  13861. }
  13862. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13863. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13864. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13865. texture._MSAAFramebuffer = framebuffer;
  13866. texture._MSAARenderBuffer = colorRenderbuffer;
  13867. texture.samples = samples;
  13868. texture._depthStencilBuffer = depthStencilBuffer;
  13869. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13870. attachments.push(attachment);
  13871. }
  13872. gl.drawBuffers(attachments);
  13873. }
  13874. else {
  13875. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13876. }
  13877. this.bindUnboundFramebuffer(null);
  13878. return samples;
  13879. };
  13880. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13881. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13882. };
  13883. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13884. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13885. };
  13886. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13887. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  13888. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13889. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13890. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13891. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13892. }
  13893. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13894. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13895. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13896. }
  13897. var gl = this._gl;
  13898. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13899. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13900. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13901. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13902. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13903. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13904. }
  13905. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13906. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13907. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13908. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13909. for (var face = 0; face < 6; face++) {
  13910. 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);
  13911. }
  13912. // Create the framebuffer
  13913. var framebuffer = gl.createFramebuffer();
  13914. this.bindUnboundFramebuffer(framebuffer);
  13915. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13916. // MipMaps
  13917. if (fullOptions.generateMipMaps) {
  13918. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13919. }
  13920. // Unbind
  13921. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13922. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13923. this.bindUnboundFramebuffer(null);
  13924. texture._framebuffer = framebuffer;
  13925. texture.width = size;
  13926. texture.height = size;
  13927. texture.isReady = true;
  13928. texture.isCube = true;
  13929. texture.samples = 1;
  13930. texture.generateMipMaps = fullOptions.generateMipMaps;
  13931. texture.samplingMode = fullOptions.samplingMode;
  13932. texture.type = fullOptions.type;
  13933. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13934. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13935. this._internalTexturesCache.push(texture);
  13936. return texture;
  13937. };
  13938. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13939. var _this = this;
  13940. if (onLoad === void 0) { onLoad = null; }
  13941. if (onError === void 0) { onError = null; }
  13942. if (forcedExtension === void 0) { forcedExtension = null; }
  13943. var callback = function (loadData) {
  13944. if (!loadData) {
  13945. if (onLoad) {
  13946. onLoad(null);
  13947. }
  13948. return;
  13949. }
  13950. var texture = loadData.texture;
  13951. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13952. texture._lodGenerationScale = scale;
  13953. texture._lodGenerationOffset = offset;
  13954. if (_this._caps.textureLOD) {
  13955. // Do not add extra process if texture lod is supported.
  13956. if (onLoad) {
  13957. onLoad(texture);
  13958. }
  13959. return;
  13960. }
  13961. var mipSlices = 3;
  13962. var gl = _this._gl;
  13963. var width = loadData.width;
  13964. if (!width) {
  13965. return;
  13966. }
  13967. var textures = [];
  13968. for (var i = 0; i < mipSlices; i++) {
  13969. //compute LOD from even spacing in smoothness (matching shader calculation)
  13970. var smoothness = i / (mipSlices - 1);
  13971. var roughness = 1 - smoothness;
  13972. var minLODIndex = offset; // roughness = 0
  13973. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13974. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13975. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13976. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13977. glTextureFromLod.isCube = true;
  13978. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13979. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13980. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13981. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13982. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13983. if (loadData.isDDS) {
  13984. var info = loadData.info;
  13985. var data = loadData.data;
  13986. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13987. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13988. }
  13989. else {
  13990. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13991. }
  13992. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13993. // Wrap in a base texture for easy binding.
  13994. var lodTexture = new BABYLON.BaseTexture(scene);
  13995. lodTexture.isCube = true;
  13996. lodTexture._texture = glTextureFromLod;
  13997. glTextureFromLod.isReady = true;
  13998. textures.push(lodTexture);
  13999. }
  14000. texture._lodTextureHigh = textures[2];
  14001. texture._lodTextureMid = textures[1];
  14002. texture._lodTextureLow = textures[0];
  14003. if (onLoad) {
  14004. onLoad(texture);
  14005. }
  14006. };
  14007. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  14008. };
  14009. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  14010. var _this = this;
  14011. if (onLoad === void 0) { onLoad = null; }
  14012. if (onError === void 0) { onError = null; }
  14013. if (forcedExtension === void 0) { forcedExtension = null; }
  14014. var gl = this._gl;
  14015. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  14016. texture.isCube = true;
  14017. texture.url = rootUrl;
  14018. texture.generateMipMaps = !noMipmap;
  14019. if (!this._doNotHandleContextLost) {
  14020. texture._extension = forcedExtension;
  14021. texture._files = files;
  14022. }
  14023. var isKTX = false;
  14024. var isDDS = false;
  14025. var lastDot = rootUrl.lastIndexOf('.');
  14026. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  14027. if (this._textureFormatInUse) {
  14028. extension = this._textureFormatInUse;
  14029. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14030. isKTX = true;
  14031. }
  14032. else {
  14033. isDDS = (extension === ".dds");
  14034. }
  14035. var onerror = function (request, exception) {
  14036. if (onError && request) {
  14037. onError(request.status + " " + request.statusText, exception);
  14038. }
  14039. };
  14040. if (isKTX) {
  14041. this._loadFile(rootUrl, function (data) {
  14042. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14043. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14044. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14045. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14046. ktx.uploadLevels(_this._gl, !noMipmap);
  14047. _this.setCubeMapTextureParams(gl, loadMipmap);
  14048. texture.width = ktx.pixelWidth;
  14049. texture.height = ktx.pixelHeight;
  14050. texture.isReady = true;
  14051. }, undefined, undefined, true, onerror);
  14052. }
  14053. else if (isDDS) {
  14054. if (files && files.length === 6) {
  14055. this._cascadeLoadFiles(scene, function (imgs) {
  14056. var info;
  14057. var loadMipmap = false;
  14058. var width = 0;
  14059. for (var index = 0; index < imgs.length; index++) {
  14060. var data = imgs[index];
  14061. info = BABYLON.DDSTools.GetDDSInfo(data);
  14062. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14063. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14064. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14065. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14066. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14067. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14068. }
  14069. texture.width = info.width;
  14070. texture.height = info.height;
  14071. texture.type = info.textureType;
  14072. width = info.width;
  14073. }
  14074. _this.setCubeMapTextureParams(gl, loadMipmap);
  14075. texture.isReady = true;
  14076. if (onLoad) {
  14077. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14078. }
  14079. }, files, onError);
  14080. }
  14081. else {
  14082. this._loadFile(rootUrl, function (data) {
  14083. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14084. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14085. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14086. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14087. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14088. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14089. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14090. }
  14091. _this.setCubeMapTextureParams(gl, loadMipmap);
  14092. texture.width = info.width;
  14093. texture.height = info.height;
  14094. texture.isReady = true;
  14095. texture.type = info.textureType;
  14096. if (onLoad) {
  14097. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14098. }
  14099. }, undefined, undefined, true, onerror);
  14100. }
  14101. }
  14102. else {
  14103. if (!files) {
  14104. throw new Error("Cannot load cubemap because files were not defined");
  14105. }
  14106. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14107. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14108. var height = width;
  14109. _this._prepareWorkingCanvas();
  14110. if (!_this._workingCanvas || !_this._workingContext) {
  14111. return;
  14112. }
  14113. _this._workingCanvas.width = width;
  14114. _this._workingCanvas.height = height;
  14115. var faces = [
  14116. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14117. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14118. ];
  14119. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14120. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14121. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14122. for (var index = 0; index < faces.length; index++) {
  14123. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14124. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14125. }
  14126. if (!noMipmap) {
  14127. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14128. }
  14129. _this.setCubeMapTextureParams(gl, !noMipmap);
  14130. texture.width = width;
  14131. texture.height = height;
  14132. texture.isReady = true;
  14133. if (format) {
  14134. texture.format = format;
  14135. }
  14136. texture.onLoadedObservable.notifyObservers(texture);
  14137. texture.onLoadedObservable.clear();
  14138. if (onLoad) {
  14139. onLoad();
  14140. }
  14141. }, files, onError);
  14142. }
  14143. this._internalTexturesCache.push(texture);
  14144. return texture;
  14145. };
  14146. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14147. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14148. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14149. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14150. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14151. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14152. // this.resetTextureCache();
  14153. };
  14154. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14155. if (compression === void 0) { compression = null; }
  14156. if (level === void 0) { level = 0; }
  14157. texture._bufferViewArray = data;
  14158. texture.format = format;
  14159. texture.type = type;
  14160. texture.invertY = invertY;
  14161. texture._compression = compression;
  14162. var gl = this._gl;
  14163. var textureType = this._getWebGLTextureType(type);
  14164. var internalFormat = this._getInternalFormat(format);
  14165. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14166. var needConversion = false;
  14167. if (internalFormat === gl.RGB) {
  14168. internalFormat = gl.RGBA;
  14169. needConversion = true;
  14170. }
  14171. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14172. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14173. if (texture.width % 4 !== 0) {
  14174. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14175. }
  14176. // Data are known to be in +X +Y +Z -X -Y -Z
  14177. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14178. var faceData = data[faceIndex];
  14179. if (compression) {
  14180. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14181. }
  14182. else {
  14183. if (needConversion) {
  14184. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14185. }
  14186. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14187. }
  14188. }
  14189. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14190. if (isPot && texture.generateMipMaps && level === 0) {
  14191. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14192. }
  14193. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14194. // this.resetTextureCache();
  14195. texture.isReady = true;
  14196. };
  14197. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14198. if (compression === void 0) { compression = null; }
  14199. var gl = this._gl;
  14200. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14201. texture.isCube = true;
  14202. texture.generateMipMaps = generateMipMaps;
  14203. texture.format = format;
  14204. texture.type = type;
  14205. if (!this._doNotHandleContextLost) {
  14206. texture._bufferViewArray = data;
  14207. }
  14208. var textureType = this._getWebGLTextureType(type);
  14209. var internalFormat = this._getInternalFormat(format);
  14210. if (internalFormat === gl.RGB) {
  14211. internalFormat = gl.RGBA;
  14212. }
  14213. var width = size;
  14214. var height = width;
  14215. texture.width = width;
  14216. texture.height = height;
  14217. // Double check on POT to generate Mips.
  14218. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14219. if (!isPot) {
  14220. generateMipMaps = false;
  14221. }
  14222. // Upload data if needed. The texture won't be ready until then.
  14223. if (data) {
  14224. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14225. }
  14226. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14227. // Filters
  14228. if (data && generateMipMaps) {
  14229. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14230. }
  14231. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14232. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14233. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14234. }
  14235. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14236. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14237. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14238. }
  14239. else {
  14240. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14241. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14242. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14243. }
  14244. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14245. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14246. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14247. return texture;
  14248. };
  14249. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14250. var _this = this;
  14251. if (onLoad === void 0) { onLoad = null; }
  14252. if (onError === void 0) { onError = null; }
  14253. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14254. if (invertY === void 0) { invertY = false; }
  14255. var gl = this._gl;
  14256. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14257. scene._addPendingData(texture);
  14258. texture.url = url;
  14259. this._internalTexturesCache.push(texture);
  14260. var onerror = function (request, exception) {
  14261. scene._removePendingData(texture);
  14262. if (onError && request) {
  14263. onError(request.status + " " + request.statusText, exception);
  14264. }
  14265. };
  14266. var internalCallback = function (data) {
  14267. var width = texture.width;
  14268. var faceDataArrays = callback(data);
  14269. if (!faceDataArrays) {
  14270. return;
  14271. }
  14272. if (mipmmapGenerator) {
  14273. var textureType = _this._getWebGLTextureType(type);
  14274. var internalFormat = _this._getInternalFormat(format);
  14275. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14276. var needConversion = false;
  14277. if (internalFormat === gl.RGB) {
  14278. internalFormat = gl.RGBA;
  14279. needConversion = true;
  14280. }
  14281. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14282. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14283. var mipData = mipmmapGenerator(faceDataArrays);
  14284. for (var level = 0; level < mipData.length; level++) {
  14285. var mipSize = width >> level;
  14286. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14287. var mipFaceData = mipData[level][faceIndex];
  14288. if (needConversion) {
  14289. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14290. }
  14291. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14292. }
  14293. }
  14294. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14295. }
  14296. else {
  14297. texture.generateMipMaps = !noMipmap;
  14298. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14299. }
  14300. texture.isReady = true;
  14301. // this.resetTextureCache();
  14302. scene._removePendingData(texture);
  14303. if (onLoad) {
  14304. onLoad();
  14305. }
  14306. };
  14307. this._loadFile(url, function (data) {
  14308. internalCallback(data);
  14309. }, undefined, scene.database, true, onerror);
  14310. return texture;
  14311. };
  14312. ;
  14313. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14314. if (compression === void 0) { compression = null; }
  14315. var internalFormat = this._getInternalFormat(format);
  14316. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14317. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14318. if (!this._doNotHandleContextLost) {
  14319. texture._bufferView = data;
  14320. texture.format = format;
  14321. texture.invertY = invertY;
  14322. texture._compression = compression;
  14323. }
  14324. if (texture.width % 4 !== 0) {
  14325. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14326. }
  14327. if (compression && data) {
  14328. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14329. }
  14330. else {
  14331. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14332. }
  14333. if (texture.generateMipMaps) {
  14334. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14335. }
  14336. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14337. // this.resetTextureCache();
  14338. texture.isReady = true;
  14339. };
  14340. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14341. if (compression === void 0) { compression = null; }
  14342. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14343. texture.baseWidth = width;
  14344. texture.baseHeight = height;
  14345. texture.baseDepth = depth;
  14346. texture.width = width;
  14347. texture.height = height;
  14348. texture.depth = depth;
  14349. texture.format = format;
  14350. texture.generateMipMaps = generateMipMaps;
  14351. texture.samplingMode = samplingMode;
  14352. texture.is3D = true;
  14353. if (!this._doNotHandleContextLost) {
  14354. texture._bufferView = data;
  14355. }
  14356. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14357. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14358. // Filters
  14359. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14360. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14361. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14362. if (generateMipMaps) {
  14363. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14364. }
  14365. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14366. this._internalTexturesCache.push(texture);
  14367. return texture;
  14368. };
  14369. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14370. var gl = this._gl;
  14371. if (!gl) {
  14372. return;
  14373. }
  14374. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14375. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14376. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14377. if (!noMipmap && !isCompressed) {
  14378. gl.generateMipmap(gl.TEXTURE_2D);
  14379. }
  14380. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14381. // this.resetTextureCache();
  14382. if (scene) {
  14383. scene._removePendingData(texture);
  14384. }
  14385. texture.onLoadedObservable.notifyObservers(texture);
  14386. texture.onLoadedObservable.clear();
  14387. };
  14388. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14389. var _this = this;
  14390. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14391. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14392. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14393. var gl = this._gl;
  14394. if (!gl) {
  14395. return;
  14396. }
  14397. if (!texture._webGLTexture) {
  14398. // this.resetTextureCache();
  14399. if (scene) {
  14400. scene._removePendingData(texture);
  14401. }
  14402. return;
  14403. }
  14404. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14405. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14406. texture.baseWidth = width;
  14407. texture.baseHeight = height;
  14408. texture.width = potWidth;
  14409. texture.height = potHeight;
  14410. texture.isReady = true;
  14411. if (processFunction(potWidth, potHeight, function () {
  14412. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14413. })) {
  14414. // Returning as texture needs extra async steps
  14415. return;
  14416. }
  14417. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14418. };
  14419. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14420. // Create new RGBA data container.
  14421. var rgbaData;
  14422. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14423. rgbaData = new Float32Array(width * height * 4);
  14424. }
  14425. else {
  14426. rgbaData = new Uint32Array(width * height * 4);
  14427. }
  14428. // Convert each pixel.
  14429. for (var x = 0; x < width; x++) {
  14430. for (var y = 0; y < height; y++) {
  14431. var index = (y * width + x) * 3;
  14432. var newIndex = (y * width + x) * 4;
  14433. // Map Old Value to new value.
  14434. rgbaData[newIndex + 0] = rgbData[index + 0];
  14435. rgbaData[newIndex + 1] = rgbData[index + 1];
  14436. rgbaData[newIndex + 2] = rgbData[index + 2];
  14437. // Add fully opaque alpha channel.
  14438. rgbaData[newIndex + 3] = 1;
  14439. }
  14440. }
  14441. return rgbaData;
  14442. };
  14443. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14444. var gl = this._gl;
  14445. if (texture._framebuffer) {
  14446. gl.deleteFramebuffer(texture._framebuffer);
  14447. texture._framebuffer = null;
  14448. }
  14449. if (texture._depthStencilBuffer) {
  14450. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14451. texture._depthStencilBuffer = null;
  14452. }
  14453. if (texture._MSAAFramebuffer) {
  14454. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14455. texture._MSAAFramebuffer = null;
  14456. }
  14457. if (texture._MSAARenderBuffer) {
  14458. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14459. texture._MSAARenderBuffer = null;
  14460. }
  14461. };
  14462. Engine.prototype._releaseTexture = function (texture) {
  14463. var gl = this._gl;
  14464. this._releaseFramebufferObjects(texture);
  14465. gl.deleteTexture(texture._webGLTexture);
  14466. // Unbind channels
  14467. this.unbindAllTextures();
  14468. var index = this._internalTexturesCache.indexOf(texture);
  14469. if (index !== -1) {
  14470. this._internalTexturesCache.splice(index, 1);
  14471. }
  14472. // Integrated fixed lod samplers.
  14473. if (texture._lodTextureHigh) {
  14474. texture._lodTextureHigh.dispose();
  14475. }
  14476. if (texture._lodTextureMid) {
  14477. texture._lodTextureMid.dispose();
  14478. }
  14479. if (texture._lodTextureLow) {
  14480. texture._lodTextureLow.dispose();
  14481. }
  14482. };
  14483. Engine.prototype.setProgram = function (program) {
  14484. if (this._currentProgram !== program) {
  14485. this._gl.useProgram(program);
  14486. this._currentProgram = program;
  14487. }
  14488. };
  14489. Engine.prototype.bindSamplers = function (effect) {
  14490. this.setProgram(effect.getProgram());
  14491. var samplers = effect.getSamplers();
  14492. for (var index = 0; index < samplers.length; index++) {
  14493. var uniform = effect.getUniform(samplers[index]);
  14494. if (uniform) {
  14495. this._boundUniforms[index] = uniform;
  14496. }
  14497. }
  14498. this._currentEffect = null;
  14499. };
  14500. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14501. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14502. return;
  14503. }
  14504. // Remove
  14505. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14506. // Bind last to it
  14507. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14508. // Bind to dummy
  14509. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14510. };
  14511. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14512. if (!internalTexture) {
  14513. return -1;
  14514. }
  14515. internalTexture._initialSlot = channel;
  14516. if (this.disableTextureBindingOptimization) {
  14517. if (channel !== internalTexture._designatedSlot) {
  14518. this._textureCollisions.addCount(1, false);
  14519. }
  14520. }
  14521. else {
  14522. if (channel !== internalTexture._designatedSlot) {
  14523. if (internalTexture._designatedSlot > -1) {
  14524. return internalTexture._designatedSlot;
  14525. }
  14526. else {
  14527. // No slot for this texture, let's pick a new one (if we find a free slot)
  14528. if (this._nextFreeTextureSlots.length) {
  14529. return this._nextFreeTextureSlots[0];
  14530. }
  14531. // We need to recycle the oldest bound texture, sorry.
  14532. this._textureCollisions.addCount(1, false);
  14533. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14534. }
  14535. }
  14536. }
  14537. return channel;
  14538. };
  14539. Engine.prototype._linkTrackers = function (previous, next) {
  14540. previous.next = next;
  14541. next.previous = previous;
  14542. };
  14543. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14544. var currentSlot = internalTexture._designatedSlot;
  14545. if (currentSlot === -1) {
  14546. return -1;
  14547. }
  14548. internalTexture._designatedSlot = -1;
  14549. if (this.disableTextureBindingOptimization) {
  14550. return -1;
  14551. }
  14552. // Remove from bound list
  14553. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14554. // Free the slot
  14555. this._boundTexturesCache[currentSlot] = null;
  14556. this._nextFreeTextureSlots.push(currentSlot);
  14557. return currentSlot;
  14558. };
  14559. Engine.prototype._activateCurrentTexture = function () {
  14560. if (this._currentTextureChannel !== this._activeChannel) {
  14561. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14562. this._currentTextureChannel = this._activeChannel;
  14563. }
  14564. };
  14565. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14566. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14567. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14568. this._activeChannel = texture._designatedSlot;
  14569. }
  14570. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14571. var isTextureForRendering = texture && texture._initialSlot > -1;
  14572. if (currentTextureBound !== texture) {
  14573. if (currentTextureBound) {
  14574. this._removeDesignatedSlot(currentTextureBound);
  14575. }
  14576. this._activateCurrentTexture();
  14577. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14578. this._boundTexturesCache[this._activeChannel] = texture;
  14579. if (texture) {
  14580. if (!this.disableTextureBindingOptimization) {
  14581. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14582. if (slotIndex > -1) {
  14583. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14584. }
  14585. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14586. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14587. }
  14588. texture._designatedSlot = this._activeChannel;
  14589. }
  14590. }
  14591. else if (forTextureDataUpdate) {
  14592. this._activateCurrentTexture();
  14593. }
  14594. if (isTextureForRendering && !forTextureDataUpdate) {
  14595. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14596. }
  14597. };
  14598. Engine.prototype._bindTexture = function (channel, texture) {
  14599. if (channel < 0) {
  14600. return;
  14601. }
  14602. if (texture) {
  14603. channel = this._getCorrectTextureChannel(channel, texture);
  14604. }
  14605. this._activeChannel = channel;
  14606. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14607. };
  14608. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14609. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14610. };
  14611. Engine.prototype.unbindAllTextures = function () {
  14612. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14613. this._activeChannel = channel;
  14614. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14615. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14616. if (this.webGLVersion > 1) {
  14617. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14618. }
  14619. }
  14620. };
  14621. /**
  14622. * Sets a texture to the according uniform.
  14623. * @param channel The texture channel
  14624. * @param uniform The uniform to set
  14625. * @param texture The texture to apply
  14626. */
  14627. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14628. if (channel < 0) {
  14629. return;
  14630. }
  14631. if (uniform) {
  14632. this._boundUniforms[channel] = uniform;
  14633. }
  14634. this._setTexture(channel, texture);
  14635. };
  14636. /**
  14637. * Sets a depth stencil texture from a render target to the according uniform.
  14638. * @param channel The texture channel
  14639. * @param uniform The uniform to set
  14640. * @param texture The render target texture containing the depth stencil texture to apply
  14641. */
  14642. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  14643. if (channel < 0) {
  14644. return;
  14645. }
  14646. if (uniform) {
  14647. this._boundUniforms[channel] = uniform;
  14648. }
  14649. if (!texture || !texture.depthStencilTexture) {
  14650. this._setTexture(channel, null);
  14651. }
  14652. else {
  14653. this._setTexture(channel, texture, false, true);
  14654. }
  14655. };
  14656. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14657. var uniform = this._boundUniforms[sourceSlot];
  14658. if (uniform._currentState === destination) {
  14659. return;
  14660. }
  14661. this._gl.uniform1i(uniform, destination);
  14662. uniform._currentState = destination;
  14663. };
  14664. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  14665. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14666. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  14667. // Not ready?
  14668. if (!texture) {
  14669. if (this._boundTexturesCache[channel] != null) {
  14670. this._activeChannel = channel;
  14671. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14672. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14673. if (this.webGLVersion > 1) {
  14674. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14675. }
  14676. }
  14677. return false;
  14678. }
  14679. // Video
  14680. if (texture.video) {
  14681. this._activeChannel = channel;
  14682. texture.update();
  14683. }
  14684. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14685. texture.delayLoad();
  14686. return false;
  14687. }
  14688. var internalTexture;
  14689. if (depthStencilTexture) {
  14690. internalTexture = texture.depthStencilTexture;
  14691. }
  14692. else if (texture.isReady()) {
  14693. internalTexture = texture.getInternalTexture();
  14694. }
  14695. else if (texture.isCube) {
  14696. internalTexture = this.emptyCubeTexture;
  14697. }
  14698. else if (texture.is3D) {
  14699. internalTexture = this.emptyTexture3D;
  14700. }
  14701. else {
  14702. internalTexture = this.emptyTexture;
  14703. }
  14704. if (!isPartOfTextureArray) {
  14705. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14706. }
  14707. if (this._boundTexturesCache[channel] === internalTexture) {
  14708. this._moveBoundTextureOnTop(internalTexture);
  14709. if (!isPartOfTextureArray) {
  14710. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14711. }
  14712. return false;
  14713. }
  14714. this._activeChannel = channel;
  14715. if (internalTexture && internalTexture.is3D) {
  14716. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14717. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14718. internalTexture._cachedWrapU = texture.wrapU;
  14719. switch (texture.wrapU) {
  14720. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14721. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14722. break;
  14723. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14724. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14725. break;
  14726. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14727. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14728. break;
  14729. }
  14730. }
  14731. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14732. internalTexture._cachedWrapV = texture.wrapV;
  14733. switch (texture.wrapV) {
  14734. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14735. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14736. break;
  14737. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14738. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14739. break;
  14740. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14741. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14742. break;
  14743. }
  14744. }
  14745. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14746. internalTexture._cachedWrapR = texture.wrapR;
  14747. switch (texture.wrapR) {
  14748. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14749. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14750. break;
  14751. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14752. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14753. break;
  14754. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14755. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14756. break;
  14757. }
  14758. }
  14759. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14760. }
  14761. else if (internalTexture && internalTexture.isCube) {
  14762. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14763. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14764. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14765. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14766. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14767. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14768. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14769. }
  14770. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14771. }
  14772. else {
  14773. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14774. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14775. internalTexture._cachedWrapU = texture.wrapU;
  14776. switch (texture.wrapU) {
  14777. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14778. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14779. break;
  14780. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14781. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14782. break;
  14783. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14784. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14785. break;
  14786. }
  14787. }
  14788. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14789. internalTexture._cachedWrapV = texture.wrapV;
  14790. switch (texture.wrapV) {
  14791. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14792. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14793. break;
  14794. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14795. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14796. break;
  14797. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14798. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14799. break;
  14800. }
  14801. }
  14802. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14803. }
  14804. return true;
  14805. };
  14806. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14807. if (channel < 0 || !uniform) {
  14808. return;
  14809. }
  14810. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14811. this._textureUnits = new Int32Array(textures.length);
  14812. }
  14813. for (var i = 0; i < textures.length; i++) {
  14814. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14815. }
  14816. this._gl.uniform1iv(uniform, this._textureUnits);
  14817. for (var index = 0; index < textures.length; index++) {
  14818. this._setTexture(this._textureUnits[index], textures[index], true);
  14819. }
  14820. };
  14821. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14822. var internalTexture = texture.getInternalTexture();
  14823. if (!internalTexture) {
  14824. return;
  14825. }
  14826. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14827. var value = texture.anisotropicFilteringLevel;
  14828. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14829. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14830. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14831. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14832. }
  14833. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14834. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14835. internalTexture._cachedAnisotropicFilteringLevel = value;
  14836. }
  14837. };
  14838. Engine.prototype.readPixels = function (x, y, width, height) {
  14839. var data = new Uint8Array(height * width * 4);
  14840. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14841. return data;
  14842. };
  14843. /**
  14844. * Add an externaly attached data from its key.
  14845. * This method call will fail and return false, if such key already exists.
  14846. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14847. * @param key the unique key that identifies the data
  14848. * @param data the data object to associate to the key for this Engine instance
  14849. * @return true if no such key were already present and the data was added successfully, false otherwise
  14850. */
  14851. Engine.prototype.addExternalData = function (key, data) {
  14852. if (!this._externalData) {
  14853. this._externalData = new BABYLON.StringDictionary();
  14854. }
  14855. return this._externalData.add(key, data);
  14856. };
  14857. /**
  14858. * Get an externaly attached data from its key
  14859. * @param key the unique key that identifies the data
  14860. * @return the associated data, if present (can be null), or undefined if not present
  14861. */
  14862. Engine.prototype.getExternalData = function (key) {
  14863. if (!this._externalData) {
  14864. this._externalData = new BABYLON.StringDictionary();
  14865. }
  14866. return this._externalData.get(key);
  14867. };
  14868. /**
  14869. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14870. * @param key the unique key that identifies the data
  14871. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14872. * @return the associated data, can be null if the factory returned null.
  14873. */
  14874. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14875. if (!this._externalData) {
  14876. this._externalData = new BABYLON.StringDictionary();
  14877. }
  14878. return this._externalData.getOrAddWithFactory(key, factory);
  14879. };
  14880. /**
  14881. * Remove an externaly attached data from the Engine instance
  14882. * @param key the unique key that identifies the data
  14883. * @return true if the data was successfully removed, false if it doesn't exist
  14884. */
  14885. Engine.prototype.removeExternalData = function (key) {
  14886. if (!this._externalData) {
  14887. this._externalData = new BABYLON.StringDictionary();
  14888. }
  14889. return this._externalData.remove(key);
  14890. };
  14891. Engine.prototype.unbindAllAttributes = function () {
  14892. if (this._mustWipeVertexAttributes) {
  14893. this._mustWipeVertexAttributes = false;
  14894. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14895. this._gl.disableVertexAttribArray(i);
  14896. this._vertexAttribArraysEnabled[i] = false;
  14897. this._currentBufferPointers[i].active = false;
  14898. }
  14899. return;
  14900. }
  14901. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14902. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14903. continue;
  14904. }
  14905. this._gl.disableVertexAttribArray(i);
  14906. this._vertexAttribArraysEnabled[i] = false;
  14907. this._currentBufferPointers[i].active = false;
  14908. }
  14909. };
  14910. Engine.prototype.releaseEffects = function () {
  14911. for (var name in this._compiledEffects) {
  14912. this._deleteProgram(this._compiledEffects[name]._program);
  14913. }
  14914. this._compiledEffects = {};
  14915. };
  14916. // Dispose
  14917. Engine.prototype.dispose = function () {
  14918. this.hideLoadingUI();
  14919. this.stopRenderLoop();
  14920. // Release postProcesses
  14921. while (this.postProcesses.length) {
  14922. this.postProcesses[0].dispose();
  14923. }
  14924. // Empty texture
  14925. if (this._emptyTexture) {
  14926. this._releaseTexture(this._emptyTexture);
  14927. this._emptyTexture = null;
  14928. }
  14929. if (this._emptyCubeTexture) {
  14930. this._releaseTexture(this._emptyCubeTexture);
  14931. this._emptyCubeTexture = null;
  14932. }
  14933. // Rescale PP
  14934. if (this._rescalePostProcess) {
  14935. this._rescalePostProcess.dispose();
  14936. }
  14937. // Release scenes
  14938. while (this.scenes.length) {
  14939. this.scenes[0].dispose();
  14940. }
  14941. // Release audio engine
  14942. if (Engine.audioEngine) {
  14943. Engine.audioEngine.dispose();
  14944. }
  14945. // Release effects
  14946. this.releaseEffects();
  14947. // Unbind
  14948. this.unbindAllAttributes();
  14949. if (this._dummyFramebuffer) {
  14950. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14951. }
  14952. //WebVR
  14953. this.disableVR();
  14954. // Events
  14955. if (BABYLON.Tools.IsWindowObjectExist()) {
  14956. window.removeEventListener("blur", this._onBlur);
  14957. window.removeEventListener("focus", this._onFocus);
  14958. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14959. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14960. if (this._renderingCanvas) {
  14961. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14962. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14963. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  14964. if (!this._doNotHandleContextLost) {
  14965. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14966. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14967. }
  14968. }
  14969. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14970. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14971. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14972. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14973. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14974. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14975. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14976. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14977. if (this._onVrDisplayConnect) {
  14978. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14979. if (this._onVrDisplayDisconnect) {
  14980. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14981. }
  14982. if (this._onVrDisplayPresentChange) {
  14983. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14984. }
  14985. this._onVrDisplayConnect = null;
  14986. this._onVrDisplayDisconnect = null;
  14987. }
  14988. }
  14989. // Remove from Instances
  14990. var index = Engine.Instances.indexOf(this);
  14991. if (index >= 0) {
  14992. Engine.Instances.splice(index, 1);
  14993. }
  14994. this._workingCanvas = null;
  14995. this._workingContext = null;
  14996. this._currentBufferPointers = [];
  14997. this._renderingCanvas = null;
  14998. this._currentProgram = null;
  14999. this._bindedRenderFunction = null;
  15000. this.onResizeObservable.clear();
  15001. this.onCanvasBlurObservable.clear();
  15002. this.onCanvasFocusObservable.clear();
  15003. this.onCanvasPointerOutObservable.clear();
  15004. this.onBeginFrameObservable.clear();
  15005. this.onEndFrameObservable.clear();
  15006. BABYLON.Effect.ResetCache();
  15007. // Abort active requests
  15008. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  15009. var request = _a[_i];
  15010. request.abort();
  15011. }
  15012. };
  15013. // Loading screen
  15014. Engine.prototype.displayLoadingUI = function () {
  15015. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15016. return;
  15017. }
  15018. var loadingScreen = this.loadingScreen;
  15019. if (loadingScreen) {
  15020. loadingScreen.displayLoadingUI();
  15021. }
  15022. };
  15023. Engine.prototype.hideLoadingUI = function () {
  15024. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15025. return;
  15026. }
  15027. var loadingScreen = this.loadingScreen;
  15028. if (loadingScreen) {
  15029. loadingScreen.hideLoadingUI();
  15030. }
  15031. };
  15032. Object.defineProperty(Engine.prototype, "loadingScreen", {
  15033. get: function () {
  15034. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  15035. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  15036. return this._loadingScreen;
  15037. },
  15038. set: function (loadingScreen) {
  15039. this._loadingScreen = loadingScreen;
  15040. },
  15041. enumerable: true,
  15042. configurable: true
  15043. });
  15044. Object.defineProperty(Engine.prototype, "loadingUIText", {
  15045. set: function (text) {
  15046. this.loadingScreen.loadingUIText = text;
  15047. },
  15048. enumerable: true,
  15049. configurable: true
  15050. });
  15051. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  15052. set: function (color) {
  15053. this.loadingScreen.loadingUIBackgroundColor = color;
  15054. },
  15055. enumerable: true,
  15056. configurable: true
  15057. });
  15058. Engine.prototype.attachContextLostEvent = function (callback) {
  15059. if (this._renderingCanvas) {
  15060. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  15061. }
  15062. };
  15063. Engine.prototype.attachContextRestoredEvent = function (callback) {
  15064. if (this._renderingCanvas) {
  15065. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  15066. }
  15067. };
  15068. Engine.prototype.getVertexShaderSource = function (program) {
  15069. var shaders = this._gl.getAttachedShaders(program);
  15070. if (!shaders) {
  15071. return null;
  15072. }
  15073. return this._gl.getShaderSource(shaders[0]);
  15074. };
  15075. Engine.prototype.getFragmentShaderSource = function (program) {
  15076. var shaders = this._gl.getAttachedShaders(program);
  15077. if (!shaders) {
  15078. return null;
  15079. }
  15080. return this._gl.getShaderSource(shaders[1]);
  15081. };
  15082. Engine.prototype.getError = function () {
  15083. return this._gl.getError();
  15084. };
  15085. // FPS
  15086. Engine.prototype.getFps = function () {
  15087. return this._fps;
  15088. };
  15089. Engine.prototype.getDeltaTime = function () {
  15090. return this._deltaTime;
  15091. };
  15092. Engine.prototype._measureFps = function () {
  15093. this._performanceMonitor.sampleFrame();
  15094. this._fps = this._performanceMonitor.averageFPS;
  15095. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15096. };
  15097. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15098. if (faceIndex === void 0) { faceIndex = -1; }
  15099. var gl = this._gl;
  15100. if (!this._dummyFramebuffer) {
  15101. var dummy = gl.createFramebuffer();
  15102. if (!dummy) {
  15103. throw new Error("Unable to create dummy framebuffer");
  15104. }
  15105. this._dummyFramebuffer = dummy;
  15106. }
  15107. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15108. if (faceIndex > -1) {
  15109. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15110. }
  15111. else {
  15112. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15113. }
  15114. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15115. var buffer;
  15116. switch (readType) {
  15117. case gl.UNSIGNED_BYTE:
  15118. buffer = new Uint8Array(4 * width * height);
  15119. readType = gl.UNSIGNED_BYTE;
  15120. break;
  15121. default:
  15122. buffer = new Float32Array(4 * width * height);
  15123. readType = gl.FLOAT;
  15124. break;
  15125. }
  15126. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15127. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15128. return buffer;
  15129. };
  15130. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15131. if (this._webGLVersion > 1) {
  15132. return this._caps.colorBufferFloat;
  15133. }
  15134. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15135. };
  15136. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15137. if (this._webGLVersion > 1) {
  15138. return this._caps.colorBufferFloat;
  15139. }
  15140. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15141. };
  15142. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15143. Engine.prototype._canRenderToFramebuffer = function (type) {
  15144. var gl = this._gl;
  15145. //clear existing errors
  15146. while (gl.getError() !== gl.NO_ERROR) { }
  15147. var successful = true;
  15148. var texture = gl.createTexture();
  15149. gl.bindTexture(gl.TEXTURE_2D, texture);
  15150. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15151. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15152. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15153. var fb = gl.createFramebuffer();
  15154. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15155. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15156. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15157. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15158. successful = successful && (gl.getError() === gl.NO_ERROR);
  15159. //try render by clearing frame buffer's color buffer
  15160. if (successful) {
  15161. gl.clear(gl.COLOR_BUFFER_BIT);
  15162. successful = successful && (gl.getError() === gl.NO_ERROR);
  15163. }
  15164. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15165. if (successful) {
  15166. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15167. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15168. var readFormat = gl.RGBA;
  15169. var readType = gl.UNSIGNED_BYTE;
  15170. var buffer = new Uint8Array(4);
  15171. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15172. successful = successful && (gl.getError() === gl.NO_ERROR);
  15173. }
  15174. //clean up
  15175. gl.deleteTexture(texture);
  15176. gl.deleteFramebuffer(fb);
  15177. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15178. //clear accumulated errors
  15179. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15180. return successful;
  15181. };
  15182. Engine.prototype._getWebGLTextureType = function (type) {
  15183. if (type === Engine.TEXTURETYPE_FLOAT) {
  15184. return this._gl.FLOAT;
  15185. }
  15186. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15187. // Add Half Float Constant.
  15188. return this._gl.HALF_FLOAT_OES;
  15189. }
  15190. return this._gl.UNSIGNED_BYTE;
  15191. };
  15192. ;
  15193. Engine.prototype._getInternalFormat = function (format) {
  15194. var internalFormat = this._gl.RGBA;
  15195. switch (format) {
  15196. case Engine.TEXTUREFORMAT_ALPHA:
  15197. internalFormat = this._gl.ALPHA;
  15198. break;
  15199. case Engine.TEXTUREFORMAT_LUMINANCE:
  15200. internalFormat = this._gl.LUMINANCE;
  15201. break;
  15202. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  15203. internalFormat = this._gl.LUMINANCE_ALPHA;
  15204. break;
  15205. case Engine.TEXTUREFORMAT_RGB:
  15206. case Engine.TEXTUREFORMAT_RGB32F:
  15207. internalFormat = this._gl.RGB;
  15208. break;
  15209. case Engine.TEXTUREFORMAT_RGBA:
  15210. case Engine.TEXTUREFORMAT_RGBA32F:
  15211. internalFormat = this._gl.RGBA;
  15212. break;
  15213. case Engine.TEXTUREFORMAT_R32F:
  15214. internalFormat = this._gl.RED;
  15215. break;
  15216. case Engine.TEXTUREFORMAT_RG32F:
  15217. internalFormat = this._gl.RG;
  15218. break;
  15219. }
  15220. return internalFormat;
  15221. };
  15222. /** @ignore */
  15223. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15224. if (this._webGLVersion === 1) {
  15225. if (format) {
  15226. switch (format) {
  15227. case Engine.TEXTUREFORMAT_LUMINANCE:
  15228. return this._gl.LUMINANCE;
  15229. }
  15230. }
  15231. return this._gl.RGBA;
  15232. }
  15233. if (type === Engine.TEXTURETYPE_FLOAT) {
  15234. if (format) {
  15235. switch (format) {
  15236. case Engine.TEXTUREFORMAT_R32F:
  15237. return this._gl.R32F;
  15238. case Engine.TEXTUREFORMAT_RG32F:
  15239. return this._gl.RG32F;
  15240. case Engine.TEXTUREFORMAT_RGB32F:
  15241. return this._gl.RGB32F;
  15242. }
  15243. }
  15244. return this._gl.RGBA32F;
  15245. }
  15246. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15247. return this._gl.RGBA16F;
  15248. }
  15249. if (format) {
  15250. switch (format) {
  15251. case Engine.TEXTUREFORMAT_LUMINANCE:
  15252. return this._gl.LUMINANCE;
  15253. }
  15254. }
  15255. return this._gl.RGBA;
  15256. };
  15257. ;
  15258. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15259. if (type === Engine.TEXTURETYPE_FLOAT) {
  15260. return this._gl.RGBA32F;
  15261. }
  15262. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15263. return this._gl.RGBA16F;
  15264. }
  15265. return this._gl.RGBA8;
  15266. };
  15267. ;
  15268. Engine.prototype.createQuery = function () {
  15269. return this._gl.createQuery();
  15270. };
  15271. Engine.prototype.deleteQuery = function (query) {
  15272. this._gl.deleteQuery(query);
  15273. return this;
  15274. };
  15275. Engine.prototype.isQueryResultAvailable = function (query) {
  15276. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15277. };
  15278. Engine.prototype.getQueryResult = function (query) {
  15279. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15280. };
  15281. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15282. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15283. this._gl.beginQuery(glAlgorithm, query);
  15284. return this;
  15285. };
  15286. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15287. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15288. this._gl.endQuery(glAlgorithm);
  15289. return this;
  15290. };
  15291. /* Time queries */
  15292. Engine.prototype._createTimeQuery = function () {
  15293. var timerQuery = this._caps.timerQuery;
  15294. if (timerQuery.createQueryEXT) {
  15295. return timerQuery.createQueryEXT();
  15296. }
  15297. return this.createQuery();
  15298. };
  15299. Engine.prototype._deleteTimeQuery = function (query) {
  15300. var timerQuery = this._caps.timerQuery;
  15301. if (timerQuery.deleteQueryEXT) {
  15302. timerQuery.deleteQueryEXT(query);
  15303. return;
  15304. }
  15305. this.deleteQuery(query);
  15306. };
  15307. Engine.prototype._getTimeQueryResult = function (query) {
  15308. var timerQuery = this._caps.timerQuery;
  15309. if (timerQuery.getQueryObjectEXT) {
  15310. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15311. }
  15312. return this.getQueryResult(query);
  15313. };
  15314. Engine.prototype._getTimeQueryAvailability = function (query) {
  15315. var timerQuery = this._caps.timerQuery;
  15316. if (timerQuery.getQueryObjectEXT) {
  15317. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15318. }
  15319. return this.isQueryResultAvailable(query);
  15320. };
  15321. Engine.prototype.startTimeQuery = function () {
  15322. var timerQuery = this._caps.timerQuery;
  15323. if (!timerQuery) {
  15324. return null;
  15325. }
  15326. var token = new BABYLON._TimeToken();
  15327. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15328. if (this._caps.canUseTimestampForTimerQuery) {
  15329. token._startTimeQuery = this._createTimeQuery();
  15330. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15331. }
  15332. else {
  15333. if (this._currentNonTimestampToken) {
  15334. return this._currentNonTimestampToken;
  15335. }
  15336. token._timeElapsedQuery = this._createTimeQuery();
  15337. if (timerQuery.beginQueryEXT) {
  15338. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15339. }
  15340. else {
  15341. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15342. }
  15343. this._currentNonTimestampToken = token;
  15344. }
  15345. return token;
  15346. };
  15347. Engine.prototype.endTimeQuery = function (token) {
  15348. var timerQuery = this._caps.timerQuery;
  15349. if (!timerQuery || !token) {
  15350. return -1;
  15351. }
  15352. if (this._caps.canUseTimestampForTimerQuery) {
  15353. if (!token._startTimeQuery) {
  15354. return -1;
  15355. }
  15356. if (!token._endTimeQuery) {
  15357. token._endTimeQuery = this._createTimeQuery();
  15358. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15359. }
  15360. }
  15361. else if (!token._timeElapsedQueryEnded) {
  15362. if (!token._timeElapsedQuery) {
  15363. return -1;
  15364. }
  15365. if (timerQuery.endQueryEXT) {
  15366. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15367. }
  15368. else {
  15369. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15370. }
  15371. token._timeElapsedQueryEnded = true;
  15372. }
  15373. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15374. var available = false;
  15375. if (token._endTimeQuery) {
  15376. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15377. }
  15378. else if (token._timeElapsedQuery) {
  15379. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15380. }
  15381. if (available && !disjoint) {
  15382. var result = 0;
  15383. if (this._caps.canUseTimestampForTimerQuery) {
  15384. if (!token._startTimeQuery || !token._endTimeQuery) {
  15385. return -1;
  15386. }
  15387. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15388. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15389. result = timeEnd - timeStart;
  15390. this._deleteTimeQuery(token._startTimeQuery);
  15391. this._deleteTimeQuery(token._endTimeQuery);
  15392. token._startTimeQuery = null;
  15393. token._endTimeQuery = null;
  15394. }
  15395. else {
  15396. if (!token._timeElapsedQuery) {
  15397. return -1;
  15398. }
  15399. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15400. this._deleteTimeQuery(token._timeElapsedQuery);
  15401. token._timeElapsedQuery = null;
  15402. token._timeElapsedQueryEnded = false;
  15403. this._currentNonTimestampToken = null;
  15404. }
  15405. return result;
  15406. }
  15407. return -1;
  15408. };
  15409. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15410. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15411. };
  15412. // Transform feedback
  15413. Engine.prototype.createTransformFeedback = function () {
  15414. return this._gl.createTransformFeedback();
  15415. };
  15416. Engine.prototype.deleteTransformFeedback = function (value) {
  15417. this._gl.deleteTransformFeedback(value);
  15418. };
  15419. Engine.prototype.bindTransformFeedback = function (value) {
  15420. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15421. };
  15422. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15423. if (usePoints === void 0) { usePoints = true; }
  15424. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15425. };
  15426. Engine.prototype.endTransformFeedback = function () {
  15427. this._gl.endTransformFeedback();
  15428. };
  15429. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15430. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15431. };
  15432. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15433. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15434. };
  15435. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15436. var _this = this;
  15437. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15438. this._activeRequests.push(request);
  15439. request.onCompleteObservable.add(function (request) {
  15440. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15441. });
  15442. return request;
  15443. };
  15444. /** @ignore */
  15445. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15446. var _this = this;
  15447. return new Promise(function (resolve, reject) {
  15448. _this._loadFile(url, function (data) {
  15449. resolve(data);
  15450. }, undefined, database, useArrayBuffer, function (request, exception) {
  15451. reject(exception);
  15452. });
  15453. });
  15454. };
  15455. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15456. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15457. var onload = function (data) {
  15458. loadedFiles[index] = data;
  15459. loadedFiles._internalCount++;
  15460. if (loadedFiles._internalCount === 6) {
  15461. onfinish(loadedFiles);
  15462. }
  15463. };
  15464. var onerror = function (request, exception) {
  15465. if (onErrorCallBack && request) {
  15466. onErrorCallBack(request.status + " " + request.statusText, exception);
  15467. }
  15468. };
  15469. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15470. };
  15471. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15472. if (onError === void 0) { onError = null; }
  15473. var loadedFiles = [];
  15474. loadedFiles._internalCount = 0;
  15475. for (var index = 0; index < 6; index++) {
  15476. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15477. }
  15478. };
  15479. // Statics
  15480. Engine.isSupported = function () {
  15481. try {
  15482. var tempcanvas = document.createElement("canvas");
  15483. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15484. return gl != null && !!window.WebGLRenderingContext;
  15485. }
  15486. catch (e) {
  15487. return false;
  15488. }
  15489. };
  15490. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15491. Engine.ExceptionList = [
  15492. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15493. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15494. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15495. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15496. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15497. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15498. ];
  15499. Engine.Instances = new Array();
  15500. // Const statics
  15501. Engine._ALPHA_DISABLE = 0;
  15502. Engine._ALPHA_ADD = 1;
  15503. Engine._ALPHA_COMBINE = 2;
  15504. Engine._ALPHA_SUBTRACT = 3;
  15505. Engine._ALPHA_MULTIPLY = 4;
  15506. Engine._ALPHA_MAXIMIZED = 5;
  15507. Engine._ALPHA_ONEONE = 6;
  15508. Engine._ALPHA_PREMULTIPLIED = 7;
  15509. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15510. Engine._ALPHA_INTERPOLATE = 9;
  15511. Engine._ALPHA_SCREENMODE = 10;
  15512. Engine._DELAYLOADSTATE_NONE = 0;
  15513. Engine._DELAYLOADSTATE_LOADED = 1;
  15514. Engine._DELAYLOADSTATE_LOADING = 2;
  15515. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15516. Engine._TEXTUREFORMAT_ALPHA = 0;
  15517. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15518. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15519. Engine._TEXTUREFORMAT_RGB = 4;
  15520. Engine._TEXTUREFORMAT_RGBA = 5;
  15521. Engine._TEXTUREFORMAT_R32F = 6;
  15522. Engine._TEXTUREFORMAT_RG32F = 7;
  15523. Engine._TEXTUREFORMAT_RGB32F = 8;
  15524. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15525. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15526. Engine._TEXTURETYPE_FLOAT = 1;
  15527. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15528. // Depht or Stencil test Constants.
  15529. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15530. 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.
  15531. 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.
  15532. 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.
  15533. 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.
  15534. 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.
  15535. 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.
  15536. 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.
  15537. // Stencil Actions Constants.
  15538. Engine._KEEP = 0x1E00;
  15539. Engine._REPLACE = 0x1E01;
  15540. Engine._INCR = 0x1E02;
  15541. Engine._DECR = 0x1E03;
  15542. Engine._INVERT = 0x150A;
  15543. Engine._INCR_WRAP = 0x8507;
  15544. Engine._DECR_WRAP = 0x8508;
  15545. // Texture rescaling mode
  15546. Engine._SCALEMODE_FLOOR = 1;
  15547. Engine._SCALEMODE_NEAREST = 2;
  15548. Engine._SCALEMODE_CEILING = 3;
  15549. // Updatable statics so stick with vars here
  15550. Engine.CollisionsEpsilon = 0.001;
  15551. Engine.CodeRepository = "src/";
  15552. Engine.ShadersRepository = "src/Shaders/";
  15553. return Engine;
  15554. }());
  15555. BABYLON.Engine = Engine;
  15556. })(BABYLON || (BABYLON = {}));
  15557. //# sourceMappingURL=babylon.engine.js.map
  15558. var BABYLON;
  15559. (function (BABYLON) {
  15560. /**
  15561. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15562. */
  15563. var Node = /** @class */ (function () {
  15564. /**
  15565. * Creates a new Node
  15566. * @param {string} name - the name and id to be given to this node
  15567. * @param {BABYLON.Scene} the scene this node will be added to
  15568. */
  15569. function Node(name, scene) {
  15570. if (scene === void 0) { scene = null; }
  15571. /**
  15572. * Gets or sets a string used to store user defined state for the node
  15573. */
  15574. this.state = "";
  15575. /**
  15576. * Gets or sets an object used to store user defined information for the node
  15577. */
  15578. this.metadata = null;
  15579. /**
  15580. * Gets or sets a boolean used to define if the node must be serialized
  15581. */
  15582. this.doNotSerialize = false;
  15583. /** @ignore */
  15584. this._isDisposed = false;
  15585. /**
  15586. * Gets a list of {BABYLON.Animation} associated with the node
  15587. */
  15588. this.animations = new Array();
  15589. this._ranges = {};
  15590. this._isEnabled = true;
  15591. this._isReady = true;
  15592. /** @ignore */
  15593. this._currentRenderId = -1;
  15594. this._parentRenderId = -1;
  15595. this._animationPropertiesOverride = null;
  15596. /**
  15597. * An event triggered when the mesh is disposed
  15598. * @type {BABYLON.Observable}
  15599. */
  15600. this.onDisposeObservable = new BABYLON.Observable();
  15601. // Behaviors
  15602. this._behaviors = new Array();
  15603. this.name = name;
  15604. this.id = name;
  15605. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15606. this.uniqueId = this._scene.getUniqueId();
  15607. this._initCache();
  15608. }
  15609. /**
  15610. * Gets a boolean indicating if the node has been disposed
  15611. * @returns true if the node was disposed
  15612. */
  15613. Node.prototype.isDisposed = function () {
  15614. return this._isDisposed;
  15615. };
  15616. Object.defineProperty(Node.prototype, "parent", {
  15617. get: function () {
  15618. return this._parentNode;
  15619. },
  15620. /**
  15621. * Gets or sets the parent of the node
  15622. */
  15623. set: function (parent) {
  15624. if (this._parentNode === parent) {
  15625. return;
  15626. }
  15627. // Remove self from list of children of parent
  15628. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15629. var index = this._parentNode._children.indexOf(this);
  15630. if (index !== -1) {
  15631. this._parentNode._children.splice(index, 1);
  15632. }
  15633. }
  15634. // Store new parent
  15635. this._parentNode = parent;
  15636. // Add as child to new parent
  15637. if (this._parentNode) {
  15638. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15639. this._parentNode._children = new Array();
  15640. }
  15641. this._parentNode._children.push(this);
  15642. }
  15643. },
  15644. enumerable: true,
  15645. configurable: true
  15646. });
  15647. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15648. /**
  15649. * Gets or sets the animation properties override
  15650. */
  15651. get: function () {
  15652. return this._animationPropertiesOverride;
  15653. },
  15654. set: function (value) {
  15655. this._animationPropertiesOverride = value;
  15656. },
  15657. enumerable: true,
  15658. configurable: true
  15659. });
  15660. /**
  15661. * Gets a string idenfifying the name of the class
  15662. * @returns "Node" string
  15663. */
  15664. Node.prototype.getClassName = function () {
  15665. return "Node";
  15666. };
  15667. Object.defineProperty(Node.prototype, "onDispose", {
  15668. /**
  15669. * Sets a callback that will be raised when the node will be disposed
  15670. */
  15671. set: function (callback) {
  15672. if (this._onDisposeObserver) {
  15673. this.onDisposeObservable.remove(this._onDisposeObserver);
  15674. }
  15675. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15676. },
  15677. enumerable: true,
  15678. configurable: true
  15679. });
  15680. /**
  15681. * Gets the scene of the node
  15682. * @returns a {BABYLON.Scene}
  15683. */
  15684. Node.prototype.getScene = function () {
  15685. return this._scene;
  15686. };
  15687. /**
  15688. * Gets the engine of the node
  15689. * @returns a {BABYLON.Engine}
  15690. */
  15691. Node.prototype.getEngine = function () {
  15692. return this._scene.getEngine();
  15693. };
  15694. /**
  15695. * Attach a behavior to the node
  15696. * @see http://doc.babylonjs.com/features/behaviour
  15697. * @param behavior defines the behavior to attach
  15698. * @returns the current Node
  15699. */
  15700. Node.prototype.addBehavior = function (behavior) {
  15701. var _this = this;
  15702. var index = this._behaviors.indexOf(behavior);
  15703. if (index !== -1) {
  15704. return this;
  15705. }
  15706. behavior.init();
  15707. if (this._scene.isLoading) {
  15708. // We defer the attach when the scene will be loaded
  15709. var observer = this._scene.onDataLoadedObservable.add(function () {
  15710. behavior.attach(_this);
  15711. setTimeout(function () {
  15712. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15713. _this._scene.onDataLoadedObservable.remove(observer);
  15714. }, 0);
  15715. });
  15716. }
  15717. else {
  15718. behavior.attach(this);
  15719. }
  15720. this._behaviors.push(behavior);
  15721. return this;
  15722. };
  15723. /**
  15724. * Remove an attached behavior
  15725. * @see http://doc.babylonjs.com/features/behaviour
  15726. * @param behavior defines the behavior to attach
  15727. * @returns the current Node
  15728. */
  15729. Node.prototype.removeBehavior = function (behavior) {
  15730. var index = this._behaviors.indexOf(behavior);
  15731. if (index === -1) {
  15732. return this;
  15733. }
  15734. this._behaviors[index].detach();
  15735. this._behaviors.splice(index, 1);
  15736. return this;
  15737. };
  15738. Object.defineProperty(Node.prototype, "behaviors", {
  15739. /**
  15740. * Gets the list of attached behaviors
  15741. * @see http://doc.babylonjs.com/features/behaviour
  15742. */
  15743. get: function () {
  15744. return this._behaviors;
  15745. },
  15746. enumerable: true,
  15747. configurable: true
  15748. });
  15749. /**
  15750. * Gets an attached behavior by name
  15751. * @param name defines the name of the behavior to look for
  15752. * @see http://doc.babylonjs.com/features/behaviour
  15753. * @returns null if behavior was not found else the requested behavior
  15754. */
  15755. Node.prototype.getBehaviorByName = function (name) {
  15756. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15757. var behavior = _a[_i];
  15758. if (behavior.name === name) {
  15759. return behavior;
  15760. }
  15761. }
  15762. return null;
  15763. };
  15764. /**
  15765. * Returns the world matrix of the node
  15766. * @returns a matrix containing the node's world matrix
  15767. */
  15768. Node.prototype.getWorldMatrix = function () {
  15769. return BABYLON.Matrix.Identity();
  15770. };
  15771. // override it in derived class if you add new variables to the cache
  15772. // and call the parent class method
  15773. /** @ignore */
  15774. Node.prototype._initCache = function () {
  15775. this._cache = {};
  15776. this._cache.parent = undefined;
  15777. };
  15778. /** @ignore */
  15779. Node.prototype.updateCache = function (force) {
  15780. if (!force && this.isSynchronized())
  15781. return;
  15782. this._cache.parent = this.parent;
  15783. this._updateCache();
  15784. };
  15785. // override it in derived class if you add new variables to the cache
  15786. // and call the parent class method if !ignoreParentClass
  15787. /** @ignore */
  15788. Node.prototype._updateCache = function (ignoreParentClass) {
  15789. };
  15790. // override it in derived class if you add new variables to the cache
  15791. /** @ignore */
  15792. Node.prototype._isSynchronized = function () {
  15793. return true;
  15794. };
  15795. /** @ignore */
  15796. Node.prototype._markSyncedWithParent = function () {
  15797. if (this.parent) {
  15798. this._parentRenderId = this.parent._currentRenderId;
  15799. }
  15800. };
  15801. /** @ignore */
  15802. Node.prototype.isSynchronizedWithParent = function () {
  15803. if (!this.parent) {
  15804. return true;
  15805. }
  15806. if (this._parentRenderId !== this.parent._currentRenderId) {
  15807. return false;
  15808. }
  15809. return this.parent.isSynchronized();
  15810. };
  15811. /** @ignore */
  15812. Node.prototype.isSynchronized = function (updateCache) {
  15813. var check = this.hasNewParent();
  15814. check = check || !this.isSynchronizedWithParent();
  15815. check = check || !this._isSynchronized();
  15816. if (updateCache)
  15817. this.updateCache(true);
  15818. return !check;
  15819. };
  15820. /** @ignore */
  15821. Node.prototype.hasNewParent = function (update) {
  15822. if (this._cache.parent === this.parent)
  15823. return false;
  15824. if (update)
  15825. this._cache.parent = this.parent;
  15826. return true;
  15827. };
  15828. /**
  15829. * Is this node ready to be used/rendered
  15830. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15831. * @return true if the node is ready
  15832. */
  15833. Node.prototype.isReady = function (completeCheck) {
  15834. if (completeCheck === void 0) { completeCheck = false; }
  15835. return this._isReady;
  15836. };
  15837. /**
  15838. * Is this node enabled?
  15839. * 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
  15840. * @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
  15841. * @return whether this node (and its parent) is enabled
  15842. * @see setEnabled
  15843. */
  15844. Node.prototype.isEnabled = function (checkAncestors) {
  15845. if (checkAncestors === void 0) { checkAncestors = true; }
  15846. if (checkAncestors === false) {
  15847. return this._isEnabled;
  15848. }
  15849. if (this._isEnabled === false) {
  15850. return false;
  15851. }
  15852. if (this.parent !== undefined && this.parent !== null) {
  15853. return this.parent.isEnabled(checkAncestors);
  15854. }
  15855. return true;
  15856. };
  15857. /**
  15858. * Set the enabled state of this node
  15859. * @param value defines the new enabled state
  15860. * @see isEnabled
  15861. */
  15862. Node.prototype.setEnabled = function (value) {
  15863. this._isEnabled = value;
  15864. };
  15865. /**
  15866. * Is this node a descendant of the given node?
  15867. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15868. * @param ancestor defines the parent node to inspect
  15869. * @see parent
  15870. * @returns a boolean indicating if this node is a descendant of the given node
  15871. */
  15872. Node.prototype.isDescendantOf = function (ancestor) {
  15873. if (this.parent) {
  15874. if (this.parent === ancestor) {
  15875. return true;
  15876. }
  15877. return this.parent.isDescendantOf(ancestor);
  15878. }
  15879. return false;
  15880. };
  15881. /** @ignore */
  15882. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15883. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15884. if (!this._children) {
  15885. return;
  15886. }
  15887. for (var index = 0; index < this._children.length; index++) {
  15888. var item = this._children[index];
  15889. if (!predicate || predicate(item)) {
  15890. results.push(item);
  15891. }
  15892. if (!directDescendantsOnly) {
  15893. item._getDescendants(results, false, predicate);
  15894. }
  15895. }
  15896. };
  15897. /**
  15898. * Will return all nodes that have this node as ascendant
  15899. * @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
  15900. * @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
  15901. * @return all children nodes of all types
  15902. */
  15903. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15904. var results = new Array();
  15905. this._getDescendants(results, directDescendantsOnly, predicate);
  15906. return results;
  15907. };
  15908. /**
  15909. * Get all child-meshes of this node
  15910. * @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
  15911. * @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
  15912. * @returns an array of {BABYLON.AbstractMesh}
  15913. */
  15914. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15915. var results = [];
  15916. this._getDescendants(results, directDescendantsOnly, function (node) {
  15917. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15918. });
  15919. return results;
  15920. };
  15921. /**
  15922. * Get all child-transformNodes of this node
  15923. * @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
  15924. * @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
  15925. * @returns an array of {BABYLON.TransformNode}
  15926. */
  15927. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15928. var results = [];
  15929. this._getDescendants(results, directDescendantsOnly, function (node) {
  15930. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15931. });
  15932. return results;
  15933. };
  15934. /**
  15935. * Get all direct children of this node
  15936. * @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
  15937. * @returns an array of {BABYLON.Node}
  15938. */
  15939. Node.prototype.getChildren = function (predicate) {
  15940. return this.getDescendants(true, predicate);
  15941. };
  15942. /** @ignore */
  15943. Node.prototype._setReady = function (state) {
  15944. if (state === this._isReady) {
  15945. return;
  15946. }
  15947. if (!state) {
  15948. this._isReady = false;
  15949. return;
  15950. }
  15951. this._isReady = true;
  15952. if (this.onReady) {
  15953. this.onReady(this);
  15954. }
  15955. };
  15956. /**
  15957. * Get an animation by name
  15958. * @param name defines the name of the animation to look for
  15959. * @returns null if not found else the requested animation
  15960. */
  15961. Node.prototype.getAnimationByName = function (name) {
  15962. for (var i = 0; i < this.animations.length; i++) {
  15963. var animation = this.animations[i];
  15964. if (animation.name === name) {
  15965. return animation;
  15966. }
  15967. }
  15968. return null;
  15969. };
  15970. /**
  15971. * Creates an animation range for this node
  15972. * @param name defines the name of the range
  15973. * @param from defines the starting key
  15974. * @param to defines the end key
  15975. */
  15976. Node.prototype.createAnimationRange = function (name, from, to) {
  15977. // check name not already in use
  15978. if (!this._ranges[name]) {
  15979. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15980. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15981. if (this.animations[i]) {
  15982. this.animations[i].createRange(name, from, to);
  15983. }
  15984. }
  15985. }
  15986. };
  15987. /**
  15988. * Delete a specific animation range
  15989. * @param name defines the name of the range to delete
  15990. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15991. */
  15992. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15993. if (deleteFrames === void 0) { deleteFrames = true; }
  15994. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15995. if (this.animations[i]) {
  15996. this.animations[i].deleteRange(name, deleteFrames);
  15997. }
  15998. }
  15999. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  16000. };
  16001. /**
  16002. * Get an animation range by name
  16003. * @param name defines the name of the animation range to look for
  16004. * @returns null if not found else the requested animation range
  16005. */
  16006. Node.prototype.getAnimationRange = function (name) {
  16007. return this._ranges[name];
  16008. };
  16009. /**
  16010. * Will start the animation sequence
  16011. * @param name defines the range frames for animation sequence
  16012. * @param loop defines if the animation should loop (false by default)
  16013. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  16014. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  16015. * @returns the object created for this animation. If range does not exist, it will return null
  16016. */
  16017. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  16018. var range = this.getAnimationRange(name);
  16019. if (!range) {
  16020. return null;
  16021. }
  16022. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  16023. };
  16024. /**
  16025. * Serialize animation ranges into a JSON compatible object
  16026. * @returns serialization object
  16027. */
  16028. Node.prototype.serializeAnimationRanges = function () {
  16029. var serializationRanges = [];
  16030. for (var name in this._ranges) {
  16031. var localRange = this._ranges[name];
  16032. if (!localRange) {
  16033. continue;
  16034. }
  16035. var range = {};
  16036. range.name = name;
  16037. range.from = localRange.from;
  16038. range.to = localRange.to;
  16039. serializationRanges.push(range);
  16040. }
  16041. return serializationRanges;
  16042. };
  16043. /**
  16044. * Computes the world matrix of the node
  16045. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  16046. * @returns the world matrix
  16047. */
  16048. Node.prototype.computeWorldMatrix = function (force) {
  16049. return BABYLON.Matrix.Identity();
  16050. };
  16051. /**
  16052. * Releases resources associated with this node.
  16053. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  16054. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  16055. */
  16056. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16057. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16058. if (!doNotRecurse) {
  16059. var nodes = this.getDescendants(true);
  16060. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  16061. var node = nodes_1[_i];
  16062. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  16063. }
  16064. }
  16065. else {
  16066. var transformNodes = this.getChildTransformNodes(true);
  16067. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  16068. var transformNode = transformNodes_1[_a];
  16069. transformNode.parent = null;
  16070. transformNode.computeWorldMatrix(true);
  16071. }
  16072. }
  16073. this.parent = null;
  16074. // Callback
  16075. this.onDisposeObservable.notifyObservers(this);
  16076. this.onDisposeObservable.clear();
  16077. // Behaviors
  16078. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  16079. var behavior = _c[_b];
  16080. behavior.detach();
  16081. }
  16082. this._behaviors = [];
  16083. this._isDisposed = true;
  16084. };
  16085. /**
  16086. * Parse animation range data from a serialization object and store them into a given node
  16087. * @param node defines where to store the animation ranges
  16088. * @param parsedNode defines the serialization object to read data from
  16089. * @param scene defines the hosting scene
  16090. */
  16091. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  16092. if (parsedNode.ranges) {
  16093. for (var index = 0; index < parsedNode.ranges.length; index++) {
  16094. var data = parsedNode.ranges[index];
  16095. node.createAnimationRange(data.name, data.from, data.to);
  16096. }
  16097. }
  16098. };
  16099. __decorate([
  16100. BABYLON.serialize()
  16101. ], Node.prototype, "name", void 0);
  16102. __decorate([
  16103. BABYLON.serialize()
  16104. ], Node.prototype, "id", void 0);
  16105. __decorate([
  16106. BABYLON.serialize()
  16107. ], Node.prototype, "uniqueId", void 0);
  16108. __decorate([
  16109. BABYLON.serialize()
  16110. ], Node.prototype, "state", void 0);
  16111. __decorate([
  16112. BABYLON.serialize()
  16113. ], Node.prototype, "metadata", void 0);
  16114. return Node;
  16115. }());
  16116. BABYLON.Node = Node;
  16117. })(BABYLON || (BABYLON = {}));
  16118. //# sourceMappingURL=babylon.node.js.map
  16119. var BABYLON;
  16120. (function (BABYLON) {
  16121. var BoundingSphere = /** @class */ (function () {
  16122. function BoundingSphere(minimum, maximum) {
  16123. this.minimum = minimum;
  16124. this.maximum = maximum;
  16125. this._tempRadiusVector = BABYLON.Vector3.Zero();
  16126. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  16127. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  16128. this.radius = distance * 0.5;
  16129. this.centerWorld = BABYLON.Vector3.Zero();
  16130. this._update(BABYLON.Matrix.Identity());
  16131. }
  16132. // Methods
  16133. BoundingSphere.prototype._update = function (world) {
  16134. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  16135. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  16136. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  16137. };
  16138. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  16139. for (var i = 0; i < 6; i++) {
  16140. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  16141. return false;
  16142. }
  16143. return true;
  16144. };
  16145. BoundingSphere.prototype.intersectsPoint = function (point) {
  16146. var x = this.centerWorld.x - point.x;
  16147. var y = this.centerWorld.y - point.y;
  16148. var z = this.centerWorld.z - point.z;
  16149. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16150. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16151. return false;
  16152. return true;
  16153. };
  16154. // Statics
  16155. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16156. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16157. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16158. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16159. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16160. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16161. return false;
  16162. return true;
  16163. };
  16164. return BoundingSphere;
  16165. }());
  16166. BABYLON.BoundingSphere = BoundingSphere;
  16167. })(BABYLON || (BABYLON = {}));
  16168. //# sourceMappingURL=babylon.boundingSphere.js.map
  16169. var BABYLON;
  16170. (function (BABYLON) {
  16171. var BoundingBox = /** @class */ (function () {
  16172. function BoundingBox(minimum, maximum) {
  16173. this.minimum = minimum;
  16174. this.maximum = maximum;
  16175. this.vectors = new Array();
  16176. this.vectorsWorld = new Array();
  16177. // Bounding vectors
  16178. this.vectors.push(this.minimum.clone());
  16179. this.vectors.push(this.maximum.clone());
  16180. this.vectors.push(this.minimum.clone());
  16181. this.vectors[2].x = this.maximum.x;
  16182. this.vectors.push(this.minimum.clone());
  16183. this.vectors[3].y = this.maximum.y;
  16184. this.vectors.push(this.minimum.clone());
  16185. this.vectors[4].z = this.maximum.z;
  16186. this.vectors.push(this.maximum.clone());
  16187. this.vectors[5].z = this.minimum.z;
  16188. this.vectors.push(this.maximum.clone());
  16189. this.vectors[6].x = this.minimum.x;
  16190. this.vectors.push(this.maximum.clone());
  16191. this.vectors[7].y = this.minimum.y;
  16192. // OBB
  16193. this.center = this.maximum.add(this.minimum).scale(0.5);
  16194. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16195. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16196. // World
  16197. for (var index = 0; index < this.vectors.length; index++) {
  16198. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16199. }
  16200. this.minimumWorld = BABYLON.Vector3.Zero();
  16201. this.maximumWorld = BABYLON.Vector3.Zero();
  16202. this.centerWorld = BABYLON.Vector3.Zero();
  16203. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16204. this._update(BABYLON.Matrix.Identity());
  16205. }
  16206. // Methods
  16207. BoundingBox.prototype.getWorldMatrix = function () {
  16208. return this._worldMatrix;
  16209. };
  16210. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16211. this._worldMatrix.copyFrom(matrix);
  16212. return this;
  16213. };
  16214. BoundingBox.prototype._update = function (world) {
  16215. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16216. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16217. for (var index = 0; index < this.vectors.length; index++) {
  16218. var v = this.vectorsWorld[index];
  16219. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16220. if (v.x < this.minimumWorld.x)
  16221. this.minimumWorld.x = v.x;
  16222. if (v.y < this.minimumWorld.y)
  16223. this.minimumWorld.y = v.y;
  16224. if (v.z < this.minimumWorld.z)
  16225. this.minimumWorld.z = v.z;
  16226. if (v.x > this.maximumWorld.x)
  16227. this.maximumWorld.x = v.x;
  16228. if (v.y > this.maximumWorld.y)
  16229. this.maximumWorld.y = v.y;
  16230. if (v.z > this.maximumWorld.z)
  16231. this.maximumWorld.z = v.z;
  16232. }
  16233. // Extend
  16234. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16235. this.extendSizeWorld.scaleInPlace(0.5);
  16236. // OBB
  16237. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16238. this.centerWorld.scaleInPlace(0.5);
  16239. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16240. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16241. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16242. this._worldMatrix = world;
  16243. };
  16244. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16245. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16246. };
  16247. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16248. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16249. };
  16250. BoundingBox.prototype.intersectsPoint = function (point) {
  16251. var delta = -BABYLON.Epsilon;
  16252. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16253. return false;
  16254. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16255. return false;
  16256. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16257. return false;
  16258. return true;
  16259. };
  16260. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16261. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16262. };
  16263. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16264. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16265. return false;
  16266. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16267. return false;
  16268. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16269. return false;
  16270. return true;
  16271. };
  16272. // Statics
  16273. BoundingBox.Intersects = function (box0, box1) {
  16274. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16275. return false;
  16276. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16277. return false;
  16278. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16279. return false;
  16280. return true;
  16281. };
  16282. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16283. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16284. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16285. return (num <= (sphereRadius * sphereRadius));
  16286. };
  16287. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16288. for (var p = 0; p < 6; p++) {
  16289. for (var i = 0; i < 8; i++) {
  16290. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16291. return false;
  16292. }
  16293. }
  16294. }
  16295. return true;
  16296. };
  16297. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16298. for (var p = 0; p < 6; p++) {
  16299. var inCount = 8;
  16300. for (var i = 0; i < 8; i++) {
  16301. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16302. --inCount;
  16303. }
  16304. else {
  16305. break;
  16306. }
  16307. }
  16308. if (inCount === 0)
  16309. return false;
  16310. }
  16311. return true;
  16312. };
  16313. return BoundingBox;
  16314. }());
  16315. BABYLON.BoundingBox = BoundingBox;
  16316. })(BABYLON || (BABYLON = {}));
  16317. //# sourceMappingURL=babylon.boundingBox.js.map
  16318. var BABYLON;
  16319. (function (BABYLON) {
  16320. var computeBoxExtents = function (axis, box) {
  16321. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16322. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16323. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16324. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16325. var r = r0 + r1 + r2;
  16326. return {
  16327. min: p - r,
  16328. max: p + r
  16329. };
  16330. };
  16331. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16332. var axisOverlap = function (axis, box0, box1) {
  16333. var result0 = computeBoxExtents(axis, box0);
  16334. var result1 = computeBoxExtents(axis, box1);
  16335. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16336. };
  16337. var BoundingInfo = /** @class */ (function () {
  16338. function BoundingInfo(minimum, maximum) {
  16339. this.minimum = minimum;
  16340. this.maximum = maximum;
  16341. this._isLocked = false;
  16342. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16343. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16344. }
  16345. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16346. get: function () {
  16347. return this._isLocked;
  16348. },
  16349. set: function (value) {
  16350. this._isLocked = value;
  16351. },
  16352. enumerable: true,
  16353. configurable: true
  16354. });
  16355. // Methods
  16356. BoundingInfo.prototype.update = function (world) {
  16357. if (this._isLocked) {
  16358. return;
  16359. }
  16360. this.boundingBox._update(world);
  16361. this.boundingSphere._update(world);
  16362. };
  16363. /**
  16364. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16365. * @param center New center of the bounding info
  16366. * @param extend New extend of the bounding info
  16367. */
  16368. BoundingInfo.prototype.centerOn = function (center, extend) {
  16369. this.minimum = center.subtract(extend);
  16370. this.maximum = center.add(extend);
  16371. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16372. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16373. return this;
  16374. };
  16375. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16376. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16377. return false;
  16378. return this.boundingBox.isInFrustum(frustumPlanes);
  16379. };
  16380. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16381. /**
  16382. * Gets the world distance between the min and max points of the bounding box
  16383. */
  16384. get: function () {
  16385. var boundingBox = this.boundingBox;
  16386. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16387. return size.length();
  16388. },
  16389. enumerable: true,
  16390. configurable: true
  16391. });
  16392. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16393. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16394. };
  16395. BoundingInfo.prototype._checkCollision = function (collider) {
  16396. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16397. };
  16398. BoundingInfo.prototype.intersectsPoint = function (point) {
  16399. if (!this.boundingSphere.centerWorld) {
  16400. return false;
  16401. }
  16402. if (!this.boundingSphere.intersectsPoint(point)) {
  16403. return false;
  16404. }
  16405. if (!this.boundingBox.intersectsPoint(point)) {
  16406. return false;
  16407. }
  16408. return true;
  16409. };
  16410. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16411. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16412. return false;
  16413. }
  16414. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16415. return false;
  16416. }
  16417. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16418. return false;
  16419. }
  16420. if (!precise) {
  16421. return true;
  16422. }
  16423. var box0 = this.boundingBox;
  16424. var box1 = boundingInfo.boundingBox;
  16425. if (!axisOverlap(box0.directions[0], box0, box1))
  16426. return false;
  16427. if (!axisOverlap(box0.directions[1], box0, box1))
  16428. return false;
  16429. if (!axisOverlap(box0.directions[2], box0, box1))
  16430. return false;
  16431. if (!axisOverlap(box1.directions[0], box0, box1))
  16432. return false;
  16433. if (!axisOverlap(box1.directions[1], box0, box1))
  16434. return false;
  16435. if (!axisOverlap(box1.directions[2], box0, box1))
  16436. return false;
  16437. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16438. return false;
  16439. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16440. return false;
  16441. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16442. return false;
  16443. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16444. return false;
  16445. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16446. return false;
  16447. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16448. return false;
  16449. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16450. return false;
  16451. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16452. return false;
  16453. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16454. return false;
  16455. return true;
  16456. };
  16457. return BoundingInfo;
  16458. }());
  16459. BABYLON.BoundingInfo = BoundingInfo;
  16460. })(BABYLON || (BABYLON = {}));
  16461. //# sourceMappingURL=babylon.boundingInfo.js.map
  16462. var BABYLON;
  16463. (function (BABYLON) {
  16464. var TransformNode = /** @class */ (function (_super) {
  16465. __extends(TransformNode, _super);
  16466. function TransformNode(name, scene, isPure) {
  16467. if (scene === void 0) { scene = null; }
  16468. if (isPure === void 0) { isPure = true; }
  16469. var _this = _super.call(this, name, scene) || this;
  16470. // Properties
  16471. _this._rotation = BABYLON.Vector3.Zero();
  16472. _this._scaling = BABYLON.Vector3.One();
  16473. _this._isDirty = false;
  16474. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16475. _this.scalingDeterminant = 1;
  16476. _this.infiniteDistance = false;
  16477. _this.position = BABYLON.Vector3.Zero();
  16478. _this._localWorld = BABYLON.Matrix.Zero();
  16479. _this._worldMatrix = BABYLON.Matrix.Zero();
  16480. _this._worldMatrixDeterminant = 0;
  16481. _this._absolutePosition = BABYLON.Vector3.Zero();
  16482. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16483. _this._postMultiplyPivotMatrix = false;
  16484. _this._isWorldMatrixFrozen = false;
  16485. /**
  16486. * An event triggered after the world matrix is updated
  16487. * @type {BABYLON.Observable}
  16488. */
  16489. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16490. _this._nonUniformScaling = false;
  16491. if (isPure) {
  16492. _this.getScene().addTransformNode(_this);
  16493. }
  16494. return _this;
  16495. }
  16496. /**
  16497. * Gets a string idenfifying the name of the class
  16498. * @returns "TransformNode" string
  16499. */
  16500. TransformNode.prototype.getClassName = function () {
  16501. return "TransformNode";
  16502. };
  16503. Object.defineProperty(TransformNode.prototype, "rotation", {
  16504. /**
  16505. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16506. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16507. * Default : (0.0, 0.0, 0.0)
  16508. */
  16509. get: function () {
  16510. return this._rotation;
  16511. },
  16512. set: function (newRotation) {
  16513. this._rotation = newRotation;
  16514. },
  16515. enumerable: true,
  16516. configurable: true
  16517. });
  16518. Object.defineProperty(TransformNode.prototype, "scaling", {
  16519. /**
  16520. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16521. * Default : (1.0, 1.0, 1.0)
  16522. */
  16523. get: function () {
  16524. return this._scaling;
  16525. },
  16526. /**
  16527. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16528. * Default : (1.0, 1.0, 1.0)
  16529. */
  16530. set: function (newScaling) {
  16531. this._scaling = newScaling;
  16532. },
  16533. enumerable: true,
  16534. configurable: true
  16535. });
  16536. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16537. /**
  16538. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16539. * It's null by default.
  16540. * 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)
  16541. */
  16542. get: function () {
  16543. return this._rotationQuaternion;
  16544. },
  16545. set: function (quaternion) {
  16546. this._rotationQuaternion = quaternion;
  16547. //reset the rotation vector.
  16548. if (quaternion && this.rotation.length()) {
  16549. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16550. }
  16551. },
  16552. enumerable: true,
  16553. configurable: true
  16554. });
  16555. /**
  16556. * Returns the latest update of the World matrix
  16557. * Returns a Matrix.
  16558. */
  16559. TransformNode.prototype.getWorldMatrix = function () {
  16560. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16561. this.computeWorldMatrix();
  16562. }
  16563. return this._worldMatrix;
  16564. };
  16565. /**
  16566. * Returns the latest update of the World matrix determinant.
  16567. */
  16568. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16569. return this._worldMatrixDeterminant;
  16570. };
  16571. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16572. /**
  16573. * Returns directly the latest state of the mesh World matrix.
  16574. * A Matrix is returned.
  16575. */
  16576. get: function () {
  16577. return this._worldMatrix;
  16578. },
  16579. enumerable: true,
  16580. configurable: true
  16581. });
  16582. /**
  16583. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16584. * Returns the AbstractMesh.
  16585. */
  16586. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16587. this._poseMatrix.copyFrom(matrix);
  16588. return this;
  16589. };
  16590. /**
  16591. * Returns the mesh Pose matrix.
  16592. * Returned object : Matrix
  16593. */
  16594. TransformNode.prototype.getPoseMatrix = function () {
  16595. return this._poseMatrix;
  16596. };
  16597. TransformNode.prototype._isSynchronized = function () {
  16598. if (this._isDirty) {
  16599. return false;
  16600. }
  16601. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16602. return false;
  16603. if (this._cache.pivotMatrixUpdated) {
  16604. return false;
  16605. }
  16606. if (this.infiniteDistance) {
  16607. return false;
  16608. }
  16609. if (!this._cache.position.equals(this.position))
  16610. return false;
  16611. if (this.rotationQuaternion) {
  16612. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16613. return false;
  16614. }
  16615. if (!this._cache.rotation.equals(this.rotation))
  16616. return false;
  16617. if (!this._cache.scaling.equals(this.scaling))
  16618. return false;
  16619. return true;
  16620. };
  16621. TransformNode.prototype._initCache = function () {
  16622. _super.prototype._initCache.call(this);
  16623. this._cache.localMatrixUpdated = false;
  16624. this._cache.position = BABYLON.Vector3.Zero();
  16625. this._cache.scaling = BABYLON.Vector3.Zero();
  16626. this._cache.rotation = BABYLON.Vector3.Zero();
  16627. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16628. this._cache.billboardMode = -1;
  16629. };
  16630. TransformNode.prototype.markAsDirty = function (property) {
  16631. if (property === "rotation") {
  16632. this.rotationQuaternion = null;
  16633. }
  16634. this._currentRenderId = Number.MAX_VALUE;
  16635. this._isDirty = true;
  16636. return this;
  16637. };
  16638. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16639. /**
  16640. * Returns the current mesh absolute position.
  16641. * Retuns a Vector3.
  16642. */
  16643. get: function () {
  16644. return this._absolutePosition;
  16645. },
  16646. enumerable: true,
  16647. configurable: true
  16648. });
  16649. /**
  16650. * Sets a new matrix to apply before all other transformation
  16651. * @param matrix defines the transform matrix
  16652. * @returns the current TransformNode
  16653. */
  16654. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16655. return this.setPivotMatrix(matrix, false);
  16656. };
  16657. /**
  16658. * Sets a new pivot matrix to the current node
  16659. * @param matrix defines the new pivot matrix to use
  16660. * @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
  16661. * @returns the current TransformNode
  16662. */
  16663. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16664. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16665. this._pivotMatrix = matrix.clone();
  16666. this._cache.pivotMatrixUpdated = true;
  16667. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16668. if (this._postMultiplyPivotMatrix) {
  16669. if (!this._pivotMatrixInverse) {
  16670. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16671. }
  16672. else {
  16673. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16674. }
  16675. }
  16676. return this;
  16677. };
  16678. /**
  16679. * Returns the mesh pivot matrix.
  16680. * Default : Identity.
  16681. * A Matrix is returned.
  16682. */
  16683. TransformNode.prototype.getPivotMatrix = function () {
  16684. return this._pivotMatrix;
  16685. };
  16686. /**
  16687. * Prevents the World matrix to be computed any longer.
  16688. * Returns the AbstractMesh.
  16689. */
  16690. TransformNode.prototype.freezeWorldMatrix = function () {
  16691. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16692. this.computeWorldMatrix(true);
  16693. this._isWorldMatrixFrozen = true;
  16694. return this;
  16695. };
  16696. /**
  16697. * Allows back the World matrix computation.
  16698. * Returns the AbstractMesh.
  16699. */
  16700. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16701. this._isWorldMatrixFrozen = false;
  16702. this.computeWorldMatrix(true);
  16703. return this;
  16704. };
  16705. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16706. /**
  16707. * True if the World matrix has been frozen.
  16708. * Returns a boolean.
  16709. */
  16710. get: function () {
  16711. return this._isWorldMatrixFrozen;
  16712. },
  16713. enumerable: true,
  16714. configurable: true
  16715. });
  16716. /**
  16717. * Retuns the mesh absolute position in the World.
  16718. * Returns a Vector3.
  16719. */
  16720. TransformNode.prototype.getAbsolutePosition = function () {
  16721. this.computeWorldMatrix();
  16722. return this._absolutePosition;
  16723. };
  16724. /**
  16725. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16726. * Returns the AbstractMesh.
  16727. */
  16728. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16729. if (!absolutePosition) {
  16730. return this;
  16731. }
  16732. var absolutePositionX;
  16733. var absolutePositionY;
  16734. var absolutePositionZ;
  16735. if (absolutePosition.x === undefined) {
  16736. if (arguments.length < 3) {
  16737. return this;
  16738. }
  16739. absolutePositionX = arguments[0];
  16740. absolutePositionY = arguments[1];
  16741. absolutePositionZ = arguments[2];
  16742. }
  16743. else {
  16744. absolutePositionX = absolutePosition.x;
  16745. absolutePositionY = absolutePosition.y;
  16746. absolutePositionZ = absolutePosition.z;
  16747. }
  16748. if (this.parent) {
  16749. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16750. invertParentWorldMatrix.invert();
  16751. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16752. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16753. }
  16754. else {
  16755. this.position.x = absolutePositionX;
  16756. this.position.y = absolutePositionY;
  16757. this.position.z = absolutePositionZ;
  16758. }
  16759. return this;
  16760. };
  16761. /**
  16762. * Sets the mesh position in its local space.
  16763. * Returns the AbstractMesh.
  16764. */
  16765. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16766. this.computeWorldMatrix();
  16767. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16768. return this;
  16769. };
  16770. /**
  16771. * Returns the mesh position in the local space from the current World matrix values.
  16772. * Returns a new Vector3.
  16773. */
  16774. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16775. this.computeWorldMatrix();
  16776. var invLocalWorldMatrix = this._localWorld.clone();
  16777. invLocalWorldMatrix.invert();
  16778. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16779. };
  16780. /**
  16781. * Translates the mesh along the passed Vector3 in its local space.
  16782. * Returns the AbstractMesh.
  16783. */
  16784. TransformNode.prototype.locallyTranslate = function (vector3) {
  16785. this.computeWorldMatrix(true);
  16786. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16787. return this;
  16788. };
  16789. /**
  16790. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16791. * @param targetPoint the position (must be in same space as current mesh) to look at
  16792. * @param yawCor optional yaw (y-axis) correction in radians
  16793. * @param pitchCor optional pitch (x-axis) correction in radians
  16794. * @param rollCor optional roll (z-axis) correction in radians
  16795. * @param space the choosen space of the target
  16796. * @returns the TransformNode.
  16797. */
  16798. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16799. if (yawCor === void 0) { yawCor = 0; }
  16800. if (pitchCor === void 0) { pitchCor = 0; }
  16801. if (rollCor === void 0) { rollCor = 0; }
  16802. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16803. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16804. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16805. targetPoint.subtractToRef(pos, dv);
  16806. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16807. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16808. var pitch = Math.atan2(dv.y, len);
  16809. if (this.rotationQuaternion) {
  16810. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16811. }
  16812. else {
  16813. this.rotation.x = pitch + pitchCor;
  16814. this.rotation.y = yaw + yawCor;
  16815. this.rotation.z = rollCor;
  16816. }
  16817. return this;
  16818. };
  16819. /**
  16820. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16821. * This Vector3 is expressed in the World space.
  16822. */
  16823. TransformNode.prototype.getDirection = function (localAxis) {
  16824. var result = BABYLON.Vector3.Zero();
  16825. this.getDirectionToRef(localAxis, result);
  16826. return result;
  16827. };
  16828. /**
  16829. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16830. * localAxis is expressed in the mesh local space.
  16831. * result is computed in the Wordl space from the mesh World matrix.
  16832. * Returns the AbstractMesh.
  16833. */
  16834. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16835. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16836. return this;
  16837. };
  16838. /**
  16839. * Sets a new pivot point to the current node
  16840. * @param point defines the new pivot point to use
  16841. * @param space defines if the point is in world or local space (local by default)
  16842. * @returns the current TransformNode
  16843. */
  16844. TransformNode.prototype.setPivotPoint = function (point, space) {
  16845. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16846. if (this.getScene().getRenderId() == 0) {
  16847. this.computeWorldMatrix(true);
  16848. }
  16849. var wm = this.getWorldMatrix();
  16850. if (space == BABYLON.Space.WORLD) {
  16851. var tmat = BABYLON.Tmp.Matrix[0];
  16852. wm.invertToRef(tmat);
  16853. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16854. }
  16855. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16856. };
  16857. /**
  16858. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16859. */
  16860. TransformNode.prototype.getPivotPoint = function () {
  16861. var point = BABYLON.Vector3.Zero();
  16862. this.getPivotPointToRef(point);
  16863. return point;
  16864. };
  16865. /**
  16866. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16867. * Returns the AbstractMesh.
  16868. */
  16869. TransformNode.prototype.getPivotPointToRef = function (result) {
  16870. result.x = -this._pivotMatrix.m[12];
  16871. result.y = -this._pivotMatrix.m[13];
  16872. result.z = -this._pivotMatrix.m[14];
  16873. return this;
  16874. };
  16875. /**
  16876. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16877. */
  16878. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16879. var point = BABYLON.Vector3.Zero();
  16880. this.getAbsolutePivotPointToRef(point);
  16881. return point;
  16882. };
  16883. /**
  16884. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16885. * Returns the AbstractMesh.
  16886. */
  16887. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16888. result.x = this._pivotMatrix.m[12];
  16889. result.y = this._pivotMatrix.m[13];
  16890. result.z = this._pivotMatrix.m[14];
  16891. this.getPivotPointToRef(result);
  16892. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16893. return this;
  16894. };
  16895. /**
  16896. * Defines the passed node as the parent of the current node.
  16897. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16898. * Returns the TransformNode.
  16899. */
  16900. TransformNode.prototype.setParent = function (node) {
  16901. if (node === null) {
  16902. var rotation = BABYLON.Tmp.Quaternion[0];
  16903. var position = BABYLON.Tmp.Vector3[0];
  16904. var scale = BABYLON.Tmp.Vector3[1];
  16905. if (this.parent && this.parent.computeWorldMatrix) {
  16906. this.parent.computeWorldMatrix(true);
  16907. }
  16908. this.computeWorldMatrix(true);
  16909. this.getWorldMatrix().decompose(scale, rotation, position);
  16910. if (this.rotationQuaternion) {
  16911. this.rotationQuaternion.copyFrom(rotation);
  16912. }
  16913. else {
  16914. rotation.toEulerAnglesToRef(this.rotation);
  16915. }
  16916. this.scaling.x = scale.x;
  16917. this.scaling.y = scale.y;
  16918. this.scaling.z = scale.z;
  16919. this.position.x = position.x;
  16920. this.position.y = position.y;
  16921. this.position.z = position.z;
  16922. }
  16923. else {
  16924. var rotation = BABYLON.Tmp.Quaternion[0];
  16925. var position = BABYLON.Tmp.Vector3[0];
  16926. var scale = BABYLON.Tmp.Vector3[1];
  16927. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16928. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16929. this.computeWorldMatrix(true);
  16930. node.computeWorldMatrix(true);
  16931. node.getWorldMatrix().invertToRef(invParentMatrix);
  16932. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16933. diffMatrix.decompose(scale, rotation, position);
  16934. if (this.rotationQuaternion) {
  16935. this.rotationQuaternion.copyFrom(rotation);
  16936. }
  16937. else {
  16938. rotation.toEulerAnglesToRef(this.rotation);
  16939. }
  16940. this.position.x = position.x;
  16941. this.position.y = position.y;
  16942. this.position.z = position.z;
  16943. this.scaling.x = scale.x;
  16944. this.scaling.y = scale.y;
  16945. this.scaling.z = scale.z;
  16946. }
  16947. this.parent = node;
  16948. return this;
  16949. };
  16950. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16951. get: function () {
  16952. return this._nonUniformScaling;
  16953. },
  16954. enumerable: true,
  16955. configurable: true
  16956. });
  16957. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16958. if (this._nonUniformScaling === value) {
  16959. return false;
  16960. }
  16961. this._nonUniformScaling = true;
  16962. return true;
  16963. };
  16964. /**
  16965. * Attach the current TransformNode to another TransformNode associated with a bone
  16966. * @param bone Bone affecting the TransformNode
  16967. * @param affectedTransformNode TransformNode associated with the bone
  16968. */
  16969. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16970. this._transformToBoneReferal = affectedTransformNode;
  16971. this.parent = bone;
  16972. if (bone.getWorldMatrix().determinant() < 0) {
  16973. this.scalingDeterminant *= -1;
  16974. }
  16975. return this;
  16976. };
  16977. TransformNode.prototype.detachFromBone = function () {
  16978. if (!this.parent) {
  16979. return this;
  16980. }
  16981. if (this.parent.getWorldMatrix().determinant() < 0) {
  16982. this.scalingDeterminant *= -1;
  16983. }
  16984. this._transformToBoneReferal = null;
  16985. this.parent = null;
  16986. return this;
  16987. };
  16988. /**
  16989. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16990. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16991. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16992. * The passed axis is also normalized.
  16993. * Returns the AbstractMesh.
  16994. */
  16995. TransformNode.prototype.rotate = function (axis, amount, space) {
  16996. axis.normalize();
  16997. if (!this.rotationQuaternion) {
  16998. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16999. this.rotation = BABYLON.Vector3.Zero();
  17000. }
  17001. var rotationQuaternion;
  17002. if (!space || space === BABYLON.Space.LOCAL) {
  17003. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  17004. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  17005. }
  17006. else {
  17007. if (this.parent) {
  17008. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  17009. invertParentWorldMatrix.invert();
  17010. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  17011. }
  17012. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  17013. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17014. }
  17015. return this;
  17016. };
  17017. /**
  17018. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  17019. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17020. * The passed axis is also normalized.
  17021. * Returns the AbstractMesh.
  17022. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  17023. */
  17024. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  17025. axis.normalize();
  17026. if (!this.rotationQuaternion) {
  17027. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17028. this.rotation.copyFromFloats(0, 0, 0);
  17029. }
  17030. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  17031. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  17032. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  17033. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  17034. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  17035. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  17036. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  17037. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  17038. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17039. return this;
  17040. };
  17041. /**
  17042. * Translates the mesh along the axis vector for the passed distance in the given space.
  17043. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17044. * Returns the AbstractMesh.
  17045. */
  17046. TransformNode.prototype.translate = function (axis, distance, space) {
  17047. var displacementVector = axis.scale(distance);
  17048. if (!space || space === BABYLON.Space.LOCAL) {
  17049. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  17050. this.setPositionWithLocalVector(tempV3);
  17051. }
  17052. else {
  17053. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  17054. }
  17055. return this;
  17056. };
  17057. /**
  17058. * Adds a rotation step to the mesh current rotation.
  17059. * x, y, z are Euler angles expressed in radians.
  17060. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  17061. * This means this rotation is made in the mesh local space only.
  17062. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  17063. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  17064. * ```javascript
  17065. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  17066. * ```
  17067. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  17068. * 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.
  17069. * Returns the AbstractMesh.
  17070. */
  17071. TransformNode.prototype.addRotation = function (x, y, z) {
  17072. var rotationQuaternion;
  17073. if (this.rotationQuaternion) {
  17074. rotationQuaternion = this.rotationQuaternion;
  17075. }
  17076. else {
  17077. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  17078. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  17079. }
  17080. var accumulation = BABYLON.Tmp.Quaternion[0];
  17081. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  17082. rotationQuaternion.multiplyInPlace(accumulation);
  17083. if (!this.rotationQuaternion) {
  17084. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  17085. }
  17086. return this;
  17087. };
  17088. /**
  17089. * Computes the mesh World matrix and returns it.
  17090. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  17091. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  17092. * If the parameter `force`is set to `true`, the actual computation is done.
  17093. * Returns the mesh World Matrix.
  17094. */
  17095. TransformNode.prototype.computeWorldMatrix = function (force) {
  17096. if (this._isWorldMatrixFrozen) {
  17097. return this._worldMatrix;
  17098. }
  17099. if (!force && this.isSynchronized(true)) {
  17100. return this._worldMatrix;
  17101. }
  17102. this._cache.position.copyFrom(this.position);
  17103. this._cache.scaling.copyFrom(this.scaling);
  17104. this._cache.pivotMatrixUpdated = false;
  17105. this._cache.billboardMode = this.billboardMode;
  17106. this._currentRenderId = this.getScene().getRenderId();
  17107. this._isDirty = false;
  17108. // Scaling
  17109. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  17110. // Rotation
  17111. //rotate, if quaternion is set and rotation was used
  17112. if (this.rotationQuaternion) {
  17113. var len = this.rotation.length();
  17114. if (len) {
  17115. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  17116. this.rotation.copyFromFloats(0, 0, 0);
  17117. }
  17118. }
  17119. if (this.rotationQuaternion) {
  17120. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  17121. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17122. }
  17123. else {
  17124. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  17125. this._cache.rotation.copyFrom(this.rotation);
  17126. }
  17127. // Translation
  17128. var camera = this.getScene().activeCamera;
  17129. if (this.infiniteDistance && !this.parent && camera) {
  17130. var cameraWorldMatrix = camera.getWorldMatrix();
  17131. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  17132. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  17133. }
  17134. else {
  17135. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  17136. }
  17137. // Composing transformations
  17138. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  17139. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17140. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  17141. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  17142. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  17143. // Need to decompose each rotation here
  17144. var currentPosition = BABYLON.Tmp.Vector3[3];
  17145. if (this.parent && this.parent.getWorldMatrix) {
  17146. if (this._transformToBoneReferal) {
  17147. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17148. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  17149. }
  17150. else {
  17151. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17152. }
  17153. }
  17154. else {
  17155. currentPosition.copyFrom(this.position);
  17156. }
  17157. currentPosition.subtractInPlace(camera.globalPosition);
  17158. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17159. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  17160. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17161. }
  17162. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  17163. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17164. }
  17165. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  17166. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17167. }
  17168. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17169. }
  17170. else {
  17171. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17172. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17173. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17174. }
  17175. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17176. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17177. }
  17178. // Local world
  17179. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17180. // Parent
  17181. if (this.parent && this.parent.getWorldMatrix) {
  17182. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  17183. if (this._transformToBoneReferal) {
  17184. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17185. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17186. }
  17187. else {
  17188. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17189. }
  17190. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17191. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17192. this._worldMatrix.copyFrom(this._localWorld);
  17193. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17194. }
  17195. else {
  17196. if (this._transformToBoneReferal) {
  17197. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17198. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17199. }
  17200. else {
  17201. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17202. }
  17203. }
  17204. this._markSyncedWithParent();
  17205. }
  17206. else {
  17207. this._worldMatrix.copyFrom(this._localWorld);
  17208. }
  17209. // Post multiply inverse of pivotMatrix
  17210. if (this._postMultiplyPivotMatrix) {
  17211. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17212. }
  17213. // Normal matrix
  17214. if (this.scaling.isNonUniform) {
  17215. this._updateNonUniformScalingState(true);
  17216. }
  17217. else if (this.parent && this.parent._nonUniformScaling) {
  17218. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17219. }
  17220. else {
  17221. this._updateNonUniformScalingState(false);
  17222. }
  17223. this._afterComputeWorldMatrix();
  17224. // Absolute position
  17225. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17226. // Callbacks
  17227. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17228. if (!this._poseMatrix) {
  17229. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17230. }
  17231. // Cache the determinant
  17232. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17233. return this._worldMatrix;
  17234. };
  17235. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17236. };
  17237. /**
  17238. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17239. * @param func: callback function to add
  17240. *
  17241. * Returns the TransformNode.
  17242. */
  17243. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17244. this.onAfterWorldMatrixUpdateObservable.add(func);
  17245. return this;
  17246. };
  17247. /**
  17248. * Removes a registered callback function.
  17249. * Returns the TransformNode.
  17250. */
  17251. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17252. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17253. return this;
  17254. };
  17255. /**
  17256. * Clone the current transform node
  17257. * Returns the new transform node
  17258. * @param name Name of the new clone
  17259. * @param newParent New parent for the clone
  17260. * @param doNotCloneChildren Do not clone children hierarchy
  17261. */
  17262. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17263. var _this = this;
  17264. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17265. result.name = name;
  17266. result.id = name;
  17267. if (newParent) {
  17268. result.parent = newParent;
  17269. }
  17270. if (!doNotCloneChildren) {
  17271. // Children
  17272. var directDescendants = this.getDescendants(true);
  17273. for (var index = 0; index < directDescendants.length; index++) {
  17274. var child = directDescendants[index];
  17275. if (child.clone) {
  17276. child.clone(name + "." + child.name, result);
  17277. }
  17278. }
  17279. }
  17280. return result;
  17281. };
  17282. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17283. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17284. serializationObject.type = this.getClassName();
  17285. // Parent
  17286. if (this.parent) {
  17287. serializationObject.parentId = this.parent.id;
  17288. }
  17289. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17290. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17291. }
  17292. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17293. serializationObject.isEnabled = this.isEnabled();
  17294. // Parent
  17295. if (this.parent) {
  17296. serializationObject.parentId = this.parent.id;
  17297. }
  17298. return serializationObject;
  17299. };
  17300. // Statics
  17301. /**
  17302. * Returns a new TransformNode object parsed from the source provided.
  17303. * The parameter `parsedMesh` is the source.
  17304. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17305. */
  17306. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17307. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17308. if (BABYLON.Tags) {
  17309. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17310. }
  17311. if (parsedTransformNode.localMatrix) {
  17312. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17313. }
  17314. else if (parsedTransformNode.pivotMatrix) {
  17315. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17316. }
  17317. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17318. // Parent
  17319. if (parsedTransformNode.parentId) {
  17320. transformNode._waitingParentId = parsedTransformNode.parentId;
  17321. }
  17322. return transformNode;
  17323. };
  17324. /**
  17325. * Releases resources associated with this transform node.
  17326. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17327. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17328. */
  17329. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17330. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17331. // Animations
  17332. this.getScene().stopAnimation(this);
  17333. // Remove from scene
  17334. this.getScene().removeTransformNode(this);
  17335. this.onAfterWorldMatrixUpdateObservable.clear();
  17336. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17337. };
  17338. // Statics
  17339. TransformNode.BILLBOARDMODE_NONE = 0;
  17340. TransformNode.BILLBOARDMODE_X = 1;
  17341. TransformNode.BILLBOARDMODE_Y = 2;
  17342. TransformNode.BILLBOARDMODE_Z = 4;
  17343. TransformNode.BILLBOARDMODE_ALL = 7;
  17344. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17345. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17346. __decorate([
  17347. BABYLON.serializeAsVector3()
  17348. ], TransformNode.prototype, "_rotation", void 0);
  17349. __decorate([
  17350. BABYLON.serializeAsQuaternion()
  17351. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17352. __decorate([
  17353. BABYLON.serializeAsVector3()
  17354. ], TransformNode.prototype, "_scaling", void 0);
  17355. __decorate([
  17356. BABYLON.serialize()
  17357. ], TransformNode.prototype, "billboardMode", void 0);
  17358. __decorate([
  17359. BABYLON.serialize()
  17360. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17361. __decorate([
  17362. BABYLON.serialize()
  17363. ], TransformNode.prototype, "infiniteDistance", void 0);
  17364. __decorate([
  17365. BABYLON.serializeAsVector3()
  17366. ], TransformNode.prototype, "position", void 0);
  17367. return TransformNode;
  17368. }(BABYLON.Node));
  17369. BABYLON.TransformNode = TransformNode;
  17370. })(BABYLON || (BABYLON = {}));
  17371. //# sourceMappingURL=babylon.transformNode.js.map
  17372. var BABYLON;
  17373. (function (BABYLON) {
  17374. var AbstractMesh = /** @class */ (function (_super) {
  17375. __extends(AbstractMesh, _super);
  17376. // Constructor
  17377. function AbstractMesh(name, scene) {
  17378. if (scene === void 0) { scene = null; }
  17379. var _this = _super.call(this, name, scene, false) || this;
  17380. _this._facetNb = 0; // facet number
  17381. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17382. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17383. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17384. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17385. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17386. _this._subDiv = {
  17387. max: 1,
  17388. X: 1,
  17389. Y: 1,
  17390. Z: 1
  17391. };
  17392. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17393. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17394. // Events
  17395. /**
  17396. * An event triggered when this mesh collides with another one
  17397. * @type {BABYLON.Observable}
  17398. */
  17399. _this.onCollideObservable = new BABYLON.Observable();
  17400. /**
  17401. * An event triggered when the collision's position changes
  17402. * @type {BABYLON.Observable}
  17403. */
  17404. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17405. /**
  17406. * An event triggered when material is changed
  17407. * @type {BABYLON.Observable}
  17408. */
  17409. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17410. // Properties
  17411. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17412. /**
  17413. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17414. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17415. * or
  17416. * 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.
  17417. * for more info check WebGl documentations
  17418. */
  17419. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17420. /**
  17421. * 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:
  17422. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17423. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17424. * 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.
  17425. */
  17426. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17427. /**
  17428. * 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.
  17429. * The default value is -1 which means don't break the query and wait till the result.
  17430. */
  17431. _this.occlusionRetryCount = -1;
  17432. _this._occlusionInternalRetryCounter = 0;
  17433. _this._isOccluded = false;
  17434. _this._isOcclusionQueryInProgress = false;
  17435. _this._visibility = 1.0;
  17436. _this.alphaIndex = Number.MAX_VALUE;
  17437. _this.isVisible = true;
  17438. _this.isPickable = true;
  17439. _this.showBoundingBox = false;
  17440. _this.showSubMeshesBoundingBox = false;
  17441. _this.isBlocker = false;
  17442. _this.enablePointerMoveEvents = false;
  17443. _this.renderingGroupId = 0;
  17444. _this._receiveShadows = false;
  17445. _this.renderOutline = false;
  17446. _this.outlineColor = BABYLON.Color3.Red();
  17447. _this.outlineWidth = 0.02;
  17448. _this.renderOverlay = false;
  17449. _this.overlayColor = BABYLON.Color3.Red();
  17450. _this.overlayAlpha = 0.5;
  17451. _this._hasVertexAlpha = false;
  17452. _this._useVertexColors = true;
  17453. _this._computeBonesUsingShaders = true;
  17454. _this._numBoneInfluencers = 4;
  17455. _this._applyFog = true;
  17456. _this.useOctreeForRenderingSelection = true;
  17457. _this.useOctreeForPicking = true;
  17458. _this.useOctreeForCollisions = true;
  17459. _this._layerMask = 0x0FFFFFFF;
  17460. /**
  17461. * True if the mesh must be rendered in any case.
  17462. */
  17463. _this.alwaysSelectAsActiveMesh = false;
  17464. /**
  17465. * This scene's action manager
  17466. * @type {BABYLON.ActionManager}
  17467. */
  17468. _this.actionManager = null;
  17469. // Physics
  17470. _this.physicsImpostor = null;
  17471. // Collisions
  17472. _this._checkCollisions = false;
  17473. _this._collisionMask = -1;
  17474. _this._collisionGroup = -1;
  17475. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17476. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17477. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17478. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17479. // Edges
  17480. _this.edgesWidth = 1;
  17481. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17482. // Cache
  17483. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17484. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17485. _this._renderId = 0;
  17486. _this._intersectionsInProgress = new Array();
  17487. _this._unIndexed = false;
  17488. _this._lightSources = new Array();
  17489. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17490. if (collidedMesh === void 0) { collidedMesh = null; }
  17491. //TODO move this to the collision coordinator!
  17492. if (_this.getScene().workerCollisions)
  17493. newPosition.multiplyInPlace(_this._collider._radius);
  17494. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17495. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17496. _this.position.addInPlace(_this._diffPositionForCollisions);
  17497. }
  17498. if (collidedMesh) {
  17499. _this.onCollideObservable.notifyObservers(collidedMesh);
  17500. }
  17501. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17502. };
  17503. _this.getScene().addMesh(_this);
  17504. _this._resyncLightSources();
  17505. return _this;
  17506. }
  17507. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17508. get: function () {
  17509. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17510. },
  17511. enumerable: true,
  17512. configurable: true
  17513. });
  17514. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17515. get: function () {
  17516. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17517. },
  17518. enumerable: true,
  17519. configurable: true
  17520. });
  17521. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17522. get: function () {
  17523. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17524. },
  17525. enumerable: true,
  17526. configurable: true
  17527. });
  17528. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17529. get: function () {
  17530. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17531. },
  17532. enumerable: true,
  17533. configurable: true
  17534. });
  17535. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17536. get: function () {
  17537. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17538. },
  17539. enumerable: true,
  17540. configurable: true
  17541. });
  17542. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17543. /**
  17544. * Read-only : the number of facets in the mesh
  17545. */
  17546. get: function () {
  17547. return this._facetNb;
  17548. },
  17549. enumerable: true,
  17550. configurable: true
  17551. });
  17552. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17553. /**
  17554. * The number (integer) of subdivisions per axis in the partioning space
  17555. */
  17556. get: function () {
  17557. return this._partitioningSubdivisions;
  17558. },
  17559. set: function (nb) {
  17560. this._partitioningSubdivisions = nb;
  17561. },
  17562. enumerable: true,
  17563. configurable: true
  17564. });
  17565. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17566. /**
  17567. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17568. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17569. */
  17570. get: function () {
  17571. return this._partitioningBBoxRatio;
  17572. },
  17573. set: function (ratio) {
  17574. this._partitioningBBoxRatio = ratio;
  17575. },
  17576. enumerable: true,
  17577. configurable: true
  17578. });
  17579. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17580. /**
  17581. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17582. * Works only for updatable meshes.
  17583. * Doesn't work with multi-materials.
  17584. */
  17585. get: function () {
  17586. return this._facetDepthSort;
  17587. },
  17588. set: function (sort) {
  17589. this._facetDepthSort = sort;
  17590. },
  17591. enumerable: true,
  17592. configurable: true
  17593. });
  17594. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17595. /**
  17596. * The location (Vector3) where the facet depth sort must be computed from.
  17597. * By default, the active camera position.
  17598. * Used only when facet depth sort is enabled.
  17599. */
  17600. get: function () {
  17601. return this._facetDepthSortFrom;
  17602. },
  17603. set: function (location) {
  17604. this._facetDepthSortFrom = location;
  17605. },
  17606. enumerable: true,
  17607. configurable: true
  17608. });
  17609. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17610. /**
  17611. * Read-only boolean : is the feature facetData enabled ?
  17612. */
  17613. get: function () {
  17614. return this._facetDataEnabled;
  17615. },
  17616. enumerable: true,
  17617. configurable: true
  17618. });
  17619. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17620. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17621. return false;
  17622. }
  17623. this._markSubMeshesAsMiscDirty();
  17624. return true;
  17625. };
  17626. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17627. set: function (callback) {
  17628. if (this._onCollideObserver) {
  17629. this.onCollideObservable.remove(this._onCollideObserver);
  17630. }
  17631. this._onCollideObserver = this.onCollideObservable.add(callback);
  17632. },
  17633. enumerable: true,
  17634. configurable: true
  17635. });
  17636. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17637. set: function (callback) {
  17638. if (this._onCollisionPositionChangeObserver) {
  17639. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17640. }
  17641. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17642. },
  17643. enumerable: true,
  17644. configurable: true
  17645. });
  17646. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17647. /**
  17648. * 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.
  17649. */
  17650. get: function () {
  17651. return this._isOccluded;
  17652. },
  17653. set: function (value) {
  17654. this._isOccluded = value;
  17655. },
  17656. enumerable: true,
  17657. configurable: true
  17658. });
  17659. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17660. /**
  17661. * Flag to check the progress status of the query
  17662. */
  17663. get: function () {
  17664. return this._isOcclusionQueryInProgress;
  17665. },
  17666. enumerable: true,
  17667. configurable: true
  17668. });
  17669. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17670. /**
  17671. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17672. */
  17673. get: function () {
  17674. return this._visibility;
  17675. },
  17676. /**
  17677. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17678. */
  17679. set: function (value) {
  17680. if (this._visibility === value) {
  17681. return;
  17682. }
  17683. this._visibility = value;
  17684. this._markSubMeshesAsMiscDirty();
  17685. },
  17686. enumerable: true,
  17687. configurable: true
  17688. });
  17689. Object.defineProperty(AbstractMesh.prototype, "material", {
  17690. get: function () {
  17691. return this._material;
  17692. },
  17693. set: function (value) {
  17694. if (this._material === value) {
  17695. return;
  17696. }
  17697. this._material = value;
  17698. if (this.onMaterialChangedObservable.hasObservers) {
  17699. this.onMaterialChangedObservable.notifyObservers(this);
  17700. }
  17701. if (!this.subMeshes) {
  17702. return;
  17703. }
  17704. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17705. var subMesh = _a[_i];
  17706. subMesh.setEffect(null);
  17707. }
  17708. },
  17709. enumerable: true,
  17710. configurable: true
  17711. });
  17712. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17713. get: function () {
  17714. return this._receiveShadows;
  17715. },
  17716. set: function (value) {
  17717. if (this._receiveShadows === value) {
  17718. return;
  17719. }
  17720. this._receiveShadows = value;
  17721. this._markSubMeshesAsLightDirty();
  17722. },
  17723. enumerable: true,
  17724. configurable: true
  17725. });
  17726. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17727. get: function () {
  17728. return this._hasVertexAlpha;
  17729. },
  17730. set: function (value) {
  17731. if (this._hasVertexAlpha === value) {
  17732. return;
  17733. }
  17734. this._hasVertexAlpha = value;
  17735. this._markSubMeshesAsAttributesDirty();
  17736. this._markSubMeshesAsMiscDirty();
  17737. },
  17738. enumerable: true,
  17739. configurable: true
  17740. });
  17741. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17742. get: function () {
  17743. return this._useVertexColors;
  17744. },
  17745. set: function (value) {
  17746. if (this._useVertexColors === value) {
  17747. return;
  17748. }
  17749. this._useVertexColors = value;
  17750. this._markSubMeshesAsAttributesDirty();
  17751. },
  17752. enumerable: true,
  17753. configurable: true
  17754. });
  17755. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17756. get: function () {
  17757. return this._computeBonesUsingShaders;
  17758. },
  17759. set: function (value) {
  17760. if (this._computeBonesUsingShaders === value) {
  17761. return;
  17762. }
  17763. this._computeBonesUsingShaders = value;
  17764. this._markSubMeshesAsAttributesDirty();
  17765. },
  17766. enumerable: true,
  17767. configurable: true
  17768. });
  17769. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17770. get: function () {
  17771. return this._numBoneInfluencers;
  17772. },
  17773. set: function (value) {
  17774. if (this._numBoneInfluencers === value) {
  17775. return;
  17776. }
  17777. this._numBoneInfluencers = value;
  17778. this._markSubMeshesAsAttributesDirty();
  17779. },
  17780. enumerable: true,
  17781. configurable: true
  17782. });
  17783. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17784. get: function () {
  17785. return this._applyFog;
  17786. },
  17787. set: function (value) {
  17788. if (this._applyFog === value) {
  17789. return;
  17790. }
  17791. this._applyFog = value;
  17792. this._markSubMeshesAsMiscDirty();
  17793. },
  17794. enumerable: true,
  17795. configurable: true
  17796. });
  17797. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17798. get: function () {
  17799. return this._layerMask;
  17800. },
  17801. set: function (value) {
  17802. if (value === this._layerMask) {
  17803. return;
  17804. }
  17805. this._layerMask = value;
  17806. this._resyncLightSources();
  17807. },
  17808. enumerable: true,
  17809. configurable: true
  17810. });
  17811. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17812. get: function () {
  17813. return this._collisionMask;
  17814. },
  17815. set: function (mask) {
  17816. this._collisionMask = !isNaN(mask) ? mask : -1;
  17817. },
  17818. enumerable: true,
  17819. configurable: true
  17820. });
  17821. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17822. get: function () {
  17823. return this._collisionGroup;
  17824. },
  17825. set: function (mask) {
  17826. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17827. },
  17828. enumerable: true,
  17829. configurable: true
  17830. });
  17831. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17832. get: function () {
  17833. return null;
  17834. },
  17835. enumerable: true,
  17836. configurable: true
  17837. });
  17838. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17839. get: function () {
  17840. return this._skeleton;
  17841. },
  17842. set: function (value) {
  17843. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17844. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17845. }
  17846. if (value && value.needInitialSkinMatrix) {
  17847. value._registerMeshWithPoseMatrix(this);
  17848. }
  17849. this._skeleton = value;
  17850. if (!this._skeleton) {
  17851. this._bonesTransformMatrices = null;
  17852. }
  17853. this._markSubMeshesAsAttributesDirty();
  17854. },
  17855. enumerable: true,
  17856. configurable: true
  17857. });
  17858. /**
  17859. * Returns the string "AbstractMesh"
  17860. */
  17861. AbstractMesh.prototype.getClassName = function () {
  17862. return "AbstractMesh";
  17863. };
  17864. /**
  17865. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17866. */
  17867. AbstractMesh.prototype.toString = function (fullDetails) {
  17868. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17869. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17870. if (this._skeleton) {
  17871. ret += ", skeleton: " + this._skeleton.name;
  17872. }
  17873. if (fullDetails) {
  17874. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17875. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17876. }
  17877. return ret;
  17878. };
  17879. AbstractMesh.prototype._rebuild = function () {
  17880. if (this._occlusionQuery) {
  17881. this._occlusionQuery = null;
  17882. }
  17883. if (this._edgesRenderer) {
  17884. this._edgesRenderer._rebuild();
  17885. }
  17886. if (!this.subMeshes) {
  17887. return;
  17888. }
  17889. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17890. var subMesh = _a[_i];
  17891. subMesh._rebuild();
  17892. }
  17893. };
  17894. AbstractMesh.prototype._resyncLightSources = function () {
  17895. this._lightSources.length = 0;
  17896. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17897. var light = _a[_i];
  17898. if (!light.isEnabled()) {
  17899. continue;
  17900. }
  17901. if (light.canAffectMesh(this)) {
  17902. this._lightSources.push(light);
  17903. }
  17904. }
  17905. this._markSubMeshesAsLightDirty();
  17906. };
  17907. AbstractMesh.prototype._resyncLighSource = function (light) {
  17908. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17909. var index = this._lightSources.indexOf(light);
  17910. if (index === -1) {
  17911. if (!isIn) {
  17912. return;
  17913. }
  17914. this._lightSources.push(light);
  17915. }
  17916. else {
  17917. if (isIn) {
  17918. return;
  17919. }
  17920. this._lightSources.splice(index, 1);
  17921. }
  17922. this._markSubMeshesAsLightDirty();
  17923. };
  17924. AbstractMesh.prototype._removeLightSource = function (light) {
  17925. var index = this._lightSources.indexOf(light);
  17926. if (index === -1) {
  17927. return;
  17928. }
  17929. this._lightSources.splice(index, 1);
  17930. this._markSubMeshesAsLightDirty();
  17931. };
  17932. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17933. if (!this.subMeshes) {
  17934. return;
  17935. }
  17936. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17937. var subMesh = _a[_i];
  17938. if (subMesh._materialDefines) {
  17939. func(subMesh._materialDefines);
  17940. }
  17941. }
  17942. };
  17943. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17944. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17945. };
  17946. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17947. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17948. };
  17949. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17950. if (!this.subMeshes) {
  17951. return;
  17952. }
  17953. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17954. var subMesh = _a[_i];
  17955. var material = subMesh.getMaterial();
  17956. if (material) {
  17957. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17958. }
  17959. }
  17960. };
  17961. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17962. /**
  17963. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17964. * Default : (1.0, 1.0, 1.0)
  17965. */
  17966. get: function () {
  17967. return this._scaling;
  17968. },
  17969. /**
  17970. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17971. * Default : (1.0, 1.0, 1.0)
  17972. */
  17973. set: function (newScaling) {
  17974. this._scaling = newScaling;
  17975. if (this.physicsImpostor) {
  17976. this.physicsImpostor.forceUpdate();
  17977. }
  17978. },
  17979. enumerable: true,
  17980. configurable: true
  17981. });
  17982. // Methods
  17983. /**
  17984. * Disables the mesh edger rendering mode.
  17985. * Returns the AbstractMesh.
  17986. */
  17987. AbstractMesh.prototype.disableEdgesRendering = function () {
  17988. if (this._edgesRenderer) {
  17989. this._edgesRenderer.dispose();
  17990. this._edgesRenderer = null;
  17991. }
  17992. return this;
  17993. };
  17994. /**
  17995. * Enables the edge rendering mode on the mesh.
  17996. * This mode makes the mesh edges visible.
  17997. * Returns the AbstractMesh.
  17998. */
  17999. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  18000. if (epsilon === void 0) { epsilon = 0.95; }
  18001. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  18002. this.disableEdgesRendering();
  18003. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  18004. return this;
  18005. };
  18006. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  18007. /**
  18008. * Returns true if the mesh is blocked. Used by the class Mesh.
  18009. * Returns the boolean `false` by default.
  18010. */
  18011. get: function () {
  18012. return false;
  18013. },
  18014. enumerable: true,
  18015. configurable: true
  18016. });
  18017. /**
  18018. * Returns the mesh itself by default, used by the class Mesh.
  18019. * Returned type : AbstractMesh
  18020. */
  18021. AbstractMesh.prototype.getLOD = function (camera) {
  18022. return this;
  18023. };
  18024. /**
  18025. * Returns 0 by default, used by the class Mesh.
  18026. * Returns an integer.
  18027. */
  18028. AbstractMesh.prototype.getTotalVertices = function () {
  18029. return 0;
  18030. };
  18031. /**
  18032. * Returns null by default, used by the class Mesh.
  18033. * Returned type : integer array
  18034. */
  18035. AbstractMesh.prototype.getIndices = function () {
  18036. return null;
  18037. };
  18038. /**
  18039. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  18040. * Returned type : float array or Float32Array
  18041. */
  18042. AbstractMesh.prototype.getVerticesData = function (kind) {
  18043. return null;
  18044. };
  18045. /**
  18046. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18047. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18048. * The `data` are either a numeric array either a Float32Array.
  18049. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18050. * 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).
  18051. * Note that a new underlying VertexBuffer object is created each call.
  18052. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18053. *
  18054. * Possible `kind` values :
  18055. * - BABYLON.VertexBuffer.PositionKind
  18056. * - BABYLON.VertexBuffer.UVKind
  18057. * - BABYLON.VertexBuffer.UV2Kind
  18058. * - BABYLON.VertexBuffer.UV3Kind
  18059. * - BABYLON.VertexBuffer.UV4Kind
  18060. * - BABYLON.VertexBuffer.UV5Kind
  18061. * - BABYLON.VertexBuffer.UV6Kind
  18062. * - BABYLON.VertexBuffer.ColorKind
  18063. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18064. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18065. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18066. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18067. *
  18068. * Returns the Mesh.
  18069. */
  18070. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18071. return this;
  18072. };
  18073. /**
  18074. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18075. * If the mesh has no geometry, it is simply returned as it is.
  18076. * The `data` are either a numeric array either a Float32Array.
  18077. * No new underlying VertexBuffer object is created.
  18078. * 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.
  18079. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18080. *
  18081. * Possible `kind` values :
  18082. * - BABYLON.VertexBuffer.PositionKind
  18083. * - BABYLON.VertexBuffer.UVKind
  18084. * - BABYLON.VertexBuffer.UV2Kind
  18085. * - BABYLON.VertexBuffer.UV3Kind
  18086. * - BABYLON.VertexBuffer.UV4Kind
  18087. * - BABYLON.VertexBuffer.UV5Kind
  18088. * - BABYLON.VertexBuffer.UV6Kind
  18089. * - BABYLON.VertexBuffer.ColorKind
  18090. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18091. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18092. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18093. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18094. *
  18095. * Returns the Mesh.
  18096. */
  18097. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18098. return this;
  18099. };
  18100. /**
  18101. * Sets the mesh indices.
  18102. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  18103. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18104. * This method creates a new index buffer each call.
  18105. * Returns the Mesh.
  18106. */
  18107. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  18108. return this;
  18109. };
  18110. /** Returns false by default, used by the class Mesh.
  18111. * Returns a boolean
  18112. */
  18113. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  18114. return false;
  18115. };
  18116. /**
  18117. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  18118. * Returns a BoundingInfo
  18119. */
  18120. AbstractMesh.prototype.getBoundingInfo = function () {
  18121. if (this._masterMesh) {
  18122. return this._masterMesh.getBoundingInfo();
  18123. }
  18124. if (!this._boundingInfo) {
  18125. // this._boundingInfo is being created here
  18126. this._updateBoundingInfo();
  18127. }
  18128. // cannot be null.
  18129. return this._boundingInfo;
  18130. };
  18131. /**
  18132. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  18133. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  18134. */
  18135. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  18136. if (includeDescendants === void 0) { includeDescendants = true; }
  18137. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  18138. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  18139. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18140. if (maxDimension === 0) {
  18141. return this;
  18142. }
  18143. var scale = 1 / maxDimension;
  18144. this.scaling.scaleInPlace(scale);
  18145. return this;
  18146. };
  18147. /**
  18148. * Sets a mesh new object BoundingInfo.
  18149. * Returns the AbstractMesh.
  18150. */
  18151. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18152. this._boundingInfo = boundingInfo;
  18153. return this;
  18154. };
  18155. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18156. get: function () {
  18157. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18158. },
  18159. enumerable: true,
  18160. configurable: true
  18161. });
  18162. AbstractMesh.prototype._preActivate = function () {
  18163. };
  18164. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18165. };
  18166. AbstractMesh.prototype._activate = function (renderId) {
  18167. this._renderId = renderId;
  18168. };
  18169. /**
  18170. * Returns the latest update of the World matrix
  18171. * Returns a Matrix.
  18172. */
  18173. AbstractMesh.prototype.getWorldMatrix = function () {
  18174. if (this._masterMesh) {
  18175. return this._masterMesh.getWorldMatrix();
  18176. }
  18177. return _super.prototype.getWorldMatrix.call(this);
  18178. };
  18179. /**
  18180. * Returns the latest update of the World matrix determinant.
  18181. */
  18182. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18183. if (this._masterMesh) {
  18184. return this._masterMesh._getWorldMatrixDeterminant();
  18185. }
  18186. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18187. };
  18188. // ================================== Point of View Movement =================================
  18189. /**
  18190. * Perform relative position change from the point of view of behind the front of the mesh.
  18191. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18192. * Supports definition of mesh facing forward or backward.
  18193. * @param {number} amountRight
  18194. * @param {number} amountUp
  18195. * @param {number} amountForward
  18196. *
  18197. * Returns the AbstractMesh.
  18198. */
  18199. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18200. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18201. return this;
  18202. };
  18203. /**
  18204. * Calculate relative position change from the point of view of behind the front of the mesh.
  18205. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18206. * Supports definition of mesh facing forward or backward.
  18207. * @param {number} amountRight
  18208. * @param {number} amountUp
  18209. * @param {number} amountForward
  18210. *
  18211. * Returns a new Vector3.
  18212. */
  18213. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18214. var rotMatrix = new BABYLON.Matrix();
  18215. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18216. rotQuaternion.toRotationMatrix(rotMatrix);
  18217. var translationDelta = BABYLON.Vector3.Zero();
  18218. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18219. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18220. return translationDelta;
  18221. };
  18222. // ================================== Point of View Rotation =================================
  18223. /**
  18224. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18225. * Supports definition of mesh facing forward or backward.
  18226. * @param {number} flipBack
  18227. * @param {number} twirlClockwise
  18228. * @param {number} tiltRight
  18229. *
  18230. * Returns the AbstractMesh.
  18231. */
  18232. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18233. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18234. return this;
  18235. };
  18236. /**
  18237. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18238. * Supports definition of mesh facing forward or backward.
  18239. * @param {number} flipBack
  18240. * @param {number} twirlClockwise
  18241. * @param {number} tiltRight
  18242. *
  18243. * Returns a new Vector3.
  18244. */
  18245. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18246. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18247. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18248. };
  18249. /**
  18250. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18251. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18252. */
  18253. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18254. if (includeDescendants === void 0) { includeDescendants = true; }
  18255. this.computeWorldMatrix(true);
  18256. var min;
  18257. var max;
  18258. var boundingInfo = this.getBoundingInfo();
  18259. if (!this.subMeshes) {
  18260. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18261. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18262. }
  18263. else {
  18264. min = boundingInfo.boundingBox.minimumWorld;
  18265. max = boundingInfo.boundingBox.maximumWorld;
  18266. }
  18267. if (includeDescendants) {
  18268. var descendants = this.getDescendants(false);
  18269. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18270. var descendant = descendants_1[_i];
  18271. var childMesh = descendant;
  18272. childMesh.computeWorldMatrix(true);
  18273. //make sure we have the needed params to get mix and max
  18274. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18275. continue;
  18276. }
  18277. var childBoundingInfo = childMesh.getBoundingInfo();
  18278. var boundingBox = childBoundingInfo.boundingBox;
  18279. var minBox = boundingBox.minimumWorld;
  18280. var maxBox = boundingBox.maximumWorld;
  18281. BABYLON.Tools.CheckExtends(minBox, min, max);
  18282. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18283. }
  18284. }
  18285. return {
  18286. min: min,
  18287. max: max
  18288. };
  18289. };
  18290. /**
  18291. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18292. * Returns the AbstractMesh.
  18293. */
  18294. AbstractMesh.prototype._updateBoundingInfo = function () {
  18295. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18296. this._boundingInfo.update(this.worldMatrixFromCache);
  18297. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18298. return this;
  18299. };
  18300. /**
  18301. * Update a mesh's children BoundingInfo objects only.
  18302. * Returns the AbstractMesh.
  18303. */
  18304. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18305. if (!this.subMeshes) {
  18306. return this;
  18307. }
  18308. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18309. var subMesh = this.subMeshes[subIndex];
  18310. if (!subMesh.IsGlobal) {
  18311. subMesh.updateBoundingInfo(matrix);
  18312. }
  18313. }
  18314. return this;
  18315. };
  18316. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18317. // Bounding info
  18318. this._updateBoundingInfo();
  18319. };
  18320. /**
  18321. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18322. * A mesh is in the frustum if its bounding box intersects the frustum.
  18323. * Boolean returned.
  18324. */
  18325. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18326. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18327. };
  18328. /**
  18329. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18330. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18331. * Boolean returned.
  18332. */
  18333. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18334. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18335. ;
  18336. };
  18337. /**
  18338. * True if the mesh intersects another mesh or a SolidParticle object.
  18339. * 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)
  18340. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18341. * Returns a boolean.
  18342. */
  18343. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18344. if (precise === void 0) { precise = false; }
  18345. if (!this._boundingInfo || !mesh._boundingInfo) {
  18346. return false;
  18347. }
  18348. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18349. return true;
  18350. }
  18351. if (includeDescendants) {
  18352. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18353. var child = _a[_i];
  18354. if (child.intersectsMesh(mesh, precise, true)) {
  18355. return true;
  18356. }
  18357. }
  18358. }
  18359. return false;
  18360. };
  18361. /**
  18362. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18363. * Returns a boolean.
  18364. */
  18365. AbstractMesh.prototype.intersectsPoint = function (point) {
  18366. if (!this._boundingInfo) {
  18367. return false;
  18368. }
  18369. return this._boundingInfo.intersectsPoint(point);
  18370. };
  18371. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18372. return this.physicsImpostor;
  18373. };
  18374. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18375. if (camera === void 0) { camera = null; }
  18376. if (!camera) {
  18377. camera = this.getScene().activeCamera;
  18378. }
  18379. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18380. };
  18381. /**
  18382. * Returns the distance from the mesh to the active camera.
  18383. * Returns a float.
  18384. */
  18385. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18386. if (camera === void 0) { camera = null; }
  18387. if (!camera) {
  18388. camera = this.getScene().activeCamera;
  18389. }
  18390. return this.absolutePosition.subtract(camera.position).length();
  18391. };
  18392. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18393. if (!this.physicsImpostor) {
  18394. return this;
  18395. }
  18396. this.physicsImpostor.applyImpulse(force, contactPoint);
  18397. return this;
  18398. };
  18399. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18400. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18401. return this;
  18402. }
  18403. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18404. mainPivot: pivot1,
  18405. connectedPivot: pivot2,
  18406. nativeParams: options
  18407. });
  18408. return this;
  18409. };
  18410. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18411. // Collisions
  18412. /**
  18413. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18414. * Default `false`.
  18415. */
  18416. get: function () {
  18417. return this._checkCollisions;
  18418. },
  18419. set: function (collisionEnabled) {
  18420. this._checkCollisions = collisionEnabled;
  18421. if (this.getScene().workerCollisions) {
  18422. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18423. }
  18424. },
  18425. enumerable: true,
  18426. configurable: true
  18427. });
  18428. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18429. /**
  18430. * Gets Collider object used to compute collisions (not physics)
  18431. */
  18432. get: function () {
  18433. return this._collider;
  18434. },
  18435. enumerable: true,
  18436. configurable: true
  18437. });
  18438. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18439. var globalPosition = this.getAbsolutePosition();
  18440. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18441. if (!this._collider) {
  18442. this._collider = new BABYLON.Collider();
  18443. }
  18444. this._collider._radius = this.ellipsoid;
  18445. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18446. return this;
  18447. };
  18448. // Submeshes octree
  18449. /**
  18450. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18451. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18452. * Returns an Octree of submeshes.
  18453. */
  18454. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18455. if (maxCapacity === void 0) { maxCapacity = 64; }
  18456. if (maxDepth === void 0) { maxDepth = 2; }
  18457. if (!this._submeshesOctree) {
  18458. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18459. }
  18460. this.computeWorldMatrix(true);
  18461. var boundingInfo = this.getBoundingInfo();
  18462. // Update octree
  18463. var bbox = boundingInfo.boundingBox;
  18464. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18465. return this._submeshesOctree;
  18466. };
  18467. // Collisions
  18468. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18469. this._generatePointsArray();
  18470. if (!this._positions) {
  18471. return this;
  18472. }
  18473. // Transformation
  18474. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18475. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18476. subMesh._lastColliderWorldVertices = [];
  18477. subMesh._trianglePlanes = [];
  18478. var start = subMesh.verticesStart;
  18479. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18480. for (var i = start; i < end; i++) {
  18481. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18482. }
  18483. }
  18484. // Collide
  18485. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18486. if (collider.collisionFound) {
  18487. collider.collidedMesh = this;
  18488. }
  18489. return this;
  18490. };
  18491. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18492. var subMeshes;
  18493. var len;
  18494. // Octrees
  18495. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18496. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18497. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18498. len = intersections.length;
  18499. subMeshes = intersections.data;
  18500. }
  18501. else {
  18502. subMeshes = this.subMeshes;
  18503. len = subMeshes.length;
  18504. }
  18505. for (var index = 0; index < len; index++) {
  18506. var subMesh = subMeshes[index];
  18507. // Bounding test
  18508. if (len > 1 && !subMesh._checkCollision(collider))
  18509. continue;
  18510. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18511. }
  18512. return this;
  18513. };
  18514. AbstractMesh.prototype._checkCollision = function (collider) {
  18515. // Bounding box test
  18516. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18517. return this;
  18518. // Transformation matrix
  18519. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18520. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18521. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18522. return this;
  18523. };
  18524. // Picking
  18525. AbstractMesh.prototype._generatePointsArray = function () {
  18526. return false;
  18527. };
  18528. /**
  18529. * Checks if the passed Ray intersects with the mesh.
  18530. * Returns an object PickingInfo.
  18531. */
  18532. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18533. var pickingInfo = new BABYLON.PickingInfo();
  18534. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18535. return pickingInfo;
  18536. }
  18537. if (!this._generatePointsArray()) {
  18538. return pickingInfo;
  18539. }
  18540. var intersectInfo = null;
  18541. // Octrees
  18542. var subMeshes;
  18543. var len;
  18544. if (this._submeshesOctree && this.useOctreeForPicking) {
  18545. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18546. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18547. len = intersections.length;
  18548. subMeshes = intersections.data;
  18549. }
  18550. else {
  18551. subMeshes = this.subMeshes;
  18552. len = subMeshes.length;
  18553. }
  18554. for (var index = 0; index < len; index++) {
  18555. var subMesh = subMeshes[index];
  18556. // Bounding test
  18557. if (len > 1 && !subMesh.canIntersects(ray))
  18558. continue;
  18559. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18560. if (currentIntersectInfo) {
  18561. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18562. intersectInfo = currentIntersectInfo;
  18563. intersectInfo.subMeshId = index;
  18564. if (fastCheck) {
  18565. break;
  18566. }
  18567. }
  18568. }
  18569. }
  18570. if (intersectInfo) {
  18571. // Get picked point
  18572. var world = this.getWorldMatrix();
  18573. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18574. var direction = ray.direction.clone();
  18575. direction = direction.scale(intersectInfo.distance);
  18576. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18577. var pickedPoint = worldOrigin.add(worldDirection);
  18578. // Return result
  18579. pickingInfo.hit = true;
  18580. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18581. pickingInfo.pickedPoint = pickedPoint;
  18582. pickingInfo.pickedMesh = this;
  18583. pickingInfo.bu = intersectInfo.bu || 0;
  18584. pickingInfo.bv = intersectInfo.bv || 0;
  18585. pickingInfo.faceId = intersectInfo.faceId;
  18586. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18587. return pickingInfo;
  18588. }
  18589. return pickingInfo;
  18590. };
  18591. /**
  18592. * Clones the mesh, used by the class Mesh.
  18593. * Just returns `null` for an AbstractMesh.
  18594. */
  18595. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18596. return null;
  18597. };
  18598. /**
  18599. * Disposes all the mesh submeshes.
  18600. * Returns the AbstractMesh.
  18601. */
  18602. AbstractMesh.prototype.releaseSubMeshes = function () {
  18603. if (this.subMeshes) {
  18604. while (this.subMeshes.length) {
  18605. this.subMeshes[0].dispose();
  18606. }
  18607. }
  18608. else {
  18609. this.subMeshes = new Array();
  18610. }
  18611. return this;
  18612. };
  18613. /**
  18614. * Releases resources associated with this abstract mesh.
  18615. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18616. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18617. */
  18618. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18619. var _this = this;
  18620. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18621. var index;
  18622. // Smart Array Retainers.
  18623. this.getScene().freeActiveMeshes();
  18624. this.getScene().freeRenderingGroups();
  18625. // Action manager
  18626. if (this.actionManager !== undefined && this.actionManager !== null) {
  18627. this.actionManager.dispose();
  18628. this.actionManager = null;
  18629. }
  18630. // Skeleton
  18631. this.skeleton = null;
  18632. // Physics
  18633. if (this.physicsImpostor) {
  18634. this.physicsImpostor.dispose();
  18635. }
  18636. // Intersections in progress
  18637. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18638. var other = this._intersectionsInProgress[index];
  18639. var pos = other._intersectionsInProgress.indexOf(this);
  18640. other._intersectionsInProgress.splice(pos, 1);
  18641. }
  18642. this._intersectionsInProgress = [];
  18643. // Lights
  18644. var lights = this.getScene().lights;
  18645. lights.forEach(function (light) {
  18646. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18647. if (meshIndex !== -1) {
  18648. light.includedOnlyMeshes.splice(meshIndex, 1);
  18649. }
  18650. meshIndex = light.excludedMeshes.indexOf(_this);
  18651. if (meshIndex !== -1) {
  18652. light.excludedMeshes.splice(meshIndex, 1);
  18653. }
  18654. // Shadow generators
  18655. var generator = light.getShadowGenerator();
  18656. if (generator) {
  18657. var shadowMap = generator.getShadowMap();
  18658. if (shadowMap && shadowMap.renderList) {
  18659. meshIndex = shadowMap.renderList.indexOf(_this);
  18660. if (meshIndex !== -1) {
  18661. shadowMap.renderList.splice(meshIndex, 1);
  18662. }
  18663. }
  18664. }
  18665. });
  18666. // Edges
  18667. if (this._edgesRenderer) {
  18668. this._edgesRenderer.dispose();
  18669. this._edgesRenderer = null;
  18670. }
  18671. // SubMeshes
  18672. if (this.getClassName() !== "InstancedMesh") {
  18673. this.releaseSubMeshes();
  18674. }
  18675. // Octree
  18676. var sceneOctree = this.getScene().selectionOctree;
  18677. if (sceneOctree !== undefined && sceneOctree !== null) {
  18678. var index = sceneOctree.dynamicContent.indexOf(this);
  18679. if (index !== -1) {
  18680. sceneOctree.dynamicContent.splice(index, 1);
  18681. }
  18682. }
  18683. // Query
  18684. var engine = this.getScene().getEngine();
  18685. if (this._occlusionQuery) {
  18686. this._isOcclusionQueryInProgress = false;
  18687. engine.deleteQuery(this._occlusionQuery);
  18688. this._occlusionQuery = null;
  18689. }
  18690. // Engine
  18691. engine.wipeCaches();
  18692. // Remove from scene
  18693. this.getScene().removeMesh(this);
  18694. if (disposeMaterialAndTextures) {
  18695. if (this.material) {
  18696. this.material.dispose(false, true);
  18697. }
  18698. }
  18699. if (!doNotRecurse) {
  18700. // Particles
  18701. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18702. if (this.getScene().particleSystems[index].emitter === this) {
  18703. this.getScene().particleSystems[index].dispose();
  18704. index--;
  18705. }
  18706. }
  18707. }
  18708. // facet data
  18709. if (this._facetDataEnabled) {
  18710. this.disableFacetData();
  18711. }
  18712. this.onAfterWorldMatrixUpdateObservable.clear();
  18713. this.onCollideObservable.clear();
  18714. this.onCollisionPositionChangeObservable.clear();
  18715. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18716. };
  18717. /**
  18718. * Adds the passed mesh as a child to the current mesh.
  18719. * Returns the AbstractMesh.
  18720. */
  18721. AbstractMesh.prototype.addChild = function (mesh) {
  18722. mesh.setParent(this);
  18723. return this;
  18724. };
  18725. /**
  18726. * Removes the passed mesh from the current mesh children list.
  18727. * Returns the AbstractMesh.
  18728. */
  18729. AbstractMesh.prototype.removeChild = function (mesh) {
  18730. mesh.setParent(null);
  18731. return this;
  18732. };
  18733. // Facet data
  18734. /**
  18735. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18736. * Returns the AbstractMesh.
  18737. */
  18738. AbstractMesh.prototype._initFacetData = function () {
  18739. if (!this._facetNormals) {
  18740. this._facetNormals = new Array();
  18741. }
  18742. if (!this._facetPositions) {
  18743. this._facetPositions = new Array();
  18744. }
  18745. if (!this._facetPartitioning) {
  18746. this._facetPartitioning = new Array();
  18747. }
  18748. this._facetNb = (this.getIndices().length / 3) | 0;
  18749. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18750. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18751. for (var f = 0; f < this._facetNb; f++) {
  18752. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18753. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18754. }
  18755. this._facetDataEnabled = true;
  18756. return this;
  18757. };
  18758. /**
  18759. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18760. * This method can be called within the render loop.
  18761. * 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.
  18762. * Returns the AbstractMesh.
  18763. */
  18764. AbstractMesh.prototype.updateFacetData = function () {
  18765. if (!this._facetDataEnabled) {
  18766. this._initFacetData();
  18767. }
  18768. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18769. var indices = this.getIndices();
  18770. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18771. var bInfo = this.getBoundingInfo();
  18772. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18773. // init arrays, matrix and sort function on first call
  18774. this._facetDepthSortEnabled = true;
  18775. if (indices instanceof Uint16Array) {
  18776. this._depthSortedIndices = new Uint16Array(indices);
  18777. }
  18778. else if (indices instanceof Uint32Array) {
  18779. this._depthSortedIndices = new Uint32Array(indices);
  18780. }
  18781. else {
  18782. var needs32bits = false;
  18783. for (var i = 0; i < indices.length; i++) {
  18784. if (indices[i] > 65535) {
  18785. needs32bits = true;
  18786. break;
  18787. }
  18788. }
  18789. if (needs32bits) {
  18790. this._depthSortedIndices = new Uint32Array(indices);
  18791. }
  18792. else {
  18793. this._depthSortedIndices = new Uint16Array(indices);
  18794. }
  18795. }
  18796. this._facetDepthSortFunction = function (f1, f2) {
  18797. return (f2.sqDistance - f1.sqDistance);
  18798. };
  18799. if (!this._facetDepthSortFrom) {
  18800. var camera = this.getScene().activeCamera;
  18801. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18802. }
  18803. this._depthSortedFacets = [];
  18804. for (var f = 0; f < this._facetNb; f++) {
  18805. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18806. this._depthSortedFacets.push(depthSortedFacet);
  18807. }
  18808. this._invertedMatrix = BABYLON.Matrix.Identity();
  18809. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18810. }
  18811. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18812. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18813. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18814. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18815. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18816. this._subDiv.max = this._partitioningSubdivisions;
  18817. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18818. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18819. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18820. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18821. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18822. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18823. // set the parameters for ComputeNormals()
  18824. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18825. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18826. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18827. this._facetParameters.bInfo = bInfo;
  18828. this._facetParameters.bbSize = this._bbSize;
  18829. this._facetParameters.subDiv = this._subDiv;
  18830. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18831. this._facetParameters.depthSort = this._facetDepthSort;
  18832. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18833. this.computeWorldMatrix(true);
  18834. this._worldMatrix.invertToRef(this._invertedMatrix);
  18835. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18836. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18837. }
  18838. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18839. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18840. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18841. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18842. var l = (this._depthSortedIndices.length / 3) | 0;
  18843. for (var f = 0; f < l; f++) {
  18844. var sind = this._depthSortedFacets[f].ind;
  18845. this._depthSortedIndices[f * 3] = indices[sind];
  18846. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18847. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18848. }
  18849. this.updateIndices(this._depthSortedIndices);
  18850. }
  18851. return this;
  18852. };
  18853. /**
  18854. * Returns the facetLocalNormals array.
  18855. * The normals are expressed in the mesh local space.
  18856. */
  18857. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18858. if (!this._facetNormals) {
  18859. this.updateFacetData();
  18860. }
  18861. return this._facetNormals;
  18862. };
  18863. /**
  18864. * Returns the facetLocalPositions array.
  18865. * The facet positions are expressed in the mesh local space.
  18866. */
  18867. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18868. if (!this._facetPositions) {
  18869. this.updateFacetData();
  18870. }
  18871. return this._facetPositions;
  18872. };
  18873. /**
  18874. * Returns the facetLocalPartioning array.
  18875. */
  18876. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18877. if (!this._facetPartitioning) {
  18878. this.updateFacetData();
  18879. }
  18880. return this._facetPartitioning;
  18881. };
  18882. /**
  18883. * Returns the i-th facet position in the world system.
  18884. * This method allocates a new Vector3 per call.
  18885. */
  18886. AbstractMesh.prototype.getFacetPosition = function (i) {
  18887. var pos = BABYLON.Vector3.Zero();
  18888. this.getFacetPositionToRef(i, pos);
  18889. return pos;
  18890. };
  18891. /**
  18892. * Sets the reference Vector3 with the i-th facet position in the world system.
  18893. * Returns the AbstractMesh.
  18894. */
  18895. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18896. var localPos = (this.getFacetLocalPositions())[i];
  18897. var world = this.getWorldMatrix();
  18898. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18899. return this;
  18900. };
  18901. /**
  18902. * Returns the i-th facet normal in the world system.
  18903. * This method allocates a new Vector3 per call.
  18904. */
  18905. AbstractMesh.prototype.getFacetNormal = function (i) {
  18906. var norm = BABYLON.Vector3.Zero();
  18907. this.getFacetNormalToRef(i, norm);
  18908. return norm;
  18909. };
  18910. /**
  18911. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18912. * Returns the AbstractMesh.
  18913. */
  18914. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18915. var localNorm = (this.getFacetLocalNormals())[i];
  18916. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18917. return this;
  18918. };
  18919. /**
  18920. * 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).
  18921. */
  18922. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18923. var bInfo = this.getBoundingInfo();
  18924. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18925. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18926. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18927. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18928. return null;
  18929. }
  18930. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18931. };
  18932. /**
  18933. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18934. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18935. * 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.
  18936. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18937. * 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.
  18938. */
  18939. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18940. if (checkFace === void 0) { checkFace = false; }
  18941. if (facing === void 0) { facing = true; }
  18942. var world = this.getWorldMatrix();
  18943. var invMat = BABYLON.Tmp.Matrix[5];
  18944. world.invertToRef(invMat);
  18945. var invVect = BABYLON.Tmp.Vector3[8];
  18946. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18947. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18948. if (projected) {
  18949. // tranform the local computed projected vector to world coordinates
  18950. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18951. }
  18952. return closest;
  18953. };
  18954. /**
  18955. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18956. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18957. * 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.
  18958. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18959. * 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.
  18960. */
  18961. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18962. if (checkFace === void 0) { checkFace = false; }
  18963. if (facing === void 0) { facing = true; }
  18964. var closest = null;
  18965. var tmpx = 0.0;
  18966. var tmpy = 0.0;
  18967. var tmpz = 0.0;
  18968. var d = 0.0; // tmp dot facet normal * facet position
  18969. var t0 = 0.0;
  18970. var projx = 0.0;
  18971. var projy = 0.0;
  18972. var projz = 0.0;
  18973. // Get all the facets in the same partitioning block than (x, y, z)
  18974. var facetPositions = this.getFacetLocalPositions();
  18975. var facetNormals = this.getFacetLocalNormals();
  18976. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18977. if (!facetsInBlock) {
  18978. return null;
  18979. }
  18980. // Get the closest facet to (x, y, z)
  18981. var shortest = Number.MAX_VALUE; // init distance vars
  18982. var tmpDistance = shortest;
  18983. var fib; // current facet in the block
  18984. var norm; // current facet normal
  18985. var p0; // current facet barycenter position
  18986. // loop on all the facets in the current partitioning block
  18987. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18988. fib = facetsInBlock[idx];
  18989. norm = facetNormals[fib];
  18990. p0 = facetPositions[fib];
  18991. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18992. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18993. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18994. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18995. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18996. projx = x + norm.x * t0;
  18997. projy = y + norm.y * t0;
  18998. projz = z + norm.z * t0;
  18999. tmpx = projx - x;
  19000. tmpy = projy - y;
  19001. tmpz = projz - z;
  19002. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  19003. if (tmpDistance < shortest) {
  19004. shortest = tmpDistance;
  19005. closest = fib;
  19006. if (projected) {
  19007. projected.x = projx;
  19008. projected.y = projy;
  19009. projected.z = projz;
  19010. }
  19011. }
  19012. }
  19013. }
  19014. return closest;
  19015. };
  19016. /**
  19017. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  19018. */
  19019. AbstractMesh.prototype.getFacetDataParameters = function () {
  19020. return this._facetParameters;
  19021. };
  19022. /**
  19023. * Disables the feature FacetData and frees the related memory.
  19024. * Returns the AbstractMesh.
  19025. */
  19026. AbstractMesh.prototype.disableFacetData = function () {
  19027. if (this._facetDataEnabled) {
  19028. this._facetDataEnabled = false;
  19029. this._facetPositions = new Array();
  19030. this._facetNormals = new Array();
  19031. this._facetPartitioning = new Array();
  19032. this._facetParameters = null;
  19033. this._depthSortedIndices = new Uint32Array(0);
  19034. }
  19035. return this;
  19036. };
  19037. /**
  19038. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  19039. * Returns the mesh.
  19040. */
  19041. AbstractMesh.prototype.updateIndices = function (indices) {
  19042. return this;
  19043. };
  19044. /**
  19045. * The mesh Geometry. Actually used by the Mesh object.
  19046. * Returns a blank geometry object.
  19047. */
  19048. /**
  19049. * Creates new normals data for the mesh.
  19050. * @param updatable.
  19051. */
  19052. AbstractMesh.prototype.createNormals = function (updatable) {
  19053. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19054. var indices = this.getIndices();
  19055. var normals;
  19056. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19057. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19058. }
  19059. else {
  19060. normals = [];
  19061. }
  19062. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  19063. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  19064. };
  19065. /**
  19066. * Align the mesh with a normal.
  19067. * Returns the mesh.
  19068. */
  19069. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  19070. if (!upDirection) {
  19071. upDirection = BABYLON.Axis.Y;
  19072. }
  19073. var axisX = BABYLON.Tmp.Vector3[0];
  19074. var axisZ = BABYLON.Tmp.Vector3[1];
  19075. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  19076. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  19077. if (this.rotationQuaternion) {
  19078. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  19079. }
  19080. else {
  19081. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  19082. }
  19083. return this;
  19084. };
  19085. AbstractMesh.prototype.checkOcclusionQuery = function () {
  19086. var engine = this.getEngine();
  19087. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  19088. this._isOccluded = false;
  19089. return;
  19090. }
  19091. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  19092. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  19093. if (isOcclusionQueryAvailable) {
  19094. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  19095. this._isOcclusionQueryInProgress = false;
  19096. this._occlusionInternalRetryCounter = 0;
  19097. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  19098. }
  19099. else {
  19100. this._occlusionInternalRetryCounter++;
  19101. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  19102. this._isOcclusionQueryInProgress = false;
  19103. this._occlusionInternalRetryCounter = 0;
  19104. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  19105. // if strict continue the last state of the object.
  19106. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  19107. }
  19108. else {
  19109. return;
  19110. }
  19111. }
  19112. }
  19113. var scene = this.getScene();
  19114. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  19115. if (!this._occlusionQuery) {
  19116. this._occlusionQuery = engine.createQuery();
  19117. }
  19118. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  19119. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  19120. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  19121. this._isOcclusionQueryInProgress = true;
  19122. };
  19123. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  19124. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  19125. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  19126. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  19127. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  19128. return AbstractMesh;
  19129. }(BABYLON.TransformNode));
  19130. BABYLON.AbstractMesh = AbstractMesh;
  19131. })(BABYLON || (BABYLON = {}));
  19132. //# sourceMappingURL=babylon.abstractMesh.js.map
  19133. var BABYLON;
  19134. (function (BABYLON) {
  19135. /**
  19136. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  19137. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  19138. * 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.
  19139. */
  19140. var Light = /** @class */ (function (_super) {
  19141. __extends(Light, _super);
  19142. /**
  19143. * Creates a Light object in the scene.
  19144. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19145. * @param name The firendly name of the light
  19146. * @param scene The scene the light belongs too
  19147. */
  19148. function Light(name, scene) {
  19149. var _this = _super.call(this, name, scene) || this;
  19150. /**
  19151. * Diffuse gives the basic color to an object.
  19152. */
  19153. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19154. /**
  19155. * Specular produces a highlight color on an object.
  19156. * Note: This is note affecting PBR materials.
  19157. */
  19158. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19159. /**
  19160. * Strength of the light.
  19161. * Note: By default it is define in the framework own unit.
  19162. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19163. */
  19164. _this.intensity = 1.0;
  19165. /**
  19166. * Defines how far from the source the light is impacting in scene units.
  19167. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19168. */
  19169. _this.range = Number.MAX_VALUE;
  19170. /**
  19171. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19172. * of light.
  19173. */
  19174. _this._photometricScale = 1.0;
  19175. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19176. _this._radius = 0.00001;
  19177. /**
  19178. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19179. * exceeding the number allowed of the materials.
  19180. */
  19181. _this.renderPriority = 0;
  19182. /**
  19183. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19184. * the current shadow generator.
  19185. */
  19186. _this.shadowEnabled = true;
  19187. _this._excludeWithLayerMask = 0;
  19188. _this._includeOnlyWithLayerMask = 0;
  19189. _this._lightmapMode = 0;
  19190. /**
  19191. * @ignore Internal use only.
  19192. */
  19193. _this._excludedMeshesIds = new Array();
  19194. /**
  19195. * @ignore Internal use only.
  19196. */
  19197. _this._includedOnlyMeshesIds = new Array();
  19198. _this.getScene().addLight(_this);
  19199. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19200. _this._buildUniformLayout();
  19201. _this.includedOnlyMeshes = new Array();
  19202. _this.excludedMeshes = new Array();
  19203. _this._resyncMeshes();
  19204. return _this;
  19205. }
  19206. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19207. /**
  19208. * If every light affecting the material is in this lightmapMode,
  19209. * material.lightmapTexture adds or multiplies
  19210. * (depends on material.useLightmapAsShadowmap)
  19211. * after every other light calculations.
  19212. */
  19213. get: function () {
  19214. return Light._LIGHTMAP_DEFAULT;
  19215. },
  19216. enumerable: true,
  19217. configurable: true
  19218. });
  19219. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19220. /**
  19221. * material.lightmapTexture as only diffuse lighting from this light
  19222. * adds only specular lighting from this light
  19223. * adds dynamic shadows
  19224. */
  19225. get: function () {
  19226. return Light._LIGHTMAP_SPECULAR;
  19227. },
  19228. enumerable: true,
  19229. configurable: true
  19230. });
  19231. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19232. /**
  19233. * material.lightmapTexture as only lighting
  19234. * no light calculation from this light
  19235. * only adds dynamic shadows from this light
  19236. */
  19237. get: function () {
  19238. return Light._LIGHTMAP_SHADOWSONLY;
  19239. },
  19240. enumerable: true,
  19241. configurable: true
  19242. });
  19243. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19244. /**
  19245. * Each light type uses the default quantity according to its type:
  19246. * point/spot lights use luminous intensity
  19247. * directional lights use illuminance
  19248. */
  19249. get: function () {
  19250. return Light._INTENSITYMODE_AUTOMATIC;
  19251. },
  19252. enumerable: true,
  19253. configurable: true
  19254. });
  19255. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19256. /**
  19257. * lumen (lm)
  19258. */
  19259. get: function () {
  19260. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19261. },
  19262. enumerable: true,
  19263. configurable: true
  19264. });
  19265. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19266. /**
  19267. * candela (lm/sr)
  19268. */
  19269. get: function () {
  19270. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19271. },
  19272. enumerable: true,
  19273. configurable: true
  19274. });
  19275. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19276. /**
  19277. * lux (lm/m^2)
  19278. */
  19279. get: function () {
  19280. return Light._INTENSITYMODE_ILLUMINANCE;
  19281. },
  19282. enumerable: true,
  19283. configurable: true
  19284. });
  19285. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19286. /**
  19287. * nit (cd/m^2)
  19288. */
  19289. get: function () {
  19290. return Light._INTENSITYMODE_LUMINANCE;
  19291. },
  19292. enumerable: true,
  19293. configurable: true
  19294. });
  19295. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19296. /**
  19297. * Light type const id of the point light.
  19298. */
  19299. get: function () {
  19300. return Light._LIGHTTYPEID_POINTLIGHT;
  19301. },
  19302. enumerable: true,
  19303. configurable: true
  19304. });
  19305. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19306. /**
  19307. * Light type const id of the directional light.
  19308. */
  19309. get: function () {
  19310. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19311. },
  19312. enumerable: true,
  19313. configurable: true
  19314. });
  19315. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19316. /**
  19317. * Light type const id of the spot light.
  19318. */
  19319. get: function () {
  19320. return Light._LIGHTTYPEID_SPOTLIGHT;
  19321. },
  19322. enumerable: true,
  19323. configurable: true
  19324. });
  19325. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19326. /**
  19327. * Light type const id of the hemispheric light.
  19328. */
  19329. get: function () {
  19330. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19331. },
  19332. enumerable: true,
  19333. configurable: true
  19334. });
  19335. Object.defineProperty(Light.prototype, "intensityMode", {
  19336. /**
  19337. * Gets the photometric scale used to interpret the intensity.
  19338. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19339. */
  19340. get: function () {
  19341. return this._intensityMode;
  19342. },
  19343. /**
  19344. * Sets the photometric scale used to interpret the intensity.
  19345. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19346. */
  19347. set: function (value) {
  19348. this._intensityMode = value;
  19349. this._computePhotometricScale();
  19350. },
  19351. enumerable: true,
  19352. configurable: true
  19353. });
  19354. ;
  19355. ;
  19356. Object.defineProperty(Light.prototype, "radius", {
  19357. /**
  19358. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19359. */
  19360. get: function () {
  19361. return this._radius;
  19362. },
  19363. /**
  19364. * sets the light radius used by PBR Materials to simulate soft area lights.
  19365. */
  19366. set: function (value) {
  19367. this._radius = value;
  19368. this._computePhotometricScale();
  19369. },
  19370. enumerable: true,
  19371. configurable: true
  19372. });
  19373. ;
  19374. ;
  19375. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19376. /**
  19377. * Gets the only meshes impacted by this light.
  19378. */
  19379. get: function () {
  19380. return this._includedOnlyMeshes;
  19381. },
  19382. /**
  19383. * Sets the only meshes impacted by this light.
  19384. */
  19385. set: function (value) {
  19386. this._includedOnlyMeshes = value;
  19387. this._hookArrayForIncludedOnly(value);
  19388. },
  19389. enumerable: true,
  19390. configurable: true
  19391. });
  19392. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19393. /**
  19394. * Gets the meshes not impacted by this light.
  19395. */
  19396. get: function () {
  19397. return this._excludedMeshes;
  19398. },
  19399. /**
  19400. * Sets the meshes not impacted by this light.
  19401. */
  19402. set: function (value) {
  19403. this._excludedMeshes = value;
  19404. this._hookArrayForExcluded(value);
  19405. },
  19406. enumerable: true,
  19407. configurable: true
  19408. });
  19409. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19410. /**
  19411. * Gets the layer id use to find what meshes are not impacted by the light.
  19412. * Inactive if 0
  19413. */
  19414. get: function () {
  19415. return this._excludeWithLayerMask;
  19416. },
  19417. /**
  19418. * Sets the layer id use to find what meshes are not impacted by the light.
  19419. * Inactive if 0
  19420. */
  19421. set: function (value) {
  19422. this._excludeWithLayerMask = value;
  19423. this._resyncMeshes();
  19424. },
  19425. enumerable: true,
  19426. configurable: true
  19427. });
  19428. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19429. /**
  19430. * Gets the layer id use to find what meshes are impacted by the light.
  19431. * Inactive if 0
  19432. */
  19433. get: function () {
  19434. return this._includeOnlyWithLayerMask;
  19435. },
  19436. /**
  19437. * Sets the layer id use to find what meshes are impacted by the light.
  19438. * Inactive if 0
  19439. */
  19440. set: function (value) {
  19441. this._includeOnlyWithLayerMask = value;
  19442. this._resyncMeshes();
  19443. },
  19444. enumerable: true,
  19445. configurable: true
  19446. });
  19447. Object.defineProperty(Light.prototype, "lightmapMode", {
  19448. /**
  19449. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19450. */
  19451. get: function () {
  19452. return this._lightmapMode;
  19453. },
  19454. /**
  19455. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19456. */
  19457. set: function (value) {
  19458. if (this._lightmapMode === value) {
  19459. return;
  19460. }
  19461. this._lightmapMode = value;
  19462. this._markMeshesAsLightDirty();
  19463. },
  19464. enumerable: true,
  19465. configurable: true
  19466. });
  19467. /**
  19468. * Returns the string "Light".
  19469. * @returns the class name
  19470. */
  19471. Light.prototype.getClassName = function () {
  19472. return "Light";
  19473. };
  19474. /**
  19475. * Converts the light information to a readable string for debug purpose.
  19476. * @param fullDetails Supports for multiple levels of logging within scene loading
  19477. * @returns the human readable light info
  19478. */
  19479. Light.prototype.toString = function (fullDetails) {
  19480. var ret = "Name: " + this.name;
  19481. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19482. if (this.animations) {
  19483. for (var i = 0; i < this.animations.length; i++) {
  19484. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19485. }
  19486. }
  19487. if (fullDetails) {
  19488. }
  19489. return ret;
  19490. };
  19491. /**
  19492. * Set the enabled state of this node.
  19493. * @param value - the new enabled state
  19494. * @see isEnabled
  19495. */
  19496. Light.prototype.setEnabled = function (value) {
  19497. _super.prototype.setEnabled.call(this, value);
  19498. this._resyncMeshes();
  19499. };
  19500. /**
  19501. * Returns the Light associated shadow generator if any.
  19502. * @return the associated shadow generator.
  19503. */
  19504. Light.prototype.getShadowGenerator = function () {
  19505. return this._shadowGenerator;
  19506. };
  19507. /**
  19508. * Returns a Vector3, the absolute light position in the World.
  19509. * @returns the world space position of the light
  19510. */
  19511. Light.prototype.getAbsolutePosition = function () {
  19512. return BABYLON.Vector3.Zero();
  19513. };
  19514. /**
  19515. * Specifies if the light will affect the passed mesh.
  19516. * @param mesh The mesh to test against the light
  19517. * @return true the mesh is affected otherwise, false.
  19518. */
  19519. Light.prototype.canAffectMesh = function (mesh) {
  19520. if (!mesh) {
  19521. return true;
  19522. }
  19523. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19524. return false;
  19525. }
  19526. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19527. return false;
  19528. }
  19529. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19530. return false;
  19531. }
  19532. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19533. return false;
  19534. }
  19535. return true;
  19536. };
  19537. /**
  19538. * Computes and Returns the light World matrix.
  19539. * @returns the world matrix
  19540. */
  19541. Light.prototype.getWorldMatrix = function () {
  19542. this._currentRenderId = this.getScene().getRenderId();
  19543. var worldMatrix = this._getWorldMatrix();
  19544. if (this.parent && this.parent.getWorldMatrix) {
  19545. if (!this._parentedWorldMatrix) {
  19546. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19547. }
  19548. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19549. this._markSyncedWithParent();
  19550. return this._parentedWorldMatrix;
  19551. }
  19552. return worldMatrix;
  19553. };
  19554. /**
  19555. * Sort function to order lights for rendering.
  19556. * @param a First Light object to compare to second.
  19557. * @param b Second Light object to compare first.
  19558. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19559. */
  19560. Light.CompareLightsPriority = function (a, b) {
  19561. //shadow-casting lights have priority over non-shadow-casting lights
  19562. //the renderPrioirty is a secondary sort criterion
  19563. if (a.shadowEnabled !== b.shadowEnabled) {
  19564. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19565. }
  19566. return b.renderPriority - a.renderPriority;
  19567. };
  19568. /**
  19569. * Releases resources associated with this node.
  19570. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19571. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19572. */
  19573. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19574. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19575. if (this._shadowGenerator) {
  19576. this._shadowGenerator.dispose();
  19577. this._shadowGenerator = null;
  19578. }
  19579. // Animations
  19580. this.getScene().stopAnimation(this);
  19581. // Remove from meshes
  19582. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19583. var mesh = _a[_i];
  19584. mesh._removeLightSource(this);
  19585. }
  19586. this._uniformBuffer.dispose();
  19587. // Remove from scene
  19588. this.getScene().removeLight(this);
  19589. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19590. };
  19591. /**
  19592. * Returns the light type ID (integer).
  19593. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19594. */
  19595. Light.prototype.getTypeID = function () {
  19596. return 0;
  19597. };
  19598. /**
  19599. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19600. * @returns the scaled intensity in intensity mode unit
  19601. */
  19602. Light.prototype.getScaledIntensity = function () {
  19603. return this._photometricScale * this.intensity;
  19604. };
  19605. /**
  19606. * Returns a new Light object, named "name", from the current one.
  19607. * @param name The name of the cloned light
  19608. * @returns the new created light
  19609. */
  19610. Light.prototype.clone = function (name) {
  19611. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19612. if (!constructor) {
  19613. return null;
  19614. }
  19615. return BABYLON.SerializationHelper.Clone(constructor, this);
  19616. };
  19617. /**
  19618. * Serializes the current light into a Serialization object.
  19619. * @returns the serialized object.
  19620. */
  19621. Light.prototype.serialize = function () {
  19622. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19623. // Type
  19624. serializationObject.type = this.getTypeID();
  19625. // Parent
  19626. if (this.parent) {
  19627. serializationObject.parentId = this.parent.id;
  19628. }
  19629. // Inclusion / exclusions
  19630. if (this.excludedMeshes.length > 0) {
  19631. serializationObject.excludedMeshesIds = [];
  19632. this.excludedMeshes.forEach(function (mesh) {
  19633. serializationObject.excludedMeshesIds.push(mesh.id);
  19634. });
  19635. }
  19636. if (this.includedOnlyMeshes.length > 0) {
  19637. serializationObject.includedOnlyMeshesIds = [];
  19638. this.includedOnlyMeshes.forEach(function (mesh) {
  19639. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19640. });
  19641. }
  19642. // Animations
  19643. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19644. serializationObject.ranges = this.serializeAnimationRanges();
  19645. return serializationObject;
  19646. };
  19647. /**
  19648. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19649. * This new light is named "name" and added to the passed scene.
  19650. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19651. * @param name The friendly name of the light
  19652. * @param scene The scene the new light will belong to
  19653. * @returns the constructor function
  19654. */
  19655. Light.GetConstructorFromName = function (type, name, scene) {
  19656. switch (type) {
  19657. case 0:
  19658. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19659. case 1:
  19660. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19661. case 2:
  19662. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19663. case 3:
  19664. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19665. }
  19666. return null;
  19667. };
  19668. /**
  19669. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19670. * @param parsedLight The JSON representation of the light
  19671. * @param scene The scene to create the parsed light in
  19672. * @returns the created light after parsing
  19673. */
  19674. Light.Parse = function (parsedLight, scene) {
  19675. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19676. if (!constructor) {
  19677. return null;
  19678. }
  19679. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19680. // Inclusion / exclusions
  19681. if (parsedLight.excludedMeshesIds) {
  19682. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19683. }
  19684. if (parsedLight.includedOnlyMeshesIds) {
  19685. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19686. }
  19687. // Parent
  19688. if (parsedLight.parentId) {
  19689. light._waitingParentId = parsedLight.parentId;
  19690. }
  19691. // Animations
  19692. if (parsedLight.animations) {
  19693. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19694. var parsedAnimation = parsedLight.animations[animationIndex];
  19695. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19696. }
  19697. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19698. }
  19699. if (parsedLight.autoAnimate) {
  19700. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19701. }
  19702. return light;
  19703. };
  19704. Light.prototype._hookArrayForExcluded = function (array) {
  19705. var _this = this;
  19706. var oldPush = array.push;
  19707. array.push = function () {
  19708. var items = [];
  19709. for (var _i = 0; _i < arguments.length; _i++) {
  19710. items[_i] = arguments[_i];
  19711. }
  19712. var result = oldPush.apply(array, items);
  19713. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19714. var item = items_1[_a];
  19715. item._resyncLighSource(_this);
  19716. }
  19717. return result;
  19718. };
  19719. var oldSplice = array.splice;
  19720. array.splice = function (index, deleteCount) {
  19721. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19722. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19723. var item = deleted_1[_i];
  19724. item._resyncLighSource(_this);
  19725. }
  19726. return deleted;
  19727. };
  19728. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19729. var item = array_1[_i];
  19730. item._resyncLighSource(this);
  19731. }
  19732. };
  19733. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19734. var _this = this;
  19735. var oldPush = array.push;
  19736. array.push = function () {
  19737. var items = [];
  19738. for (var _i = 0; _i < arguments.length; _i++) {
  19739. items[_i] = arguments[_i];
  19740. }
  19741. var result = oldPush.apply(array, items);
  19742. _this._resyncMeshes();
  19743. return result;
  19744. };
  19745. var oldSplice = array.splice;
  19746. array.splice = function (index, deleteCount) {
  19747. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19748. _this._resyncMeshes();
  19749. return deleted;
  19750. };
  19751. this._resyncMeshes();
  19752. };
  19753. Light.prototype._resyncMeshes = function () {
  19754. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19755. var mesh = _a[_i];
  19756. mesh._resyncLighSource(this);
  19757. }
  19758. };
  19759. /**
  19760. * Forces the meshes to update their light related information in their rendering used effects
  19761. * @ignore Internal Use Only
  19762. */
  19763. Light.prototype._markMeshesAsLightDirty = function () {
  19764. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19765. var mesh = _a[_i];
  19766. if (mesh._lightSources.indexOf(this) !== -1) {
  19767. mesh._markSubMeshesAsLightDirty();
  19768. }
  19769. }
  19770. };
  19771. /**
  19772. * Recomputes the cached photometric scale if needed.
  19773. */
  19774. Light.prototype._computePhotometricScale = function () {
  19775. this._photometricScale = this._getPhotometricScale();
  19776. this.getScene().resetCachedMaterial();
  19777. };
  19778. /**
  19779. * Returns the Photometric Scale according to the light type and intensity mode.
  19780. */
  19781. Light.prototype._getPhotometricScale = function () {
  19782. var photometricScale = 0.0;
  19783. var lightTypeID = this.getTypeID();
  19784. //get photometric mode
  19785. var photometricMode = this.intensityMode;
  19786. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19787. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19788. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19789. }
  19790. else {
  19791. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19792. }
  19793. }
  19794. //compute photometric scale
  19795. switch (lightTypeID) {
  19796. case Light.LIGHTTYPEID_POINTLIGHT:
  19797. case Light.LIGHTTYPEID_SPOTLIGHT:
  19798. switch (photometricMode) {
  19799. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19800. photometricScale = 1.0 / (4.0 * Math.PI);
  19801. break;
  19802. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19803. photometricScale = 1.0;
  19804. break;
  19805. case Light.INTENSITYMODE_LUMINANCE:
  19806. photometricScale = this.radius * this.radius;
  19807. break;
  19808. }
  19809. break;
  19810. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19811. switch (photometricMode) {
  19812. case Light.INTENSITYMODE_ILLUMINANCE:
  19813. photometricScale = 1.0;
  19814. break;
  19815. case Light.INTENSITYMODE_LUMINANCE:
  19816. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19817. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19818. var apexAngleRadians = this.radius;
  19819. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19820. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19821. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19822. photometricScale = solidAngle;
  19823. break;
  19824. }
  19825. break;
  19826. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19827. // No fall off in hemisperic light.
  19828. photometricScale = 1.0;
  19829. break;
  19830. }
  19831. return photometricScale;
  19832. };
  19833. /**
  19834. * Reorder the light in the scene according to their defined priority.
  19835. * @ignore Internal Use Only
  19836. */
  19837. Light.prototype._reorderLightsInScene = function () {
  19838. var scene = this.getScene();
  19839. if (this._renderPriority != 0) {
  19840. scene.requireLightSorting = true;
  19841. }
  19842. this.getScene().sortLightsByPriority();
  19843. };
  19844. //lightmapMode Consts
  19845. Light._LIGHTMAP_DEFAULT = 0;
  19846. Light._LIGHTMAP_SPECULAR = 1;
  19847. Light._LIGHTMAP_SHADOWSONLY = 2;
  19848. // Intensity Mode Consts
  19849. Light._INTENSITYMODE_AUTOMATIC = 0;
  19850. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19851. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19852. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19853. Light._INTENSITYMODE_LUMINANCE = 4;
  19854. // Light types ids const.
  19855. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19856. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19857. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19858. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19859. __decorate([
  19860. BABYLON.serializeAsColor3()
  19861. ], Light.prototype, "diffuse", void 0);
  19862. __decorate([
  19863. BABYLON.serializeAsColor3()
  19864. ], Light.prototype, "specular", void 0);
  19865. __decorate([
  19866. BABYLON.serialize()
  19867. ], Light.prototype, "intensity", void 0);
  19868. __decorate([
  19869. BABYLON.serialize()
  19870. ], Light.prototype, "range", void 0);
  19871. __decorate([
  19872. BABYLON.serialize()
  19873. ], Light.prototype, "intensityMode", null);
  19874. __decorate([
  19875. BABYLON.serialize()
  19876. ], Light.prototype, "radius", null);
  19877. __decorate([
  19878. BABYLON.serialize()
  19879. ], Light.prototype, "_renderPriority", void 0);
  19880. __decorate([
  19881. BABYLON.expandToProperty("_reorderLightsInScene")
  19882. ], Light.prototype, "renderPriority", void 0);
  19883. __decorate([
  19884. BABYLON.serialize()
  19885. ], Light.prototype, "shadowEnabled", void 0);
  19886. __decorate([
  19887. BABYLON.serialize("excludeWithLayerMask")
  19888. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19889. __decorate([
  19890. BABYLON.serialize("includeOnlyWithLayerMask")
  19891. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19892. __decorate([
  19893. BABYLON.serialize("lightmapMode")
  19894. ], Light.prototype, "_lightmapMode", void 0);
  19895. return Light;
  19896. }(BABYLON.Node));
  19897. BABYLON.Light = Light;
  19898. })(BABYLON || (BABYLON = {}));
  19899. //# sourceMappingURL=babylon.light.js.map
  19900. var BABYLON;
  19901. (function (BABYLON) {
  19902. var Camera = /** @class */ (function (_super) {
  19903. __extends(Camera, _super);
  19904. function Camera(name, position, scene) {
  19905. var _this = _super.call(this, name, scene) || this;
  19906. /**
  19907. * The vector the camera should consider as up.
  19908. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19909. */
  19910. _this.upVector = BABYLON.Vector3.Up();
  19911. _this.orthoLeft = null;
  19912. _this.orthoRight = null;
  19913. _this.orthoBottom = null;
  19914. _this.orthoTop = null;
  19915. /**
  19916. * FOV is set in Radians. (default is 0.8)
  19917. */
  19918. _this.fov = 0.8;
  19919. _this.minZ = 1;
  19920. _this.maxZ = 10000.0;
  19921. _this.inertia = 0.9;
  19922. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19923. _this.isIntermediate = false;
  19924. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19925. /**
  19926. * Restricts the camera to viewing objects with the same layerMask.
  19927. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19928. */
  19929. _this.layerMask = 0x0FFFFFFF;
  19930. /**
  19931. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19932. */
  19933. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19934. // Camera rig members
  19935. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19936. _this._rigCameras = new Array();
  19937. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19938. _this._skipRendering = false;
  19939. _this.customRenderTargets = new Array();
  19940. // Observables
  19941. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19942. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19943. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19944. _this.onRestoreStateObservable = new BABYLON.Observable();
  19945. // Cache
  19946. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19947. _this._projectionMatrix = new BABYLON.Matrix();
  19948. _this._doNotComputeProjectionMatrix = false;
  19949. _this._postProcesses = new Array();
  19950. _this._transformMatrix = BABYLON.Matrix.Zero();
  19951. _this._activeMeshes = new BABYLON.SmartArray(256);
  19952. _this._globalPosition = BABYLON.Vector3.Zero();
  19953. _this._refreshFrustumPlanes = true;
  19954. _this.getScene().addCamera(_this);
  19955. if (!_this.getScene().activeCamera) {
  19956. _this.getScene().activeCamera = _this;
  19957. }
  19958. _this.position = position;
  19959. return _this;
  19960. }
  19961. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19962. get: function () {
  19963. return Camera._PERSPECTIVE_CAMERA;
  19964. },
  19965. enumerable: true,
  19966. configurable: true
  19967. });
  19968. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19969. get: function () {
  19970. return Camera._ORTHOGRAPHIC_CAMERA;
  19971. },
  19972. enumerable: true,
  19973. configurable: true
  19974. });
  19975. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19976. /**
  19977. * This is the default FOV mode for perspective cameras.
  19978. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19979. *
  19980. */
  19981. get: function () {
  19982. return Camera._FOVMODE_VERTICAL_FIXED;
  19983. },
  19984. enumerable: true,
  19985. configurable: true
  19986. });
  19987. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19988. /**
  19989. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19990. *
  19991. */
  19992. get: function () {
  19993. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19994. },
  19995. enumerable: true,
  19996. configurable: true
  19997. });
  19998. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19999. get: function () {
  20000. return Camera._RIG_MODE_NONE;
  20001. },
  20002. enumerable: true,
  20003. configurable: true
  20004. });
  20005. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  20006. get: function () {
  20007. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  20008. },
  20009. enumerable: true,
  20010. configurable: true
  20011. });
  20012. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  20013. get: function () {
  20014. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  20015. },
  20016. enumerable: true,
  20017. configurable: true
  20018. });
  20019. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  20020. get: function () {
  20021. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20022. },
  20023. enumerable: true,
  20024. configurable: true
  20025. });
  20026. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  20027. get: function () {
  20028. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  20029. },
  20030. enumerable: true,
  20031. configurable: true
  20032. });
  20033. Object.defineProperty(Camera, "RIG_MODE_VR", {
  20034. get: function () {
  20035. return Camera._RIG_MODE_VR;
  20036. },
  20037. enumerable: true,
  20038. configurable: true
  20039. });
  20040. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  20041. get: function () {
  20042. return Camera._RIG_MODE_WEBVR;
  20043. },
  20044. enumerable: true,
  20045. configurable: true
  20046. });
  20047. /**
  20048. * Store current camera state (fov, position, etc..)
  20049. */
  20050. Camera.prototype.storeState = function () {
  20051. this._stateStored = true;
  20052. this._storedFov = this.fov;
  20053. return this;
  20054. };
  20055. /**
  20056. * Restores the camera state values if it has been stored. You must call storeState() first
  20057. */
  20058. Camera.prototype._restoreStateValues = function () {
  20059. if (!this._stateStored) {
  20060. return false;
  20061. }
  20062. this.fov = this._storedFov;
  20063. return true;
  20064. };
  20065. /**
  20066. * Restored camera state. You must call storeState() first
  20067. */
  20068. Camera.prototype.restoreState = function () {
  20069. if (this._restoreStateValues()) {
  20070. this.onRestoreStateObservable.notifyObservers(this);
  20071. return true;
  20072. }
  20073. return false;
  20074. };
  20075. Camera.prototype.getClassName = function () {
  20076. return "Camera";
  20077. };
  20078. /**
  20079. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20080. */
  20081. Camera.prototype.toString = function (fullDetails) {
  20082. var ret = "Name: " + this.name;
  20083. ret += ", type: " + this.getClassName();
  20084. if (this.animations) {
  20085. for (var i = 0; i < this.animations.length; i++) {
  20086. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20087. }
  20088. }
  20089. if (fullDetails) {
  20090. }
  20091. return ret;
  20092. };
  20093. Object.defineProperty(Camera.prototype, "globalPosition", {
  20094. get: function () {
  20095. return this._globalPosition;
  20096. },
  20097. enumerable: true,
  20098. configurable: true
  20099. });
  20100. Camera.prototype.getActiveMeshes = function () {
  20101. return this._activeMeshes;
  20102. };
  20103. Camera.prototype.isActiveMesh = function (mesh) {
  20104. return (this._activeMeshes.indexOf(mesh) !== -1);
  20105. };
  20106. //Cache
  20107. Camera.prototype._initCache = function () {
  20108. _super.prototype._initCache.call(this);
  20109. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20110. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20111. this._cache.mode = undefined;
  20112. this._cache.minZ = undefined;
  20113. this._cache.maxZ = undefined;
  20114. this._cache.fov = undefined;
  20115. this._cache.fovMode = undefined;
  20116. this._cache.aspectRatio = undefined;
  20117. this._cache.orthoLeft = undefined;
  20118. this._cache.orthoRight = undefined;
  20119. this._cache.orthoBottom = undefined;
  20120. this._cache.orthoTop = undefined;
  20121. this._cache.renderWidth = undefined;
  20122. this._cache.renderHeight = undefined;
  20123. };
  20124. Camera.prototype._updateCache = function (ignoreParentClass) {
  20125. if (!ignoreParentClass) {
  20126. _super.prototype._updateCache.call(this);
  20127. }
  20128. this._cache.position.copyFrom(this.position);
  20129. this._cache.upVector.copyFrom(this.upVector);
  20130. };
  20131. // Synchronized
  20132. Camera.prototype._isSynchronized = function () {
  20133. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  20134. };
  20135. Camera.prototype._isSynchronizedViewMatrix = function () {
  20136. if (!_super.prototype._isSynchronized.call(this))
  20137. return false;
  20138. return this._cache.position.equals(this.position)
  20139. && this._cache.upVector.equals(this.upVector)
  20140. && this.isSynchronizedWithParent();
  20141. };
  20142. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  20143. var check = this._cache.mode === this.mode
  20144. && this._cache.minZ === this.minZ
  20145. && this._cache.maxZ === this.maxZ;
  20146. if (!check) {
  20147. return false;
  20148. }
  20149. var engine = this.getEngine();
  20150. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20151. check = this._cache.fov === this.fov
  20152. && this._cache.fovMode === this.fovMode
  20153. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20154. }
  20155. else {
  20156. check = this._cache.orthoLeft === this.orthoLeft
  20157. && this._cache.orthoRight === this.orthoRight
  20158. && this._cache.orthoBottom === this.orthoBottom
  20159. && this._cache.orthoTop === this.orthoTop
  20160. && this._cache.renderWidth === engine.getRenderWidth()
  20161. && this._cache.renderHeight === engine.getRenderHeight();
  20162. }
  20163. return check;
  20164. };
  20165. // Controls
  20166. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20167. };
  20168. Camera.prototype.detachControl = function (element) {
  20169. };
  20170. Camera.prototype.update = function () {
  20171. this._checkInputs();
  20172. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20173. this._updateRigCameras();
  20174. }
  20175. };
  20176. Camera.prototype._checkInputs = function () {
  20177. this.onAfterCheckInputsObservable.notifyObservers(this);
  20178. };
  20179. Object.defineProperty(Camera.prototype, "rigCameras", {
  20180. get: function () {
  20181. return this._rigCameras;
  20182. },
  20183. enumerable: true,
  20184. configurable: true
  20185. });
  20186. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20187. get: function () {
  20188. return this._rigPostProcess;
  20189. },
  20190. enumerable: true,
  20191. configurable: true
  20192. });
  20193. /**
  20194. * Internal, gets the first post proces.
  20195. * @returns the first post process to be run on this camera.
  20196. */
  20197. Camera.prototype._getFirstPostProcess = function () {
  20198. for (var pp in this._postProcesses) {
  20199. if (this._postProcesses[pp] !== null) {
  20200. return this._postProcesses[pp];
  20201. }
  20202. }
  20203. return null;
  20204. };
  20205. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20206. // invalidate framebuffer
  20207. var firstPostProcess = this._getFirstPostProcess();
  20208. if (firstPostProcess) {
  20209. firstPostProcess.markTextureDirty();
  20210. }
  20211. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20212. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20213. var cam = this._rigCameras[i];
  20214. var rigPostProcess = cam._rigPostProcess;
  20215. // for VR rig, there does not have to be a post process
  20216. if (rigPostProcess) {
  20217. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20218. if (isPass) {
  20219. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20220. cam.isIntermediate = this._postProcesses.length === 0;
  20221. }
  20222. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20223. rigPostProcess.markTextureDirty();
  20224. }
  20225. else {
  20226. cam._postProcesses = this._postProcesses.slice(0);
  20227. }
  20228. }
  20229. };
  20230. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20231. if (insertAt === void 0) { insertAt = null; }
  20232. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20233. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20234. return 0;
  20235. }
  20236. if (insertAt == null || insertAt < 0) {
  20237. this._postProcesses.push(postProcess);
  20238. }
  20239. else if (this._postProcesses[insertAt] === null) {
  20240. this._postProcesses[insertAt] = postProcess;
  20241. }
  20242. else {
  20243. this._postProcesses.splice(insertAt, 0, postProcess);
  20244. }
  20245. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20246. return this._postProcesses.indexOf(postProcess);
  20247. };
  20248. Camera.prototype.detachPostProcess = function (postProcess) {
  20249. var idx = this._postProcesses.indexOf(postProcess);
  20250. if (idx !== -1) {
  20251. this._postProcesses[idx] = null;
  20252. }
  20253. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20254. };
  20255. Camera.prototype.getWorldMatrix = function () {
  20256. if (!this._worldMatrix) {
  20257. this._worldMatrix = BABYLON.Matrix.Identity();
  20258. }
  20259. var viewMatrix = this.getViewMatrix();
  20260. viewMatrix.invertToRef(this._worldMatrix);
  20261. return this._worldMatrix;
  20262. };
  20263. Camera.prototype._getViewMatrix = function () {
  20264. return BABYLON.Matrix.Identity();
  20265. };
  20266. Camera.prototype.getViewMatrix = function (force) {
  20267. if (!force && this._isSynchronizedViewMatrix()) {
  20268. return this._computedViewMatrix;
  20269. }
  20270. this.updateCache();
  20271. this._computedViewMatrix = this._getViewMatrix();
  20272. this._currentRenderId = this.getScene().getRenderId();
  20273. this._refreshFrustumPlanes = true;
  20274. if (!this.parent || !this.parent.getWorldMatrix) {
  20275. this._globalPosition.copyFrom(this.position);
  20276. }
  20277. else {
  20278. if (!this._worldMatrix) {
  20279. this._worldMatrix = BABYLON.Matrix.Identity();
  20280. }
  20281. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20282. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20283. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20284. this._computedViewMatrix.invert();
  20285. this._markSyncedWithParent();
  20286. }
  20287. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20288. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20289. }
  20290. this.onViewMatrixChangedObservable.notifyObservers(this);
  20291. return this._computedViewMatrix;
  20292. };
  20293. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20294. this._doNotComputeProjectionMatrix = true;
  20295. if (projection !== undefined) {
  20296. this._projectionMatrix = projection;
  20297. }
  20298. };
  20299. ;
  20300. Camera.prototype.unfreezeProjectionMatrix = function () {
  20301. this._doNotComputeProjectionMatrix = false;
  20302. };
  20303. ;
  20304. Camera.prototype.getProjectionMatrix = function (force) {
  20305. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20306. return this._projectionMatrix;
  20307. }
  20308. // Cache
  20309. this._cache.mode = this.mode;
  20310. this._cache.minZ = this.minZ;
  20311. this._cache.maxZ = this.maxZ;
  20312. // Matrix
  20313. this._refreshFrustumPlanes = true;
  20314. var engine = this.getEngine();
  20315. var scene = this.getScene();
  20316. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20317. this._cache.fov = this.fov;
  20318. this._cache.fovMode = this.fovMode;
  20319. this._cache.aspectRatio = engine.getAspectRatio(this);
  20320. if (this.minZ <= 0) {
  20321. this.minZ = 0.1;
  20322. }
  20323. if (scene.useRightHandedSystem) {
  20324. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20325. }
  20326. else {
  20327. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20328. }
  20329. }
  20330. else {
  20331. var halfWidth = engine.getRenderWidth() / 2.0;
  20332. var halfHeight = engine.getRenderHeight() / 2.0;
  20333. if (scene.useRightHandedSystem) {
  20334. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20335. }
  20336. else {
  20337. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20338. }
  20339. this._cache.orthoLeft = this.orthoLeft;
  20340. this._cache.orthoRight = this.orthoRight;
  20341. this._cache.orthoBottom = this.orthoBottom;
  20342. this._cache.orthoTop = this.orthoTop;
  20343. this._cache.renderWidth = engine.getRenderWidth();
  20344. this._cache.renderHeight = engine.getRenderHeight();
  20345. }
  20346. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20347. return this._projectionMatrix;
  20348. };
  20349. Camera.prototype.getTranformationMatrix = function () {
  20350. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20351. return this._transformMatrix;
  20352. };
  20353. Camera.prototype.updateFrustumPlanes = function () {
  20354. if (!this._refreshFrustumPlanes) {
  20355. return;
  20356. }
  20357. this.getTranformationMatrix();
  20358. if (!this._frustumPlanes) {
  20359. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20360. }
  20361. else {
  20362. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20363. }
  20364. this._refreshFrustumPlanes = false;
  20365. };
  20366. Camera.prototype.isInFrustum = function (target) {
  20367. this.updateFrustumPlanes();
  20368. return target.isInFrustum(this._frustumPlanes);
  20369. };
  20370. Camera.prototype.isCompletelyInFrustum = function (target) {
  20371. this.updateFrustumPlanes();
  20372. return target.isCompletelyInFrustum(this._frustumPlanes);
  20373. };
  20374. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20375. if (length === void 0) { length = 100; }
  20376. if (!transform) {
  20377. transform = this.getWorldMatrix();
  20378. }
  20379. if (!origin) {
  20380. origin = this.position;
  20381. }
  20382. var forward = new BABYLON.Vector3(0, 0, 1);
  20383. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20384. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20385. return new BABYLON.Ray(origin, direction, length);
  20386. };
  20387. /**
  20388. * Releases resources associated with this node.
  20389. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20390. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20391. */
  20392. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20393. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20394. // Observables
  20395. this.onViewMatrixChangedObservable.clear();
  20396. this.onProjectionMatrixChangedObservable.clear();
  20397. this.onAfterCheckInputsObservable.clear();
  20398. this.onRestoreStateObservable.clear();
  20399. // Inputs
  20400. if (this.inputs) {
  20401. this.inputs.clear();
  20402. }
  20403. // Animations
  20404. this.getScene().stopAnimation(this);
  20405. // Remove from scene
  20406. this.getScene().removeCamera(this);
  20407. while (this._rigCameras.length > 0) {
  20408. var camera = this._rigCameras.pop();
  20409. if (camera) {
  20410. camera.dispose();
  20411. }
  20412. }
  20413. // Postprocesses
  20414. if (this._rigPostProcess) {
  20415. this._rigPostProcess.dispose(this);
  20416. this._rigPostProcess = null;
  20417. this._postProcesses = [];
  20418. }
  20419. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20420. this._rigPostProcess = null;
  20421. this._postProcesses = [];
  20422. }
  20423. else {
  20424. var i = this._postProcesses.length;
  20425. while (--i >= 0) {
  20426. var postProcess = this._postProcesses[i];
  20427. if (postProcess) {
  20428. postProcess.dispose(this);
  20429. }
  20430. }
  20431. }
  20432. // Render targets
  20433. var i = this.customRenderTargets.length;
  20434. while (--i >= 0) {
  20435. this.customRenderTargets[i].dispose();
  20436. }
  20437. this.customRenderTargets = [];
  20438. // Active Meshes
  20439. this._activeMeshes.dispose();
  20440. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20441. };
  20442. Object.defineProperty(Camera.prototype, "leftCamera", {
  20443. // ---- Camera rigs section ----
  20444. get: function () {
  20445. if (this._rigCameras.length < 1) {
  20446. return null;
  20447. }
  20448. return this._rigCameras[0];
  20449. },
  20450. enumerable: true,
  20451. configurable: true
  20452. });
  20453. Object.defineProperty(Camera.prototype, "rightCamera", {
  20454. get: function () {
  20455. if (this._rigCameras.length < 2) {
  20456. return null;
  20457. }
  20458. return this._rigCameras[1];
  20459. },
  20460. enumerable: true,
  20461. configurable: true
  20462. });
  20463. Camera.prototype.getLeftTarget = function () {
  20464. if (this._rigCameras.length < 1) {
  20465. return null;
  20466. }
  20467. return this._rigCameras[0].getTarget();
  20468. };
  20469. Camera.prototype.getRightTarget = function () {
  20470. if (this._rigCameras.length < 2) {
  20471. return null;
  20472. }
  20473. return this._rigCameras[1].getTarget();
  20474. };
  20475. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20476. if (this.cameraRigMode === mode) {
  20477. return;
  20478. }
  20479. while (this._rigCameras.length > 0) {
  20480. var camera = this._rigCameras.pop();
  20481. if (camera) {
  20482. camera.dispose();
  20483. }
  20484. }
  20485. this.cameraRigMode = mode;
  20486. this._cameraRigParams = {};
  20487. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20488. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20489. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20490. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20491. // create the rig cameras, unless none
  20492. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20493. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20494. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20495. if (leftCamera && rightCamera) {
  20496. this._rigCameras.push(leftCamera);
  20497. this._rigCameras.push(rightCamera);
  20498. }
  20499. }
  20500. switch (this.cameraRigMode) {
  20501. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20502. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20503. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20504. break;
  20505. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20506. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20507. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20508. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20509. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20510. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20511. break;
  20512. case Camera.RIG_MODE_VR:
  20513. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20514. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20515. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20516. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20517. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20518. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20519. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20520. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20521. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20522. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20523. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20524. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20525. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20526. if (metrics.compensateDistortion) {
  20527. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20528. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20529. }
  20530. break;
  20531. case Camera.RIG_MODE_WEBVR:
  20532. if (rigParams.vrDisplay) {
  20533. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20534. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20535. //Left eye
  20536. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20537. this._rigCameras[0].setCameraRigParameter("left", true);
  20538. //leaving this for future reference
  20539. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20540. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20541. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20542. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20543. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20544. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20545. this._rigCameras[0].parent = this;
  20546. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20547. //Right eye
  20548. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20549. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20550. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20551. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20552. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20553. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20554. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20555. this._rigCameras[1].parent = this;
  20556. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20557. if (Camera.UseAlternateWebVRRendering) {
  20558. this._rigCameras[1]._skipRendering = true;
  20559. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20560. }
  20561. }
  20562. break;
  20563. }
  20564. this._cascadePostProcessesToRigCams();
  20565. this.update();
  20566. };
  20567. Camera.prototype._getVRProjectionMatrix = function () {
  20568. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20569. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20570. return this._projectionMatrix;
  20571. };
  20572. Camera.prototype._updateCameraRotationMatrix = function () {
  20573. //Here for WebVR
  20574. };
  20575. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20576. //Here for WebVR
  20577. };
  20578. /**
  20579. * This function MUST be overwritten by the different WebVR cameras available.
  20580. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20581. */
  20582. Camera.prototype._getWebVRProjectionMatrix = function () {
  20583. return BABYLON.Matrix.Identity();
  20584. };
  20585. /**
  20586. * This function MUST be overwritten by the different WebVR cameras available.
  20587. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20588. */
  20589. Camera.prototype._getWebVRViewMatrix = function () {
  20590. return BABYLON.Matrix.Identity();
  20591. };
  20592. Camera.prototype.setCameraRigParameter = function (name, value) {
  20593. if (!this._cameraRigParams) {
  20594. this._cameraRigParams = {};
  20595. }
  20596. this._cameraRigParams[name] = value;
  20597. //provisionnally:
  20598. if (name === "interaxialDistance") {
  20599. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20600. }
  20601. };
  20602. /**
  20603. * needs to be overridden by children so sub has required properties to be copied
  20604. */
  20605. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20606. return null;
  20607. };
  20608. /**
  20609. * May need to be overridden by children
  20610. */
  20611. Camera.prototype._updateRigCameras = function () {
  20612. for (var i = 0; i < this._rigCameras.length; i++) {
  20613. this._rigCameras[i].minZ = this.minZ;
  20614. this._rigCameras[i].maxZ = this.maxZ;
  20615. this._rigCameras[i].fov = this.fov;
  20616. }
  20617. // only update viewport when ANAGLYPH
  20618. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20619. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20620. }
  20621. };
  20622. Camera.prototype._setupInputs = function () {
  20623. };
  20624. Camera.prototype.serialize = function () {
  20625. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20626. // Type
  20627. serializationObject.type = this.getClassName();
  20628. // Parent
  20629. if (this.parent) {
  20630. serializationObject.parentId = this.parent.id;
  20631. }
  20632. if (this.inputs) {
  20633. this.inputs.serialize(serializationObject);
  20634. }
  20635. // Animations
  20636. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20637. serializationObject.ranges = this.serializeAnimationRanges();
  20638. return serializationObject;
  20639. };
  20640. Camera.prototype.clone = function (name) {
  20641. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20642. };
  20643. Camera.prototype.getDirection = function (localAxis) {
  20644. var result = BABYLON.Vector3.Zero();
  20645. this.getDirectionToRef(localAxis, result);
  20646. return result;
  20647. };
  20648. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20649. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20650. };
  20651. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20652. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20653. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20654. switch (type) {
  20655. case "ArcRotateCamera":
  20656. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20657. case "DeviceOrientationCamera":
  20658. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20659. case "FollowCamera":
  20660. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20661. case "ArcFollowCamera":
  20662. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20663. case "GamepadCamera":
  20664. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20665. case "TouchCamera":
  20666. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20667. case "VirtualJoysticksCamera":
  20668. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20669. case "WebVRFreeCamera":
  20670. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20671. case "WebVRGamepadCamera":
  20672. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20673. case "VRDeviceOrientationFreeCamera":
  20674. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20675. case "VRDeviceOrientationGamepadCamera":
  20676. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20677. case "AnaglyphArcRotateCamera":
  20678. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20679. case "AnaglyphFreeCamera":
  20680. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20681. case "AnaglyphGamepadCamera":
  20682. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20683. case "AnaglyphUniversalCamera":
  20684. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20685. case "StereoscopicArcRotateCamera":
  20686. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20687. case "StereoscopicFreeCamera":
  20688. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20689. case "StereoscopicGamepadCamera":
  20690. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20691. case "StereoscopicUniversalCamera":
  20692. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20693. case "FreeCamera":// Forcing Universal here
  20694. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20695. default:// Universal Camera is the default value
  20696. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20697. }
  20698. };
  20699. Camera.prototype.computeWorldMatrix = function () {
  20700. return this.getWorldMatrix();
  20701. };
  20702. Camera.Parse = function (parsedCamera, scene) {
  20703. var type = parsedCamera.type;
  20704. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20705. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20706. // Parent
  20707. if (parsedCamera.parentId) {
  20708. camera._waitingParentId = parsedCamera.parentId;
  20709. }
  20710. //If camera has an input manager, let it parse inputs settings
  20711. if (camera.inputs) {
  20712. camera.inputs.parse(parsedCamera);
  20713. camera._setupInputs();
  20714. }
  20715. if (camera.setPosition) {
  20716. camera.position.copyFromFloats(0, 0, 0);
  20717. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20718. }
  20719. // Target
  20720. if (parsedCamera.target) {
  20721. if (camera.setTarget) {
  20722. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20723. }
  20724. }
  20725. // Apply 3d rig, when found
  20726. if (parsedCamera.cameraRigMode) {
  20727. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20728. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20729. }
  20730. // Animations
  20731. if (parsedCamera.animations) {
  20732. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20733. var parsedAnimation = parsedCamera.animations[animationIndex];
  20734. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20735. }
  20736. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20737. }
  20738. if (parsedCamera.autoAnimate) {
  20739. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20740. }
  20741. return camera;
  20742. };
  20743. // Statics
  20744. Camera._PERSPECTIVE_CAMERA = 0;
  20745. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20746. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20747. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20748. Camera._RIG_MODE_NONE = 0;
  20749. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20750. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20751. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20752. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20753. Camera._RIG_MODE_VR = 20;
  20754. Camera._RIG_MODE_WEBVR = 21;
  20755. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20756. Camera.UseAlternateWebVRRendering = false;
  20757. __decorate([
  20758. BABYLON.serializeAsVector3()
  20759. ], Camera.prototype, "position", void 0);
  20760. __decorate([
  20761. BABYLON.serializeAsVector3()
  20762. ], Camera.prototype, "upVector", void 0);
  20763. __decorate([
  20764. BABYLON.serialize()
  20765. ], Camera.prototype, "orthoLeft", void 0);
  20766. __decorate([
  20767. BABYLON.serialize()
  20768. ], Camera.prototype, "orthoRight", void 0);
  20769. __decorate([
  20770. BABYLON.serialize()
  20771. ], Camera.prototype, "orthoBottom", void 0);
  20772. __decorate([
  20773. BABYLON.serialize()
  20774. ], Camera.prototype, "orthoTop", void 0);
  20775. __decorate([
  20776. BABYLON.serialize()
  20777. ], Camera.prototype, "fov", void 0);
  20778. __decorate([
  20779. BABYLON.serialize()
  20780. ], Camera.prototype, "minZ", void 0);
  20781. __decorate([
  20782. BABYLON.serialize()
  20783. ], Camera.prototype, "maxZ", void 0);
  20784. __decorate([
  20785. BABYLON.serialize()
  20786. ], Camera.prototype, "inertia", void 0);
  20787. __decorate([
  20788. BABYLON.serialize()
  20789. ], Camera.prototype, "mode", void 0);
  20790. __decorate([
  20791. BABYLON.serialize()
  20792. ], Camera.prototype, "layerMask", void 0);
  20793. __decorate([
  20794. BABYLON.serialize()
  20795. ], Camera.prototype, "fovMode", void 0);
  20796. __decorate([
  20797. BABYLON.serialize()
  20798. ], Camera.prototype, "cameraRigMode", void 0);
  20799. __decorate([
  20800. BABYLON.serialize()
  20801. ], Camera.prototype, "interaxialDistance", void 0);
  20802. __decorate([
  20803. BABYLON.serialize()
  20804. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20805. return Camera;
  20806. }(BABYLON.Node));
  20807. BABYLON.Camera = Camera;
  20808. })(BABYLON || (BABYLON = {}));
  20809. //# sourceMappingURL=babylon.camera.js.map
  20810. var BABYLON;
  20811. (function (BABYLON) {
  20812. var RenderingManager = /** @class */ (function () {
  20813. function RenderingManager(scene) {
  20814. this._renderingGroups = new Array();
  20815. this._autoClearDepthStencil = {};
  20816. this._customOpaqueSortCompareFn = {};
  20817. this._customAlphaTestSortCompareFn = {};
  20818. this._customTransparentSortCompareFn = {};
  20819. this._renderinGroupInfo = null;
  20820. this._scene = scene;
  20821. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20822. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20823. }
  20824. }
  20825. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20826. if (depth === void 0) { depth = true; }
  20827. if (stencil === void 0) { stencil = true; }
  20828. if (this._depthStencilBufferAlreadyCleaned) {
  20829. return;
  20830. }
  20831. this._scene.getEngine().clear(null, false, depth, stencil);
  20832. this._depthStencilBufferAlreadyCleaned = true;
  20833. };
  20834. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20835. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20836. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20837. var info = null;
  20838. if (observable) {
  20839. if (!this._renderinGroupInfo) {
  20840. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20841. }
  20842. info = this._renderinGroupInfo;
  20843. info.scene = this._scene;
  20844. info.camera = this._scene.activeCamera;
  20845. }
  20846. // Dispatch sprites
  20847. if (renderSprites) {
  20848. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20849. var manager = this._scene.spriteManagers[index];
  20850. this.dispatchSprites(manager);
  20851. }
  20852. }
  20853. // Render
  20854. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20855. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20856. var renderingGroup = this._renderingGroups[index];
  20857. if (!renderingGroup && !observable)
  20858. continue;
  20859. var renderingGroupMask = 0;
  20860. // Fire PRECLEAR stage
  20861. if (observable && info) {
  20862. renderingGroupMask = Math.pow(2, index);
  20863. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20864. info.renderingGroupId = index;
  20865. observable.notifyObservers(info, renderingGroupMask);
  20866. }
  20867. // Clear depth/stencil if needed
  20868. if (RenderingManager.AUTOCLEAR) {
  20869. var autoClear = this._autoClearDepthStencil[index];
  20870. if (autoClear && autoClear.autoClear) {
  20871. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20872. }
  20873. }
  20874. if (observable && info) {
  20875. // Fire PREOPAQUE stage
  20876. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20877. observable.notifyObservers(info, renderingGroupMask);
  20878. // Fire PRETRANSPARENT stage
  20879. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20880. observable.notifyObservers(info, renderingGroupMask);
  20881. }
  20882. if (renderingGroup)
  20883. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20884. // Fire POSTTRANSPARENT stage
  20885. if (observable && info) {
  20886. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20887. observable.notifyObservers(info, renderingGroupMask);
  20888. }
  20889. }
  20890. };
  20891. RenderingManager.prototype.reset = function () {
  20892. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20893. var renderingGroup = this._renderingGroups[index];
  20894. if (renderingGroup) {
  20895. renderingGroup.prepare();
  20896. }
  20897. }
  20898. };
  20899. RenderingManager.prototype.dispose = function () {
  20900. this.freeRenderingGroups();
  20901. this._renderingGroups.length = 0;
  20902. };
  20903. /**
  20904. * Clear the info related to rendering groups preventing retention points during dispose.
  20905. */
  20906. RenderingManager.prototype.freeRenderingGroups = function () {
  20907. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20908. var renderingGroup = this._renderingGroups[index];
  20909. if (renderingGroup) {
  20910. renderingGroup.dispose();
  20911. }
  20912. }
  20913. };
  20914. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20915. if (this._renderingGroups[renderingGroupId] === undefined) {
  20916. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20917. }
  20918. };
  20919. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20920. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20921. this._prepareRenderingGroup(renderingGroupId);
  20922. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20923. };
  20924. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20925. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20926. this._prepareRenderingGroup(renderingGroupId);
  20927. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20928. };
  20929. /**
  20930. * @param subMesh The submesh to dispatch
  20931. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20932. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20933. */
  20934. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20935. if (mesh === undefined) {
  20936. mesh = subMesh.getMesh();
  20937. }
  20938. var renderingGroupId = mesh.renderingGroupId || 0;
  20939. this._prepareRenderingGroup(renderingGroupId);
  20940. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20941. };
  20942. /**
  20943. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20944. * This allowed control for front to back rendering or reversly depending of the special needs.
  20945. *
  20946. * @param renderingGroupId The rendering group id corresponding to its index
  20947. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20948. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20949. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20950. */
  20951. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20952. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20953. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20954. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20955. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20956. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20957. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20958. if (this._renderingGroups[renderingGroupId]) {
  20959. var group = this._renderingGroups[renderingGroupId];
  20960. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20961. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20962. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20963. }
  20964. };
  20965. /**
  20966. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20967. *
  20968. * @param renderingGroupId The rendering group id corresponding to its index
  20969. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20970. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20971. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20972. */
  20973. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20974. if (depth === void 0) { depth = true; }
  20975. if (stencil === void 0) { stencil = true; }
  20976. this._autoClearDepthStencil[renderingGroupId] = {
  20977. autoClear: autoClearDepthStencil,
  20978. depth: depth,
  20979. stencil: stencil
  20980. };
  20981. };
  20982. /**
  20983. * The max id used for rendering groups (not included)
  20984. */
  20985. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20986. /**
  20987. * The min id used for rendering groups (included)
  20988. */
  20989. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20990. /**
  20991. * Used to globally prevent autoclearing scenes.
  20992. */
  20993. RenderingManager.AUTOCLEAR = true;
  20994. return RenderingManager;
  20995. }());
  20996. BABYLON.RenderingManager = RenderingManager;
  20997. })(BABYLON || (BABYLON = {}));
  20998. //# sourceMappingURL=babylon.renderingManager.js.map
  20999. var BABYLON;
  21000. (function (BABYLON) {
  21001. var RenderingGroup = /** @class */ (function () {
  21002. /**
  21003. * Creates a new rendering group.
  21004. * @param index The rendering group index
  21005. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  21006. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  21007. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  21008. */
  21009. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21010. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21011. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21012. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21013. this.index = index;
  21014. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  21015. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  21016. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  21017. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  21018. this._particleSystems = new BABYLON.SmartArray(256);
  21019. this._spriteManagers = new BABYLON.SmartArray(256);
  21020. this._edgesRenderers = new BABYLON.SmartArray(16);
  21021. this._scene = scene;
  21022. this.opaqueSortCompareFn = opaqueSortCompareFn;
  21023. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  21024. this.transparentSortCompareFn = transparentSortCompareFn;
  21025. }
  21026. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  21027. /**
  21028. * Set the opaque sort comparison function.
  21029. * If null the sub meshes will be render in the order they were created
  21030. */
  21031. set: function (value) {
  21032. this._opaqueSortCompareFn = value;
  21033. if (value) {
  21034. this._renderOpaque = this.renderOpaqueSorted;
  21035. }
  21036. else {
  21037. this._renderOpaque = RenderingGroup.renderUnsorted;
  21038. }
  21039. },
  21040. enumerable: true,
  21041. configurable: true
  21042. });
  21043. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  21044. /**
  21045. * Set the alpha test sort comparison function.
  21046. * If null the sub meshes will be render in the order they were created
  21047. */
  21048. set: function (value) {
  21049. this._alphaTestSortCompareFn = value;
  21050. if (value) {
  21051. this._renderAlphaTest = this.renderAlphaTestSorted;
  21052. }
  21053. else {
  21054. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  21055. }
  21056. },
  21057. enumerable: true,
  21058. configurable: true
  21059. });
  21060. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  21061. /**
  21062. * Set the transparent sort comparison function.
  21063. * If null the sub meshes will be render in the order they were created
  21064. */
  21065. set: function (value) {
  21066. if (value) {
  21067. this._transparentSortCompareFn = value;
  21068. }
  21069. else {
  21070. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  21071. }
  21072. this._renderTransparent = this.renderTransparentSorted;
  21073. },
  21074. enumerable: true,
  21075. configurable: true
  21076. });
  21077. /**
  21078. * Render all the sub meshes contained in the group.
  21079. * @param customRenderFunction Used to override the default render behaviour of the group.
  21080. * @returns true if rendered some submeshes.
  21081. */
  21082. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  21083. if (customRenderFunction) {
  21084. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  21085. return;
  21086. }
  21087. var engine = this._scene.getEngine();
  21088. // Depth only
  21089. if (this._depthOnlySubMeshes.length !== 0) {
  21090. engine.setColorWrite(false);
  21091. this._renderAlphaTest(this._depthOnlySubMeshes);
  21092. engine.setColorWrite(true);
  21093. }
  21094. // Opaque
  21095. if (this._opaqueSubMeshes.length !== 0) {
  21096. this._renderOpaque(this._opaqueSubMeshes);
  21097. }
  21098. // Alpha test
  21099. if (this._alphaTestSubMeshes.length !== 0) {
  21100. this._renderAlphaTest(this._alphaTestSubMeshes);
  21101. }
  21102. var stencilState = engine.getStencilBuffer();
  21103. engine.setStencilBuffer(false);
  21104. // Sprites
  21105. if (renderSprites) {
  21106. this._renderSprites();
  21107. }
  21108. // Particles
  21109. if (renderParticles) {
  21110. this._renderParticles(activeMeshes);
  21111. }
  21112. if (this.onBeforeTransparentRendering) {
  21113. this.onBeforeTransparentRendering();
  21114. }
  21115. // Transparent
  21116. if (this._transparentSubMeshes.length !== 0) {
  21117. this._renderTransparent(this._transparentSubMeshes);
  21118. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21119. }
  21120. // Set back stencil to false in case it changes before the edge renderer.
  21121. engine.setStencilBuffer(false);
  21122. // Edges
  21123. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21124. this._edgesRenderers.data[edgesRendererIndex].render();
  21125. }
  21126. // Restore Stencil state.
  21127. engine.setStencilBuffer(stencilState);
  21128. };
  21129. /**
  21130. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  21131. * @param subMeshes The submeshes to render
  21132. */
  21133. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  21134. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  21135. };
  21136. /**
  21137. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  21138. * @param subMeshes The submeshes to render
  21139. */
  21140. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  21141. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  21142. };
  21143. /**
  21144. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  21145. * @param subMeshes The submeshes to render
  21146. */
  21147. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  21148. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  21149. };
  21150. /**
  21151. * Renders the submeshes in a specified order.
  21152. * @param subMeshes The submeshes to sort before render
  21153. * @param sortCompareFn The comparison function use to sort
  21154. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21155. * @param transparent Specifies to activate blending if true
  21156. */
  21157. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21158. var subIndex = 0;
  21159. var subMesh;
  21160. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21161. for (; subIndex < subMeshes.length; subIndex++) {
  21162. subMesh = subMeshes.data[subIndex];
  21163. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21164. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21165. }
  21166. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21167. if (sortCompareFn) {
  21168. sortedArray.sort(sortCompareFn);
  21169. }
  21170. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21171. subMesh = sortedArray[subIndex];
  21172. if (transparent) {
  21173. var material = subMesh.getMaterial();
  21174. if (material && material.needDepthPrePass) {
  21175. var engine = material.getScene().getEngine();
  21176. engine.setColorWrite(false);
  21177. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21178. subMesh.render(false);
  21179. engine.setColorWrite(true);
  21180. }
  21181. }
  21182. subMesh.render(transparent);
  21183. }
  21184. };
  21185. /**
  21186. * Renders the submeshes in the order they were dispatched (no sort applied).
  21187. * @param subMeshes The submeshes to render
  21188. */
  21189. RenderingGroup.renderUnsorted = function (subMeshes) {
  21190. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21191. var submesh = subMeshes.data[subIndex];
  21192. submesh.render(false);
  21193. }
  21194. };
  21195. /**
  21196. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21197. * are rendered back to front if in the same alpha index.
  21198. *
  21199. * @param a The first submesh
  21200. * @param b The second submesh
  21201. * @returns The result of the comparison
  21202. */
  21203. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21204. // Alpha index first
  21205. if (a._alphaIndex > b._alphaIndex) {
  21206. return 1;
  21207. }
  21208. if (a._alphaIndex < b._alphaIndex) {
  21209. return -1;
  21210. }
  21211. // Then distance to camera
  21212. return RenderingGroup.backToFrontSortCompare(a, b);
  21213. };
  21214. /**
  21215. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21216. * are rendered back to front.
  21217. *
  21218. * @param a The first submesh
  21219. * @param b The second submesh
  21220. * @returns The result of the comparison
  21221. */
  21222. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21223. // Then distance to camera
  21224. if (a._distanceToCamera < b._distanceToCamera) {
  21225. return 1;
  21226. }
  21227. if (a._distanceToCamera > b._distanceToCamera) {
  21228. return -1;
  21229. }
  21230. return 0;
  21231. };
  21232. /**
  21233. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21234. * are rendered front to back (prevent overdraw).
  21235. *
  21236. * @param a The first submesh
  21237. * @param b The second submesh
  21238. * @returns The result of the comparison
  21239. */
  21240. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21241. // Then distance to camera
  21242. if (a._distanceToCamera < b._distanceToCamera) {
  21243. return -1;
  21244. }
  21245. if (a._distanceToCamera > b._distanceToCamera) {
  21246. return 1;
  21247. }
  21248. return 0;
  21249. };
  21250. /**
  21251. * Resets the different lists of submeshes to prepare a new frame.
  21252. */
  21253. RenderingGroup.prototype.prepare = function () {
  21254. this._opaqueSubMeshes.reset();
  21255. this._transparentSubMeshes.reset();
  21256. this._alphaTestSubMeshes.reset();
  21257. this._depthOnlySubMeshes.reset();
  21258. this._particleSystems.reset();
  21259. this._spriteManagers.reset();
  21260. this._edgesRenderers.reset();
  21261. };
  21262. RenderingGroup.prototype.dispose = function () {
  21263. this._opaqueSubMeshes.dispose();
  21264. this._transparentSubMeshes.dispose();
  21265. this._alphaTestSubMeshes.dispose();
  21266. this._depthOnlySubMeshes.dispose();
  21267. this._particleSystems.dispose();
  21268. this._spriteManagers.dispose();
  21269. this._edgesRenderers.dispose();
  21270. };
  21271. /**
  21272. * Inserts the submesh in its correct queue depending on its material.
  21273. * @param subMesh The submesh to dispatch
  21274. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21275. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21276. */
  21277. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21278. // Get mesh and materials if not provided
  21279. if (mesh === undefined) {
  21280. mesh = subMesh.getMesh();
  21281. }
  21282. if (material === undefined) {
  21283. material = subMesh.getMaterial();
  21284. }
  21285. if (material === null || material === undefined) {
  21286. return;
  21287. }
  21288. if (material.needAlphaBlendingForMesh(mesh)) {
  21289. this._transparentSubMeshes.push(subMesh);
  21290. }
  21291. else if (material.needAlphaTesting()) {
  21292. if (material.needDepthPrePass) {
  21293. this._depthOnlySubMeshes.push(subMesh);
  21294. }
  21295. this._alphaTestSubMeshes.push(subMesh);
  21296. }
  21297. else {
  21298. if (material.needDepthPrePass) {
  21299. this._depthOnlySubMeshes.push(subMesh);
  21300. }
  21301. this._opaqueSubMeshes.push(subMesh); // Opaque
  21302. }
  21303. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21304. this._edgesRenderers.push(mesh._edgesRenderer);
  21305. }
  21306. };
  21307. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21308. this._spriteManagers.push(spriteManager);
  21309. };
  21310. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21311. this._particleSystems.push(particleSystem);
  21312. };
  21313. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21314. if (this._particleSystems.length === 0) {
  21315. return;
  21316. }
  21317. // Particles
  21318. var activeCamera = this._scene.activeCamera;
  21319. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21320. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21321. var particleSystem = this._particleSystems.data[particleIndex];
  21322. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21323. continue;
  21324. }
  21325. var emitter = particleSystem.emitter;
  21326. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21327. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21328. }
  21329. }
  21330. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21331. };
  21332. RenderingGroup.prototype._renderSprites = function () {
  21333. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21334. return;
  21335. }
  21336. // Sprites
  21337. var activeCamera = this._scene.activeCamera;
  21338. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21339. for (var id = 0; id < this._spriteManagers.length; id++) {
  21340. var spriteManager = this._spriteManagers.data[id];
  21341. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21342. spriteManager.render();
  21343. }
  21344. }
  21345. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21346. };
  21347. return RenderingGroup;
  21348. }());
  21349. BABYLON.RenderingGroup = RenderingGroup;
  21350. })(BABYLON || (BABYLON = {}));
  21351. //# sourceMappingURL=babylon.renderingGroup.js.map
  21352. var BABYLON;
  21353. (function (BABYLON) {
  21354. var ClickInfo = /** @class */ (function () {
  21355. function ClickInfo() {
  21356. this._singleClick = false;
  21357. this._doubleClick = false;
  21358. this._hasSwiped = false;
  21359. this._ignore = false;
  21360. }
  21361. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21362. get: function () {
  21363. return this._singleClick;
  21364. },
  21365. set: function (b) {
  21366. this._singleClick = b;
  21367. },
  21368. enumerable: true,
  21369. configurable: true
  21370. });
  21371. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21372. get: function () {
  21373. return this._doubleClick;
  21374. },
  21375. set: function (b) {
  21376. this._doubleClick = b;
  21377. },
  21378. enumerable: true,
  21379. configurable: true
  21380. });
  21381. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21382. get: function () {
  21383. return this._hasSwiped;
  21384. },
  21385. set: function (b) {
  21386. this._hasSwiped = b;
  21387. },
  21388. enumerable: true,
  21389. configurable: true
  21390. });
  21391. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21392. get: function () {
  21393. return this._ignore;
  21394. },
  21395. set: function (b) {
  21396. this._ignore = b;
  21397. },
  21398. enumerable: true,
  21399. configurable: true
  21400. });
  21401. return ClickInfo;
  21402. }());
  21403. /**
  21404. * This class is used by the onRenderingGroupObservable
  21405. */
  21406. var RenderingGroupInfo = /** @class */ (function () {
  21407. function RenderingGroupInfo() {
  21408. }
  21409. /**
  21410. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21411. * This stage will be fired no matter what
  21412. */
  21413. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21414. /**
  21415. * Called before opaque object are rendered.
  21416. * This stage will be fired only if there's 3D Opaque content to render
  21417. */
  21418. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21419. /**
  21420. * Called after the opaque objects are rendered and before the transparent ones
  21421. * This stage will be fired only if there's 3D transparent content to render
  21422. */
  21423. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21424. /**
  21425. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21426. * This stage will be fired no matter what
  21427. */
  21428. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21429. return RenderingGroupInfo;
  21430. }());
  21431. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21432. /**
  21433. * Represents a scene to be rendered by the engine.
  21434. * @see http://doc.babylonjs.com/page.php?p=21911
  21435. */
  21436. var Scene = /** @class */ (function () {
  21437. /**
  21438. * @constructor
  21439. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21440. */
  21441. function Scene(engine) {
  21442. // Members
  21443. this.autoClear = true;
  21444. this.autoClearDepthAndStencil = true;
  21445. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21446. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21447. this.forceWireframe = false;
  21448. this._forcePointsCloud = false;
  21449. this.forceShowBoundingBoxes = false;
  21450. this.animationsEnabled = true;
  21451. this.useConstantAnimationDeltaTime = false;
  21452. this.constantlyUpdateMeshUnderPointer = false;
  21453. this.hoverCursor = "pointer";
  21454. this.defaultCursor = "";
  21455. /**
  21456. * This is used to call preventDefault() on pointer down
  21457. * in order to block unwanted artifacts like system double clicks
  21458. */
  21459. this.preventDefaultOnPointerDown = true;
  21460. // Metadata
  21461. this.metadata = null;
  21462. /**
  21463. * An event triggered when the scene is disposed.
  21464. * @type {BABYLON.Observable}
  21465. */
  21466. this.onDisposeObservable = new BABYLON.Observable();
  21467. /**
  21468. * An event triggered before rendering the scene (right after animations and physics)
  21469. * @type {BABYLON.Observable}
  21470. */
  21471. this.onBeforeRenderObservable = new BABYLON.Observable();
  21472. /**
  21473. * An event triggered after rendering the scene
  21474. * @type {BABYLON.Observable}
  21475. */
  21476. this.onAfterRenderObservable = new BABYLON.Observable();
  21477. /**
  21478. * An event triggered before animating the scene
  21479. * @type {BABYLON.Observable}
  21480. */
  21481. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21482. /**
  21483. * An event triggered after animations processing
  21484. * @type {BABYLON.Observable}
  21485. */
  21486. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21487. /**
  21488. * An event triggered before draw calls are ready to be sent
  21489. * @type {BABYLON.Observable}
  21490. */
  21491. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21492. /**
  21493. * An event triggered after draw calls have been sent
  21494. * @type {BABYLON.Observable}
  21495. */
  21496. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21497. /**
  21498. * An event triggered when physic simulation is about to be run
  21499. * @type {BABYLON.Observable}
  21500. */
  21501. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21502. /**
  21503. * An event triggered when physic simulation has been done
  21504. * @type {BABYLON.Observable}
  21505. */
  21506. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21507. /**
  21508. * An event triggered when the scene is ready
  21509. * @type {BABYLON.Observable}
  21510. */
  21511. this.onReadyObservable = new BABYLON.Observable();
  21512. /**
  21513. * An event triggered before rendering a camera
  21514. * @type {BABYLON.Observable}
  21515. */
  21516. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21517. /**
  21518. * An event triggered after rendering a camera
  21519. * @type {BABYLON.Observable}
  21520. */
  21521. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21522. /**
  21523. * An event triggered when active meshes evaluation is about to start
  21524. * @type {BABYLON.Observable}
  21525. */
  21526. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21527. /**
  21528. * An event triggered when active meshes evaluation is done
  21529. * @type {BABYLON.Observable}
  21530. */
  21531. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21532. /**
  21533. * An event triggered when particles rendering is about to start
  21534. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21535. * @type {BABYLON.Observable}
  21536. */
  21537. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21538. /**
  21539. * An event triggered when particles rendering is done
  21540. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21541. * @type {BABYLON.Observable}
  21542. */
  21543. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21544. /**
  21545. * An event triggered when sprites rendering is about to start
  21546. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21547. * @type {BABYLON.Observable}
  21548. */
  21549. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21550. /**
  21551. * An event triggered when sprites rendering is done
  21552. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21553. * @type {BABYLON.Observable}
  21554. */
  21555. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21556. /**
  21557. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21558. * @type {BABYLON.Observable}
  21559. */
  21560. this.onDataLoadedObservable = new BABYLON.Observable();
  21561. /**
  21562. * An event triggered when a camera is created
  21563. * @type {BABYLON.Observable}
  21564. */
  21565. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21566. /**
  21567. * An event triggered when a camera is removed
  21568. * @type {BABYLON.Observable}
  21569. */
  21570. this.onCameraRemovedObservable = new BABYLON.Observable();
  21571. /**
  21572. * An event triggered when a light is created
  21573. * @type {BABYLON.Observable}
  21574. */
  21575. this.onNewLightAddedObservable = new BABYLON.Observable();
  21576. /**
  21577. * An event triggered when a light is removed
  21578. * @type {BABYLON.Observable}
  21579. */
  21580. this.onLightRemovedObservable = new BABYLON.Observable();
  21581. /**
  21582. * An event triggered when a geometry is created
  21583. * @type {BABYLON.Observable}
  21584. */
  21585. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21586. /**
  21587. * An event triggered when a geometry is removed
  21588. * @type {BABYLON.Observable}
  21589. */
  21590. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21591. /**
  21592. * An event triggered when a transform node is created
  21593. * @type {BABYLON.Observable}
  21594. */
  21595. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21596. /**
  21597. * An event triggered when a transform node is removed
  21598. * @type {BABYLON.Observable}
  21599. */
  21600. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21601. /**
  21602. * An event triggered when a mesh is created
  21603. * @type {BABYLON.Observable}
  21604. */
  21605. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21606. /**
  21607. * An event triggered when a mesh is removed
  21608. * @type {BABYLON.Observable}
  21609. */
  21610. this.onMeshRemovedObservable = new BABYLON.Observable();
  21611. /**
  21612. * An event triggered when render targets are about to be rendered
  21613. * Can happen multiple times per frame.
  21614. * @type {BABYLON.Observable}
  21615. */
  21616. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21617. /**
  21618. * An event triggered when render targets were rendered.
  21619. * Can happen multiple times per frame.
  21620. * @type {BABYLON.Observable}
  21621. */
  21622. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21623. /**
  21624. * An event triggered before calculating deterministic simulation step
  21625. * @type {BABYLON.Observable}
  21626. */
  21627. this.onBeforeStepObservable = new BABYLON.Observable();
  21628. /**
  21629. * An event triggered after calculating deterministic simulation step
  21630. * @type {BABYLON.Observable}
  21631. */
  21632. this.onAfterStepObservable = new BABYLON.Observable();
  21633. /**
  21634. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21635. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21636. * 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)
  21637. */
  21638. this.onRenderingGroupObservable = new BABYLON.Observable();
  21639. // Animations
  21640. this.animations = [];
  21641. /**
  21642. * 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).
  21643. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21644. */
  21645. this.onPrePointerObservable = new BABYLON.Observable();
  21646. /**
  21647. * Observable event triggered each time an input event is received from the rendering canvas
  21648. */
  21649. this.onPointerObservable = new BABYLON.Observable();
  21650. this._meshPickProceed = false;
  21651. this._currentPickResult = null;
  21652. this._previousPickResult = null;
  21653. this._totalPointersPressed = 0;
  21654. this._doubleClickOccured = false;
  21655. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21656. this.cameraToUseForPointers = null;
  21657. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21658. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21659. this._startingPointerTime = 0;
  21660. this._previousStartingPointerTime = 0;
  21661. // Deterministic lockstep
  21662. this._timeAccumulator = 0;
  21663. this._currentStepId = 0;
  21664. this._currentInternalStep = 0;
  21665. // Keyboard
  21666. /**
  21667. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21668. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21669. */
  21670. this.onPreKeyboardObservable = new BABYLON.Observable();
  21671. /**
  21672. * Observable event triggered each time an keyboard event is received from the hosting window
  21673. */
  21674. this.onKeyboardObservable = new BABYLON.Observable();
  21675. // Coordinate system
  21676. /**
  21677. * use right-handed coordinate system on this scene.
  21678. * @type {boolean}
  21679. */
  21680. this._useRightHandedSystem = false;
  21681. // Fog
  21682. this._fogEnabled = true;
  21683. this._fogMode = Scene.FOGMODE_NONE;
  21684. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21685. this.fogDensity = 0.1;
  21686. this.fogStart = 0;
  21687. this.fogEnd = 1000.0;
  21688. // Lights
  21689. /**
  21690. * is shadow enabled on this scene.
  21691. * @type {boolean}
  21692. */
  21693. this._shadowsEnabled = true;
  21694. /**
  21695. * is light enabled on this scene.
  21696. * @type {boolean}
  21697. */
  21698. this._lightsEnabled = true;
  21699. /**
  21700. * All of the lights added to this scene.
  21701. * @see BABYLON.Light
  21702. * @type {BABYLON.Light[]}
  21703. */
  21704. this.lights = new Array();
  21705. // Cameras
  21706. /** All of the cameras added to this scene. */
  21707. this.cameras = new Array();
  21708. /** All of the active cameras added to this scene. */
  21709. this.activeCameras = new Array();
  21710. // Meshes
  21711. /**
  21712. * All of the tranform nodes added to this scene.
  21713. * @see BABYLON.TransformNode
  21714. * @type {BABYLON.TransformNode[]}
  21715. */
  21716. this.transformNodes = new Array();
  21717. /**
  21718. * All of the (abstract) meshes added to this scene.
  21719. * @see BABYLON.AbstractMesh
  21720. * @type {BABYLON.AbstractMesh[]}
  21721. */
  21722. this.meshes = new Array();
  21723. /**
  21724. * All of the animation groups added to this scene.
  21725. * @see BABYLON.AnimationGroup
  21726. * @type {BABYLON.AnimationGroup[]}
  21727. */
  21728. this.animationGroups = new Array();
  21729. // Geometries
  21730. this._geometries = new Array();
  21731. this.materials = new Array();
  21732. this.multiMaterials = new Array();
  21733. // Textures
  21734. this._texturesEnabled = true;
  21735. this.textures = new Array();
  21736. // Particles
  21737. this.particlesEnabled = true;
  21738. this.particleSystems = new Array();
  21739. // Sprites
  21740. this.spritesEnabled = true;
  21741. this.spriteManagers = new Array();
  21742. /**
  21743. * The list of layers (background and foreground) of the scene.
  21744. */
  21745. this.layers = new Array();
  21746. /**
  21747. * The list of effect layers (highlights/glow) contained in the scene.
  21748. */
  21749. this.effectLayers = new Array();
  21750. // Skeletons
  21751. this._skeletonsEnabled = true;
  21752. this.skeletons = new Array();
  21753. // Morph targets
  21754. this.morphTargetManagers = new Array();
  21755. // Lens flares
  21756. this.lensFlaresEnabled = true;
  21757. this.lensFlareSystems = new Array();
  21758. // Collisions
  21759. this.collisionsEnabled = true;
  21760. /** Defines the gravity applied to this scene */
  21761. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21762. // Postprocesses
  21763. this.postProcesses = new Array();
  21764. this.postProcessesEnabled = true;
  21765. // Customs render targets
  21766. this.renderTargetsEnabled = true;
  21767. this.dumpNextRenderTargets = false;
  21768. this.customRenderTargets = new Array();
  21769. // Imported meshes
  21770. this.importedMeshesFiles = new Array();
  21771. // Probes
  21772. this.probesEnabled = true;
  21773. this.reflectionProbes = new Array();
  21774. this._actionManagers = new Array();
  21775. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21776. // Procedural textures
  21777. this.proceduralTexturesEnabled = true;
  21778. this._proceduralTextures = new Array();
  21779. this.soundTracks = new Array();
  21780. this._audioEnabled = true;
  21781. this._headphone = false;
  21782. // Performance counters
  21783. this._totalVertices = new BABYLON.PerfCounter();
  21784. this._activeIndices = new BABYLON.PerfCounter();
  21785. this._activeParticles = new BABYLON.PerfCounter();
  21786. this._activeBones = new BABYLON.PerfCounter();
  21787. this._animationTime = 0;
  21788. this.animationTimeScale = 1;
  21789. this._renderId = 0;
  21790. this._executeWhenReadyTimeoutId = -1;
  21791. this._intermediateRendering = false;
  21792. this._viewUpdateFlag = -1;
  21793. this._projectionUpdateFlag = -1;
  21794. this._alternateViewUpdateFlag = -1;
  21795. this._alternateProjectionUpdateFlag = -1;
  21796. this._toBeDisposed = new BABYLON.SmartArray(256);
  21797. this._activeRequests = new Array();
  21798. this._pendingData = new Array();
  21799. this._isDisposed = false;
  21800. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21801. this._activeMeshes = new BABYLON.SmartArray(256);
  21802. this._processedMaterials = new BABYLON.SmartArray(256);
  21803. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21804. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21805. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21806. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21807. this._activeAnimatables = new Array();
  21808. this._transformMatrix = BABYLON.Matrix.Zero();
  21809. this._useAlternateCameraConfiguration = false;
  21810. this._alternateRendering = false;
  21811. this.requireLightSorting = false;
  21812. this._depthRenderer = {};
  21813. this._activeMeshesFrozen = false;
  21814. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21815. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21816. this._engine.scenes.push(this);
  21817. this._uid = null;
  21818. this._renderingManager = new BABYLON.RenderingManager(this);
  21819. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21820. if (BABYLON.OutlineRenderer) {
  21821. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21822. }
  21823. if (BABYLON.Tools.IsWindowObjectExist()) {
  21824. this.attachControl();
  21825. }
  21826. //simplification queue
  21827. if (BABYLON.SimplificationQueue) {
  21828. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21829. }
  21830. //collision coordinator initialization. For now legacy per default.
  21831. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21832. // Uniform Buffer
  21833. this._createUbo();
  21834. // Default Image processing definition.
  21835. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21836. }
  21837. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21838. /** The fog is deactivated */
  21839. get: function () {
  21840. return Scene._FOGMODE_NONE;
  21841. },
  21842. enumerable: true,
  21843. configurable: true
  21844. });
  21845. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21846. /** The fog density is following an exponential function */
  21847. get: function () {
  21848. return Scene._FOGMODE_EXP;
  21849. },
  21850. enumerable: true,
  21851. configurable: true
  21852. });
  21853. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21854. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21855. get: function () {
  21856. return Scene._FOGMODE_EXP2;
  21857. },
  21858. enumerable: true,
  21859. configurable: true
  21860. });
  21861. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21862. /** The fog density is following a linear function. */
  21863. get: function () {
  21864. return Scene._FOGMODE_LINEAR;
  21865. },
  21866. enumerable: true,
  21867. configurable: true
  21868. });
  21869. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21870. /**
  21871. * Texture used in all pbr material as the reflection texture.
  21872. * As in the majority of the scene they are the same (exception for multi room and so on),
  21873. * this is easier to reference from here than from all the materials.
  21874. */
  21875. get: function () {
  21876. return this._environmentTexture;
  21877. },
  21878. /**
  21879. * Texture used in all pbr material as the reflection texture.
  21880. * As in the majority of the scene they are the same (exception for multi room and so on),
  21881. * this is easier to set here than in all the materials.
  21882. */
  21883. set: function (value) {
  21884. if (this._environmentTexture === value) {
  21885. return;
  21886. }
  21887. this._environmentTexture = value;
  21888. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21889. },
  21890. enumerable: true,
  21891. configurable: true
  21892. });
  21893. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21894. /**
  21895. * Default image processing configuration used either in the rendering
  21896. * Forward main pass or through the imageProcessingPostProcess if present.
  21897. * As in the majority of the scene they are the same (exception for multi camera),
  21898. * this is easier to reference from here than from all the materials and post process.
  21899. *
  21900. * No setter as we it is a shared configuration, you can set the values instead.
  21901. */
  21902. get: function () {
  21903. return this._imageProcessingConfiguration;
  21904. },
  21905. enumerable: true,
  21906. configurable: true
  21907. });
  21908. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21909. get: function () {
  21910. return this._forcePointsCloud;
  21911. },
  21912. set: function (value) {
  21913. if (this._forcePointsCloud === value) {
  21914. return;
  21915. }
  21916. this._forcePointsCloud = value;
  21917. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21918. },
  21919. enumerable: true,
  21920. configurable: true
  21921. });
  21922. Object.defineProperty(Scene.prototype, "onDispose", {
  21923. /** A function to be executed when this scene is disposed. */
  21924. set: function (callback) {
  21925. if (this._onDisposeObserver) {
  21926. this.onDisposeObservable.remove(this._onDisposeObserver);
  21927. }
  21928. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21929. },
  21930. enumerable: true,
  21931. configurable: true
  21932. });
  21933. Object.defineProperty(Scene.prototype, "beforeRender", {
  21934. /** A function to be executed before rendering this scene */
  21935. set: function (callback) {
  21936. if (this._onBeforeRenderObserver) {
  21937. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21938. }
  21939. if (callback) {
  21940. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21941. }
  21942. },
  21943. enumerable: true,
  21944. configurable: true
  21945. });
  21946. Object.defineProperty(Scene.prototype, "afterRender", {
  21947. /** A function to be executed after rendering this scene */
  21948. set: function (callback) {
  21949. if (this._onAfterRenderObserver) {
  21950. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21951. }
  21952. if (callback) {
  21953. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21954. }
  21955. },
  21956. enumerable: true,
  21957. configurable: true
  21958. });
  21959. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21960. set: function (callback) {
  21961. if (this._onBeforeCameraRenderObserver) {
  21962. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21963. }
  21964. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21965. },
  21966. enumerable: true,
  21967. configurable: true
  21968. });
  21969. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21970. set: function (callback) {
  21971. if (this._onAfterCameraRenderObserver) {
  21972. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21973. }
  21974. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21975. },
  21976. enumerable: true,
  21977. configurable: true
  21978. });
  21979. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21980. get: function () {
  21981. if (!this._gamepadManager) {
  21982. this._gamepadManager = new BABYLON.GamepadManager(this);
  21983. }
  21984. return this._gamepadManager;
  21985. },
  21986. enumerable: true,
  21987. configurable: true
  21988. });
  21989. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21990. get: function () {
  21991. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21992. },
  21993. enumerable: true,
  21994. configurable: true
  21995. });
  21996. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21997. get: function () {
  21998. return this._useRightHandedSystem;
  21999. },
  22000. set: function (value) {
  22001. if (this._useRightHandedSystem === value) {
  22002. return;
  22003. }
  22004. this._useRightHandedSystem = value;
  22005. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22006. },
  22007. enumerable: true,
  22008. configurable: true
  22009. });
  22010. Scene.prototype.setStepId = function (newStepId) {
  22011. this._currentStepId = newStepId;
  22012. };
  22013. ;
  22014. Scene.prototype.getStepId = function () {
  22015. return this._currentStepId;
  22016. };
  22017. ;
  22018. Scene.prototype.getInternalStep = function () {
  22019. return this._currentInternalStep;
  22020. };
  22021. ;
  22022. Object.defineProperty(Scene.prototype, "fogEnabled", {
  22023. get: function () {
  22024. return this._fogEnabled;
  22025. },
  22026. /**
  22027. * is fog enabled on this scene.
  22028. */
  22029. set: function (value) {
  22030. if (this._fogEnabled === value) {
  22031. return;
  22032. }
  22033. this._fogEnabled = value;
  22034. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22035. },
  22036. enumerable: true,
  22037. configurable: true
  22038. });
  22039. Object.defineProperty(Scene.prototype, "fogMode", {
  22040. get: function () {
  22041. return this._fogMode;
  22042. },
  22043. set: function (value) {
  22044. if (this._fogMode === value) {
  22045. return;
  22046. }
  22047. this._fogMode = value;
  22048. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22049. },
  22050. enumerable: true,
  22051. configurable: true
  22052. });
  22053. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  22054. get: function () {
  22055. return this._shadowsEnabled;
  22056. },
  22057. set: function (value) {
  22058. if (this._shadowsEnabled === value) {
  22059. return;
  22060. }
  22061. this._shadowsEnabled = value;
  22062. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22063. },
  22064. enumerable: true,
  22065. configurable: true
  22066. });
  22067. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  22068. get: function () {
  22069. return this._lightsEnabled;
  22070. },
  22071. set: function (value) {
  22072. if (this._lightsEnabled === value) {
  22073. return;
  22074. }
  22075. this._lightsEnabled = value;
  22076. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22077. },
  22078. enumerable: true,
  22079. configurable: true
  22080. });
  22081. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  22082. /** The default material used on meshes when no material is affected */
  22083. get: function () {
  22084. if (!this._defaultMaterial) {
  22085. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  22086. }
  22087. return this._defaultMaterial;
  22088. },
  22089. /** The default material used on meshes when no material is affected */
  22090. set: function (value) {
  22091. this._defaultMaterial = value;
  22092. },
  22093. enumerable: true,
  22094. configurable: true
  22095. });
  22096. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  22097. get: function () {
  22098. return this._texturesEnabled;
  22099. },
  22100. set: function (value) {
  22101. if (this._texturesEnabled === value) {
  22102. return;
  22103. }
  22104. this._texturesEnabled = value;
  22105. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22106. },
  22107. enumerable: true,
  22108. configurable: true
  22109. });
  22110. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  22111. get: function () {
  22112. return this._skeletonsEnabled;
  22113. },
  22114. set: function (value) {
  22115. if (this._skeletonsEnabled === value) {
  22116. return;
  22117. }
  22118. this._skeletonsEnabled = value;
  22119. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  22120. },
  22121. enumerable: true,
  22122. configurable: true
  22123. });
  22124. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  22125. get: function () {
  22126. if (!this._postProcessRenderPipelineManager) {
  22127. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  22128. }
  22129. return this._postProcessRenderPipelineManager;
  22130. },
  22131. enumerable: true,
  22132. configurable: true
  22133. });
  22134. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  22135. get: function () {
  22136. if (!this._mainSoundTrack) {
  22137. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  22138. }
  22139. return this._mainSoundTrack;
  22140. },
  22141. enumerable: true,
  22142. configurable: true
  22143. });
  22144. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  22145. get: function () {
  22146. return this._alternateRendering;
  22147. },
  22148. enumerable: true,
  22149. configurable: true
  22150. });
  22151. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22152. get: function () {
  22153. return this._frustumPlanes;
  22154. },
  22155. enumerable: true,
  22156. configurable: true
  22157. });
  22158. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22159. /**
  22160. * Gets the current geometry buffer associated to the scene.
  22161. */
  22162. get: function () {
  22163. return this._geometryBufferRenderer;
  22164. },
  22165. /**
  22166. * Sets the current geometry buffer for the scene.
  22167. */
  22168. set: function (geometryBufferRenderer) {
  22169. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22170. this._geometryBufferRenderer = geometryBufferRenderer;
  22171. }
  22172. },
  22173. enumerable: true,
  22174. configurable: true
  22175. });
  22176. Object.defineProperty(Scene.prototype, "debugLayer", {
  22177. // Properties
  22178. get: function () {
  22179. if (!this._debugLayer) {
  22180. this._debugLayer = new BABYLON.DebugLayer(this);
  22181. }
  22182. return this._debugLayer;
  22183. },
  22184. enumerable: true,
  22185. configurable: true
  22186. });
  22187. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22188. get: function () {
  22189. return this._workerCollisions;
  22190. },
  22191. set: function (enabled) {
  22192. if (!BABYLON.CollisionCoordinatorLegacy) {
  22193. return;
  22194. }
  22195. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22196. this._workerCollisions = enabled;
  22197. if (this.collisionCoordinator) {
  22198. this.collisionCoordinator.destroy();
  22199. }
  22200. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22201. this.collisionCoordinator.init(this);
  22202. },
  22203. enumerable: true,
  22204. configurable: true
  22205. });
  22206. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22207. get: function () {
  22208. return this._selectionOctree;
  22209. },
  22210. enumerable: true,
  22211. configurable: true
  22212. });
  22213. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22214. /**
  22215. * The mesh that is currently under the pointer.
  22216. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22217. */
  22218. get: function () {
  22219. return this._pointerOverMesh;
  22220. },
  22221. enumerable: true,
  22222. configurable: true
  22223. });
  22224. Object.defineProperty(Scene.prototype, "pointerX", {
  22225. /**
  22226. * Current on-screen X position of the pointer
  22227. * @return {number} X position of the pointer
  22228. */
  22229. get: function () {
  22230. return this._pointerX;
  22231. },
  22232. enumerable: true,
  22233. configurable: true
  22234. });
  22235. Object.defineProperty(Scene.prototype, "pointerY", {
  22236. /**
  22237. * Current on-screen Y position of the pointer
  22238. * @return {number} Y position of the pointer
  22239. */
  22240. get: function () {
  22241. return this._pointerY;
  22242. },
  22243. enumerable: true,
  22244. configurable: true
  22245. });
  22246. Scene.prototype.getCachedMaterial = function () {
  22247. return this._cachedMaterial;
  22248. };
  22249. Scene.prototype.getCachedEffect = function () {
  22250. return this._cachedEffect;
  22251. };
  22252. Scene.prototype.getCachedVisibility = function () {
  22253. return this._cachedVisibility;
  22254. };
  22255. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22256. if (visibility === void 0) { visibility = 1; }
  22257. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22258. };
  22259. Scene.prototype.getBoundingBoxRenderer = function () {
  22260. if (!this._boundingBoxRenderer) {
  22261. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22262. }
  22263. return this._boundingBoxRenderer;
  22264. };
  22265. Scene.prototype.getOutlineRenderer = function () {
  22266. return this._outlineRenderer;
  22267. };
  22268. Scene.prototype.getEngine = function () {
  22269. return this._engine;
  22270. };
  22271. Scene.prototype.getTotalVertices = function () {
  22272. return this._totalVertices.current;
  22273. };
  22274. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22275. get: function () {
  22276. return this._totalVertices;
  22277. },
  22278. enumerable: true,
  22279. configurable: true
  22280. });
  22281. Scene.prototype.getActiveIndices = function () {
  22282. return this._activeIndices.current;
  22283. };
  22284. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22285. get: function () {
  22286. return this._activeIndices;
  22287. },
  22288. enumerable: true,
  22289. configurable: true
  22290. });
  22291. Scene.prototype.getActiveParticles = function () {
  22292. return this._activeParticles.current;
  22293. };
  22294. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22295. get: function () {
  22296. return this._activeParticles;
  22297. },
  22298. enumerable: true,
  22299. configurable: true
  22300. });
  22301. Scene.prototype.getActiveBones = function () {
  22302. return this._activeBones.current;
  22303. };
  22304. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22305. get: function () {
  22306. return this._activeBones;
  22307. },
  22308. enumerable: true,
  22309. configurable: true
  22310. });
  22311. // Stats
  22312. Scene.prototype.getInterFramePerfCounter = function () {
  22313. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22314. return 0;
  22315. };
  22316. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22317. get: function () {
  22318. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22319. return null;
  22320. },
  22321. enumerable: true,
  22322. configurable: true
  22323. });
  22324. Scene.prototype.getLastFrameDuration = function () {
  22325. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22326. return 0;
  22327. };
  22328. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22329. get: function () {
  22330. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22331. return null;
  22332. },
  22333. enumerable: true,
  22334. configurable: true
  22335. });
  22336. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22337. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22338. return 0;
  22339. };
  22340. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22341. get: function () {
  22342. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22343. return null;
  22344. },
  22345. enumerable: true,
  22346. configurable: true
  22347. });
  22348. Scene.prototype.getActiveMeshes = function () {
  22349. return this._activeMeshes;
  22350. };
  22351. Scene.prototype.getRenderTargetsDuration = function () {
  22352. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22353. return 0;
  22354. };
  22355. Scene.prototype.getRenderDuration = function () {
  22356. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22357. return 0;
  22358. };
  22359. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22360. get: function () {
  22361. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22362. return null;
  22363. },
  22364. enumerable: true,
  22365. configurable: true
  22366. });
  22367. Scene.prototype.getParticlesDuration = function () {
  22368. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22369. return 0;
  22370. };
  22371. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22372. get: function () {
  22373. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22374. return null;
  22375. },
  22376. enumerable: true,
  22377. configurable: true
  22378. });
  22379. Scene.prototype.getSpritesDuration = function () {
  22380. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22381. return 0;
  22382. };
  22383. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22384. get: function () {
  22385. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22386. return null;
  22387. },
  22388. enumerable: true,
  22389. configurable: true
  22390. });
  22391. Scene.prototype.getAnimationRatio = function () {
  22392. return this._animationRatio;
  22393. };
  22394. Scene.prototype.getRenderId = function () {
  22395. return this._renderId;
  22396. };
  22397. Scene.prototype.incrementRenderId = function () {
  22398. this._renderId++;
  22399. };
  22400. Scene.prototype._updatePointerPosition = function (evt) {
  22401. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22402. if (!canvasRect) {
  22403. return;
  22404. }
  22405. this._pointerX = evt.clientX - canvasRect.left;
  22406. this._pointerY = evt.clientY - canvasRect.top;
  22407. this._unTranslatedPointerX = this._pointerX;
  22408. this._unTranslatedPointerY = this._pointerY;
  22409. };
  22410. Scene.prototype._createUbo = function () {
  22411. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22412. this._sceneUbo.addUniform("viewProjection", 16);
  22413. this._sceneUbo.addUniform("view", 16);
  22414. };
  22415. Scene.prototype._createAlternateUbo = function () {
  22416. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22417. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22418. this._alternateSceneUbo.addUniform("view", 16);
  22419. };
  22420. // Pointers handling
  22421. /**
  22422. * Use this method to simulate a pointer move on a mesh
  22423. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22424. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22425. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22426. */
  22427. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22428. var evt = new PointerEvent("pointermove", pointerEventInit);
  22429. return this._processPointerMove(pickResult, evt);
  22430. };
  22431. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22432. var canvas = this._engine.getRenderingCanvas();
  22433. if (!canvas) {
  22434. return this;
  22435. }
  22436. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22437. this.setPointerOverSprite(null);
  22438. this.setPointerOverMesh(pickResult.pickedMesh);
  22439. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22440. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22441. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22442. }
  22443. else {
  22444. canvas.style.cursor = this.hoverCursor;
  22445. }
  22446. }
  22447. else {
  22448. canvas.style.cursor = this.defaultCursor;
  22449. }
  22450. }
  22451. else {
  22452. this.setPointerOverMesh(null);
  22453. // Sprites
  22454. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22455. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22456. this.setPointerOverSprite(pickResult.pickedSprite);
  22457. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22458. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22459. }
  22460. else {
  22461. canvas.style.cursor = this.hoverCursor;
  22462. }
  22463. }
  22464. else {
  22465. this.setPointerOverSprite(null);
  22466. // Restore pointer
  22467. canvas.style.cursor = this.defaultCursor;
  22468. }
  22469. }
  22470. if (pickResult) {
  22471. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22472. if (this.onPointerMove) {
  22473. this.onPointerMove(evt, pickResult, type);
  22474. }
  22475. if (this.onPointerObservable.hasObservers()) {
  22476. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22477. this.onPointerObservable.notifyObservers(pi, type);
  22478. }
  22479. }
  22480. return this;
  22481. };
  22482. /**
  22483. * Use this method to simulate a pointer down on a mesh
  22484. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22485. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22486. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22487. */
  22488. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22489. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22490. return this._processPointerDown(pickResult, evt);
  22491. };
  22492. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22493. var _this = this;
  22494. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22495. this._pickedDownMesh = pickResult.pickedMesh;
  22496. var actionManager = pickResult.pickedMesh.actionManager;
  22497. if (actionManager) {
  22498. if (actionManager.hasPickTriggers) {
  22499. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22500. switch (evt.button) {
  22501. case 0:
  22502. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22503. break;
  22504. case 1:
  22505. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22506. break;
  22507. case 2:
  22508. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22509. break;
  22510. }
  22511. }
  22512. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22513. window.setTimeout(function () {
  22514. 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);
  22515. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22516. if (_this._totalPointersPressed !== 0 &&
  22517. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22518. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22519. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22520. _this._startingPointerTime = 0;
  22521. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22522. }
  22523. }
  22524. }, Scene.LongPressDelay);
  22525. }
  22526. }
  22527. }
  22528. if (pickResult) {
  22529. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22530. if (this.onPointerDown) {
  22531. this.onPointerDown(evt, pickResult, type);
  22532. }
  22533. if (this.onPointerObservable.hasObservers()) {
  22534. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22535. this.onPointerObservable.notifyObservers(pi, type);
  22536. }
  22537. }
  22538. return this;
  22539. };
  22540. /**
  22541. * Use this method to simulate a pointer up on a mesh
  22542. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22543. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22544. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22545. */
  22546. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22547. var evt = new PointerEvent("pointerup", pointerEventInit);
  22548. var clickInfo = new ClickInfo();
  22549. clickInfo.singleClick = true;
  22550. clickInfo.ignore = true;
  22551. return this._processPointerUp(pickResult, evt, clickInfo);
  22552. };
  22553. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22554. if (pickResult && pickResult && pickResult.pickedMesh) {
  22555. this._pickedUpMesh = pickResult.pickedMesh;
  22556. if (this._pickedDownMesh === this._pickedUpMesh) {
  22557. if (this.onPointerPick) {
  22558. this.onPointerPick(evt, pickResult);
  22559. }
  22560. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22561. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  22562. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  22563. this.onPointerObservable.notifyObservers(pi, type_1);
  22564. }
  22565. }
  22566. if (pickResult.pickedMesh.actionManager) {
  22567. if (clickInfo.ignore) {
  22568. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22569. }
  22570. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22571. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22572. }
  22573. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22574. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22575. }
  22576. }
  22577. }
  22578. if (this._pickedDownMesh &&
  22579. this._pickedDownMesh.actionManager &&
  22580. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22581. this._pickedDownMesh !== this._pickedUpMesh) {
  22582. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22583. }
  22584. var type = BABYLON.PointerEventTypes.POINTERUP;
  22585. if (this.onPointerObservable.hasObservers()) {
  22586. if (!clickInfo.ignore) {
  22587. if (!clickInfo.hasSwiped) {
  22588. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22589. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  22590. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  22591. this.onPointerObservable.notifyObservers(pi, type_2);
  22592. }
  22593. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22594. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22595. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  22596. this.onPointerObservable.notifyObservers(pi, type_3);
  22597. }
  22598. }
  22599. }
  22600. else {
  22601. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22602. this.onPointerObservable.notifyObservers(pi, type);
  22603. }
  22604. }
  22605. if (this.onPointerUp) {
  22606. this.onPointerUp(evt, pickResult, type);
  22607. }
  22608. return this;
  22609. };
  22610. /**
  22611. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22612. * @param attachUp defines if you want to attach events to pointerup
  22613. * @param attachDown defines if you want to attach events to pointerdown
  22614. * @param attachMove defines if you want to attach events to pointermove
  22615. */
  22616. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22617. var _this = this;
  22618. if (attachUp === void 0) { attachUp = true; }
  22619. if (attachDown === void 0) { attachDown = true; }
  22620. if (attachMove === void 0) { attachMove = true; }
  22621. this._initActionManager = function (act, clickInfo) {
  22622. if (!_this._meshPickProceed) {
  22623. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22624. _this._currentPickResult = pickResult;
  22625. if (pickResult) {
  22626. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22627. }
  22628. _this._meshPickProceed = true;
  22629. }
  22630. return act;
  22631. };
  22632. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22633. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22634. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22635. btn !== _this._previousButtonPressed) {
  22636. _this._doubleClickOccured = false;
  22637. clickInfo.singleClick = true;
  22638. clickInfo.ignore = false;
  22639. cb(clickInfo, _this._currentPickResult);
  22640. }
  22641. };
  22642. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22643. var clickInfo = new ClickInfo();
  22644. _this._currentPickResult = null;
  22645. var act = null;
  22646. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22647. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22648. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22649. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22650. act = _this._initActionManager(act, clickInfo);
  22651. if (act)
  22652. checkPicking = act.hasPickTriggers;
  22653. }
  22654. if (checkPicking) {
  22655. var btn = evt.button;
  22656. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22657. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22658. if (!clickInfo.hasSwiped) {
  22659. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22660. if (!checkSingleClickImmediately) {
  22661. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22662. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22663. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22664. act = _this._initActionManager(act, clickInfo);
  22665. if (act)
  22666. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22667. }
  22668. }
  22669. if (checkSingleClickImmediately) {
  22670. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22671. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22672. btn !== _this._previousButtonPressed) {
  22673. clickInfo.singleClick = true;
  22674. cb(clickInfo, _this._currentPickResult);
  22675. }
  22676. }
  22677. else {
  22678. // wait that no double click has been raised during the double click delay
  22679. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22680. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22681. }
  22682. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22683. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22684. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22685. act = _this._initActionManager(act, clickInfo);
  22686. if (act)
  22687. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22688. }
  22689. if (checkDoubleClick) {
  22690. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22691. if (btn === _this._previousButtonPressed &&
  22692. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22693. !_this._doubleClickOccured) {
  22694. // pointer has not moved for 2 clicks, it's a double click
  22695. if (!clickInfo.hasSwiped &&
  22696. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22697. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22698. _this._previousStartingPointerTime = 0;
  22699. _this._doubleClickOccured = true;
  22700. clickInfo.doubleClick = true;
  22701. clickInfo.ignore = false;
  22702. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22703. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22704. }
  22705. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22706. cb(clickInfo, _this._currentPickResult);
  22707. }
  22708. else {
  22709. _this._doubleClickOccured = false;
  22710. _this._previousStartingPointerTime = _this._startingPointerTime;
  22711. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22712. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22713. _this._previousButtonPressed = btn;
  22714. if (Scene.ExclusiveDoubleClickMode) {
  22715. if (_this._previousDelayedSimpleClickTimeout) {
  22716. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22717. }
  22718. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22719. cb(clickInfo, _this._previousPickResult);
  22720. }
  22721. else {
  22722. cb(clickInfo, _this._currentPickResult);
  22723. }
  22724. }
  22725. }
  22726. else {
  22727. _this._doubleClickOccured = false;
  22728. _this._previousStartingPointerTime = _this._startingPointerTime;
  22729. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22730. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22731. _this._previousButtonPressed = btn;
  22732. }
  22733. }
  22734. }
  22735. }
  22736. clickInfo.ignore = true;
  22737. cb(clickInfo, _this._currentPickResult);
  22738. };
  22739. this._spritePredicate = function (sprite) {
  22740. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22741. };
  22742. this._onPointerMove = function (evt) {
  22743. _this._updatePointerPosition(evt);
  22744. // PreObservable support
  22745. if (_this.onPrePointerObservable.hasObservers()) {
  22746. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22747. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22748. _this.onPrePointerObservable.notifyObservers(pi, type);
  22749. if (pi.skipOnPointerObservable) {
  22750. return;
  22751. }
  22752. }
  22753. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22754. return;
  22755. }
  22756. if (!_this.pointerMovePredicate) {
  22757. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22758. }
  22759. // Meshes
  22760. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22761. _this._processPointerMove(pickResult, evt);
  22762. };
  22763. this._onPointerDown = function (evt) {
  22764. _this._totalPointersPressed++;
  22765. _this._pickedDownMesh = null;
  22766. _this._meshPickProceed = false;
  22767. _this._updatePointerPosition(evt);
  22768. if (_this.preventDefaultOnPointerDown && canvas) {
  22769. evt.preventDefault();
  22770. canvas.focus();
  22771. }
  22772. // PreObservable support
  22773. if (_this.onPrePointerObservable.hasObservers()) {
  22774. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22775. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22776. _this.onPrePointerObservable.notifyObservers(pi, type);
  22777. if (pi.skipOnPointerObservable) {
  22778. return;
  22779. }
  22780. }
  22781. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22782. return;
  22783. }
  22784. _this._startingPointerPosition.x = _this._pointerX;
  22785. _this._startingPointerPosition.y = _this._pointerY;
  22786. _this._startingPointerTime = new Date().getTime();
  22787. if (!_this.pointerDownPredicate) {
  22788. _this.pointerDownPredicate = function (mesh) {
  22789. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22790. };
  22791. }
  22792. // Meshes
  22793. _this._pickedDownMesh = null;
  22794. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22795. _this._processPointerDown(pickResult, evt);
  22796. // Sprites
  22797. _this._pickedDownSprite = null;
  22798. if (_this.spriteManagers.length > 0) {
  22799. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22800. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22801. if (pickResult.pickedSprite.actionManager) {
  22802. _this._pickedDownSprite = pickResult.pickedSprite;
  22803. switch (evt.button) {
  22804. case 0:
  22805. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22806. break;
  22807. case 1:
  22808. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22809. break;
  22810. case 2:
  22811. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22812. break;
  22813. }
  22814. if (pickResult.pickedSprite.actionManager) {
  22815. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22816. }
  22817. }
  22818. }
  22819. }
  22820. };
  22821. this._onPointerUp = function (evt) {
  22822. if (_this._totalPointersPressed === 0) {
  22823. return; // So we need to test it the pointer down was pressed before.
  22824. }
  22825. _this._totalPointersPressed--;
  22826. _this._pickedUpMesh = null;
  22827. _this._meshPickProceed = false;
  22828. _this._updatePointerPosition(evt);
  22829. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22830. // PreObservable support
  22831. if (_this.onPrePointerObservable.hasObservers()) {
  22832. if (!clickInfo.ignore) {
  22833. if (!clickInfo.hasSwiped) {
  22834. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22835. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22836. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22837. _this.onPrePointerObservable.notifyObservers(pi, type);
  22838. if (pi.skipOnPointerObservable) {
  22839. return;
  22840. }
  22841. }
  22842. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22843. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22844. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22845. _this.onPrePointerObservable.notifyObservers(pi, type);
  22846. if (pi.skipOnPointerObservable) {
  22847. return;
  22848. }
  22849. }
  22850. }
  22851. }
  22852. else {
  22853. var type = BABYLON.PointerEventTypes.POINTERUP;
  22854. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22855. _this.onPrePointerObservable.notifyObservers(pi, type);
  22856. if (pi.skipOnPointerObservable) {
  22857. return;
  22858. }
  22859. }
  22860. }
  22861. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22862. return;
  22863. }
  22864. if (!_this.pointerUpPredicate) {
  22865. _this.pointerUpPredicate = function (mesh) {
  22866. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22867. };
  22868. }
  22869. // Meshes
  22870. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22871. _this._initActionManager(null, clickInfo);
  22872. }
  22873. if (!pickResult) {
  22874. pickResult = _this._currentPickResult;
  22875. }
  22876. _this._processPointerUp(pickResult, evt, clickInfo);
  22877. // Sprites
  22878. if (_this.spriteManagers.length > 0) {
  22879. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22880. if (spritePickResult) {
  22881. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22882. if (spritePickResult.pickedSprite.actionManager) {
  22883. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22884. if (spritePickResult.pickedSprite.actionManager) {
  22885. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22886. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22887. }
  22888. }
  22889. }
  22890. }
  22891. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22892. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22893. }
  22894. }
  22895. }
  22896. _this._previousPickResult = _this._currentPickResult;
  22897. });
  22898. };
  22899. this._onKeyDown = function (evt) {
  22900. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22901. if (_this.onPreKeyboardObservable.hasObservers()) {
  22902. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22903. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22904. if (pi.skipOnPointerObservable) {
  22905. return;
  22906. }
  22907. }
  22908. if (_this.onKeyboardObservable.hasObservers()) {
  22909. var pi = new BABYLON.KeyboardInfo(type, evt);
  22910. _this.onKeyboardObservable.notifyObservers(pi, type);
  22911. }
  22912. if (_this.actionManager) {
  22913. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22914. }
  22915. };
  22916. this._onKeyUp = function (evt) {
  22917. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22918. if (_this.onPreKeyboardObservable.hasObservers()) {
  22919. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22920. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22921. if (pi.skipOnPointerObservable) {
  22922. return;
  22923. }
  22924. }
  22925. if (_this.onKeyboardObservable.hasObservers()) {
  22926. var pi = new BABYLON.KeyboardInfo(type, evt);
  22927. _this.onKeyboardObservable.notifyObservers(pi, type);
  22928. }
  22929. if (_this.actionManager) {
  22930. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22931. }
  22932. };
  22933. var engine = this.getEngine();
  22934. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22935. if (!canvas) {
  22936. return;
  22937. }
  22938. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22939. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22940. });
  22941. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22942. if (!canvas) {
  22943. return;
  22944. }
  22945. canvas.removeEventListener("keydown", _this._onKeyDown);
  22946. canvas.removeEventListener("keyup", _this._onKeyUp);
  22947. });
  22948. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22949. var canvas = this._engine.getRenderingCanvas();
  22950. if (!canvas) {
  22951. return;
  22952. }
  22953. if (attachMove) {
  22954. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22955. // Wheel
  22956. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22957. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22958. }
  22959. if (attachDown) {
  22960. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22961. }
  22962. if (attachUp) {
  22963. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22964. }
  22965. canvas.tabIndex = 1;
  22966. };
  22967. Scene.prototype.detachControl = function () {
  22968. var engine = this.getEngine();
  22969. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22970. var canvas = engine.getRenderingCanvas();
  22971. if (!canvas) {
  22972. return;
  22973. }
  22974. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22975. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22976. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22977. if (this._onCanvasBlurObserver) {
  22978. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22979. }
  22980. if (this._onCanvasFocusObserver) {
  22981. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22982. }
  22983. // Wheel
  22984. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22985. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22986. // Keyboard
  22987. canvas.removeEventListener("keydown", this._onKeyDown);
  22988. canvas.removeEventListener("keyup", this._onKeyUp);
  22989. // Observables
  22990. this.onKeyboardObservable.clear();
  22991. this.onPreKeyboardObservable.clear();
  22992. this.onPointerObservable.clear();
  22993. this.onPrePointerObservable.clear();
  22994. };
  22995. /**
  22996. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22997. * Delay loaded resources are not taking in account
  22998. * @return true if all required resources are ready
  22999. */
  23000. Scene.prototype.isReady = function () {
  23001. if (this._isDisposed) {
  23002. return false;
  23003. }
  23004. if (this._pendingData.length > 0) {
  23005. return false;
  23006. }
  23007. var index;
  23008. var engine = this.getEngine();
  23009. // Geometries
  23010. for (index = 0; index < this._geometries.length; index++) {
  23011. var geometry = this._geometries[index];
  23012. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23013. return false;
  23014. }
  23015. }
  23016. // Meshes
  23017. for (index = 0; index < this.meshes.length; index++) {
  23018. var mesh = this.meshes[index];
  23019. if (!mesh.isEnabled()) {
  23020. continue;
  23021. }
  23022. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  23023. continue;
  23024. }
  23025. if (!mesh.isReady(true)) {
  23026. return false;
  23027. }
  23028. // Effect layers
  23029. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  23030. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  23031. var layer = _a[_i];
  23032. if (!layer.hasMesh(mesh)) {
  23033. continue;
  23034. }
  23035. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23036. var subMesh = _c[_b];
  23037. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  23038. return false;
  23039. }
  23040. }
  23041. }
  23042. }
  23043. // Particles
  23044. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  23045. var particleSystem = _e[_d];
  23046. if (!particleSystem.isReady()) {
  23047. return false;
  23048. }
  23049. }
  23050. return true;
  23051. };
  23052. Scene.prototype.resetCachedMaterial = function () {
  23053. this._cachedMaterial = null;
  23054. this._cachedEffect = null;
  23055. this._cachedVisibility = null;
  23056. };
  23057. Scene.prototype.registerBeforeRender = function (func) {
  23058. this.onBeforeRenderObservable.add(func);
  23059. };
  23060. Scene.prototype.unregisterBeforeRender = function (func) {
  23061. this.onBeforeRenderObservable.removeCallback(func);
  23062. };
  23063. Scene.prototype.registerAfterRender = function (func) {
  23064. this.onAfterRenderObservable.add(func);
  23065. };
  23066. Scene.prototype.unregisterAfterRender = function (func) {
  23067. this.onAfterRenderObservable.removeCallback(func);
  23068. };
  23069. Scene.prototype._executeOnceBeforeRender = function (func) {
  23070. var _this = this;
  23071. var execFunc = function () {
  23072. func();
  23073. setTimeout(function () {
  23074. _this.unregisterBeforeRender(execFunc);
  23075. });
  23076. };
  23077. this.registerBeforeRender(execFunc);
  23078. };
  23079. /**
  23080. * The provided function will run before render once and will be disposed afterwards.
  23081. * A timeout delay can be provided so that the function will be executed in N ms.
  23082. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  23083. * @param func The function to be executed.
  23084. * @param timeout optional delay in ms
  23085. */
  23086. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  23087. var _this = this;
  23088. if (timeout !== undefined) {
  23089. setTimeout(function () {
  23090. _this._executeOnceBeforeRender(func);
  23091. }, timeout);
  23092. }
  23093. else {
  23094. this._executeOnceBeforeRender(func);
  23095. }
  23096. };
  23097. Scene.prototype._addPendingData = function (data) {
  23098. this._pendingData.push(data);
  23099. };
  23100. Scene.prototype._removePendingData = function (data) {
  23101. var wasLoading = this.isLoading;
  23102. var index = this._pendingData.indexOf(data);
  23103. if (index !== -1) {
  23104. this._pendingData.splice(index, 1);
  23105. }
  23106. if (wasLoading && !this.isLoading) {
  23107. this.onDataLoadedObservable.notifyObservers(this);
  23108. }
  23109. };
  23110. Scene.prototype.getWaitingItemsCount = function () {
  23111. return this._pendingData.length;
  23112. };
  23113. Object.defineProperty(Scene.prototype, "isLoading", {
  23114. get: function () {
  23115. return this._pendingData.length > 0;
  23116. },
  23117. enumerable: true,
  23118. configurable: true
  23119. });
  23120. /**
  23121. * Registers a function to be executed when the scene is ready.
  23122. * @param {Function} func - the function to be executed.
  23123. */
  23124. Scene.prototype.executeWhenReady = function (func) {
  23125. var _this = this;
  23126. this.onReadyObservable.add(func);
  23127. if (this._executeWhenReadyTimeoutId !== -1) {
  23128. return;
  23129. }
  23130. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23131. _this._checkIsReady();
  23132. }, 150);
  23133. };
  23134. /**
  23135. * Returns a promise that resolves when the scene is ready.
  23136. * @returns A promise that resolves when the scene is ready.
  23137. */
  23138. Scene.prototype.whenReadyAsync = function () {
  23139. var _this = this;
  23140. return new Promise(function (resolve) {
  23141. _this.executeWhenReady(function () {
  23142. resolve();
  23143. });
  23144. });
  23145. };
  23146. Scene.prototype._checkIsReady = function () {
  23147. var _this = this;
  23148. if (this.isReady()) {
  23149. this.onReadyObservable.notifyObservers(this);
  23150. this.onReadyObservable.clear();
  23151. this._executeWhenReadyTimeoutId = -1;
  23152. return;
  23153. }
  23154. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23155. _this._checkIsReady();
  23156. }, 150);
  23157. };
  23158. // Animations
  23159. /**
  23160. * Will start the animation sequence of a given target
  23161. * @param target - the target
  23162. * @param {number} from - from which frame should animation start
  23163. * @param {number} to - till which frame should animation run.
  23164. * @param {boolean} [loop] - should the animation loop
  23165. * @param {number} [speedRatio] - the speed in which to run the animation
  23166. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  23167. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  23168. * Returns {BABYLON.Animatable} the animatable object created for this animation
  23169. * See BABYLON.Animatable
  23170. */
  23171. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  23172. if (speedRatio === void 0) { speedRatio = 1.0; }
  23173. if (from > to && speedRatio > 0) {
  23174. speedRatio *= -1;
  23175. }
  23176. this.stopAnimation(target);
  23177. if (!animatable) {
  23178. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23179. }
  23180. // Local animations
  23181. if (target.animations) {
  23182. animatable.appendAnimations(target, target.animations);
  23183. }
  23184. // Children animations
  23185. if (target.getAnimatables) {
  23186. var animatables = target.getAnimatables();
  23187. for (var index = 0; index < animatables.length; index++) {
  23188. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  23189. }
  23190. }
  23191. animatable.reset();
  23192. return animatable;
  23193. };
  23194. /**
  23195. * Begin a new animation on a given node
  23196. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23197. * @param {BABYLON.Animation[]} defines the list of animations to start
  23198. * @param {number} from defines the initial value
  23199. * @param {number} to defines the final value
  23200. * @param {boolean} loop defines if you want animation to loop (off by default)
  23201. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23202. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23203. * @returns the list of created animatables
  23204. */
  23205. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23206. if (speedRatio === undefined) {
  23207. speedRatio = 1.0;
  23208. }
  23209. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23210. return animatable;
  23211. };
  23212. /**
  23213. * Begin a new animation on a given node and its hierarchy
  23214. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23215. * @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.
  23216. * @param {BABYLON.Animation[]} defines the list of animations to start
  23217. * @param {number} from defines the initial value
  23218. * @param {number} to defines the final value
  23219. * @param {boolean} loop defines if you want animation to loop (off by default)
  23220. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23221. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23222. * @returns the list of animatables created for all nodes
  23223. */
  23224. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23225. var children = target.getDescendants(directDescendantsOnly);
  23226. var result = [];
  23227. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23228. var child = children_1[_i];
  23229. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23230. }
  23231. return result;
  23232. };
  23233. Scene.prototype.getAnimatableByTarget = function (target) {
  23234. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23235. if (this._activeAnimatables[index].target === target) {
  23236. return this._activeAnimatables[index];
  23237. }
  23238. }
  23239. return null;
  23240. };
  23241. Object.defineProperty(Scene.prototype, "animatables", {
  23242. get: function () {
  23243. return this._activeAnimatables;
  23244. },
  23245. enumerable: true,
  23246. configurable: true
  23247. });
  23248. /**
  23249. * Will stop the animation of the given target
  23250. * @param target - the target
  23251. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  23252. * @see beginAnimation
  23253. */
  23254. Scene.prototype.stopAnimation = function (target, animationName) {
  23255. var animatable = this.getAnimatableByTarget(target);
  23256. if (animatable) {
  23257. animatable.stop(animationName);
  23258. }
  23259. };
  23260. /**
  23261. * Stops and removes all animations that have been applied to the scene
  23262. */
  23263. Scene.prototype.stopAllAnimations = function () {
  23264. if (this._activeAnimatables) {
  23265. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23266. this._activeAnimatables[i].stop();
  23267. }
  23268. this._activeAnimatables = [];
  23269. }
  23270. };
  23271. Scene.prototype._animate = function () {
  23272. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23273. return;
  23274. }
  23275. // Getting time
  23276. var now = BABYLON.Tools.Now;
  23277. if (!this._animationTimeLast) {
  23278. if (this._pendingData.length > 0) {
  23279. return;
  23280. }
  23281. this._animationTimeLast = now;
  23282. }
  23283. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23284. this._animationTime += deltaTime;
  23285. this._animationTimeLast = now;
  23286. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23287. this._activeAnimatables[index]._animate(this._animationTime);
  23288. }
  23289. };
  23290. // Matrix
  23291. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23292. this._useAlternateCameraConfiguration = active;
  23293. };
  23294. Scene.prototype.getViewMatrix = function () {
  23295. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23296. };
  23297. Scene.prototype.getProjectionMatrix = function () {
  23298. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23299. };
  23300. Scene.prototype.getTransformMatrix = function () {
  23301. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23302. };
  23303. Scene.prototype.setTransformMatrix = function (view, projection) {
  23304. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23305. return;
  23306. }
  23307. this._viewUpdateFlag = view.updateFlag;
  23308. this._projectionUpdateFlag = projection.updateFlag;
  23309. this._viewMatrix = view;
  23310. this._projectionMatrix = projection;
  23311. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23312. // Update frustum
  23313. if (!this._frustumPlanes) {
  23314. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23315. }
  23316. else {
  23317. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23318. }
  23319. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23320. var otherCamera = this.activeCamera._alternateCamera;
  23321. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23322. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23323. }
  23324. if (this._sceneUbo.useUbo) {
  23325. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23326. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23327. this._sceneUbo.update();
  23328. }
  23329. };
  23330. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23331. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23332. return;
  23333. }
  23334. this._alternateViewUpdateFlag = view.updateFlag;
  23335. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23336. this._alternateViewMatrix = view;
  23337. this._alternateProjectionMatrix = projection;
  23338. if (!this._alternateTransformMatrix) {
  23339. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23340. }
  23341. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23342. if (!this._alternateSceneUbo) {
  23343. this._createAlternateUbo();
  23344. }
  23345. if (this._alternateSceneUbo.useUbo) {
  23346. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23347. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23348. this._alternateSceneUbo.update();
  23349. }
  23350. };
  23351. Scene.prototype.getSceneUniformBuffer = function () {
  23352. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23353. };
  23354. // Methods
  23355. Scene.prototype.getUniqueId = function () {
  23356. var result = Scene._uniqueIdCounter;
  23357. Scene._uniqueIdCounter++;
  23358. return result;
  23359. };
  23360. Scene.prototype.addMesh = function (newMesh) {
  23361. this.meshes.push(newMesh);
  23362. //notify the collision coordinator
  23363. if (this.collisionCoordinator) {
  23364. this.collisionCoordinator.onMeshAdded(newMesh);
  23365. }
  23366. newMesh._resyncLightSources();
  23367. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23368. };
  23369. Scene.prototype.removeMesh = function (toRemove) {
  23370. var index = this.meshes.indexOf(toRemove);
  23371. if (index !== -1) {
  23372. // Remove from the scene if mesh found
  23373. this.meshes.splice(index, 1);
  23374. }
  23375. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23376. return index;
  23377. };
  23378. Scene.prototype.addTransformNode = function (newTransformNode) {
  23379. this.transformNodes.push(newTransformNode);
  23380. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23381. };
  23382. Scene.prototype.removeTransformNode = function (toRemove) {
  23383. var index = this.transformNodes.indexOf(toRemove);
  23384. if (index !== -1) {
  23385. // Remove from the scene if found
  23386. this.transformNodes.splice(index, 1);
  23387. }
  23388. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23389. return index;
  23390. };
  23391. Scene.prototype.removeSkeleton = function (toRemove) {
  23392. var index = this.skeletons.indexOf(toRemove);
  23393. if (index !== -1) {
  23394. // Remove from the scene if found
  23395. this.skeletons.splice(index, 1);
  23396. }
  23397. return index;
  23398. };
  23399. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23400. var index = this.morphTargetManagers.indexOf(toRemove);
  23401. if (index !== -1) {
  23402. // Remove from the scene if found
  23403. this.morphTargetManagers.splice(index, 1);
  23404. }
  23405. return index;
  23406. };
  23407. Scene.prototype.removeLight = function (toRemove) {
  23408. var index = this.lights.indexOf(toRemove);
  23409. if (index !== -1) {
  23410. // Remove from meshes
  23411. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23412. var mesh = _a[_i];
  23413. mesh._removeLightSource(toRemove);
  23414. }
  23415. // Remove from the scene if mesh found
  23416. this.lights.splice(index, 1);
  23417. this.sortLightsByPriority();
  23418. }
  23419. this.onLightRemovedObservable.notifyObservers(toRemove);
  23420. return index;
  23421. };
  23422. Scene.prototype.removeCamera = function (toRemove) {
  23423. var index = this.cameras.indexOf(toRemove);
  23424. if (index !== -1) {
  23425. // Remove from the scene if mesh found
  23426. this.cameras.splice(index, 1);
  23427. }
  23428. // Remove from activeCameras
  23429. var index2 = this.activeCameras.indexOf(toRemove);
  23430. if (index2 !== -1) {
  23431. // Remove from the scene if mesh found
  23432. this.activeCameras.splice(index2, 1);
  23433. }
  23434. // Reset the activeCamera
  23435. if (this.activeCamera === toRemove) {
  23436. if (this.cameras.length > 0) {
  23437. this.activeCamera = this.cameras[0];
  23438. }
  23439. else {
  23440. this.activeCamera = null;
  23441. }
  23442. }
  23443. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23444. return index;
  23445. };
  23446. Scene.prototype.removeParticleSystem = function (toRemove) {
  23447. var index = this.particleSystems.indexOf(toRemove);
  23448. if (index !== -1) {
  23449. this.particleSystems.splice(index, 1);
  23450. }
  23451. return index;
  23452. };
  23453. ;
  23454. Scene.prototype.removeAnimation = function (toRemove) {
  23455. var index = this.animations.indexOf(toRemove);
  23456. if (index !== -1) {
  23457. this.animations.splice(index, 1);
  23458. }
  23459. return index;
  23460. };
  23461. ;
  23462. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23463. var index = this.multiMaterials.indexOf(toRemove);
  23464. if (index !== -1) {
  23465. this.multiMaterials.splice(index, 1);
  23466. }
  23467. return index;
  23468. };
  23469. ;
  23470. Scene.prototype.removeMaterial = function (toRemove) {
  23471. var index = this.materials.indexOf(toRemove);
  23472. if (index !== -1) {
  23473. this.materials.splice(index, 1);
  23474. }
  23475. return index;
  23476. };
  23477. ;
  23478. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23479. var index = this.lensFlareSystems.indexOf(toRemove);
  23480. if (index !== -1) {
  23481. this.lensFlareSystems.splice(index, 1);
  23482. }
  23483. return index;
  23484. };
  23485. ;
  23486. Scene.prototype.removeActionManager = function (toRemove) {
  23487. var index = this._actionManagers.indexOf(toRemove);
  23488. if (index !== -1) {
  23489. this._actionManagers.splice(index, 1);
  23490. }
  23491. return index;
  23492. };
  23493. ;
  23494. Scene.prototype.addLight = function (newLight) {
  23495. this.lights.push(newLight);
  23496. this.sortLightsByPriority();
  23497. // Add light to all meshes (To support if the light is removed and then readded)
  23498. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23499. var mesh = _a[_i];
  23500. if (mesh._lightSources.indexOf(newLight) === -1) {
  23501. mesh._lightSources.push(newLight);
  23502. mesh._resyncLightSources();
  23503. }
  23504. }
  23505. this.onNewLightAddedObservable.notifyObservers(newLight);
  23506. };
  23507. Scene.prototype.sortLightsByPriority = function () {
  23508. if (this.requireLightSorting) {
  23509. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23510. }
  23511. };
  23512. Scene.prototype.addCamera = function (newCamera) {
  23513. this.cameras.push(newCamera);
  23514. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23515. };
  23516. Scene.prototype.addSkeleton = function (newSkeleton) {
  23517. this.skeletons.push(newSkeleton);
  23518. };
  23519. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23520. this.particleSystems.push(newParticleSystem);
  23521. };
  23522. Scene.prototype.addAnimation = function (newAnimation) {
  23523. this.animations.push(newAnimation);
  23524. };
  23525. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23526. this.multiMaterials.push(newMultiMaterial);
  23527. };
  23528. Scene.prototype.addMaterial = function (newMaterial) {
  23529. this.materials.push(newMaterial);
  23530. };
  23531. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23532. this.morphTargetManagers.push(newMorphTargetManager);
  23533. };
  23534. Scene.prototype.addGeometry = function (newGeometrie) {
  23535. this._geometries.push(newGeometrie);
  23536. };
  23537. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23538. this.lensFlareSystems.push(newLensFlareSystem);
  23539. };
  23540. Scene.prototype.addActionManager = function (newActionManager) {
  23541. this._actionManagers.push(newActionManager);
  23542. };
  23543. /**
  23544. * Switch active camera
  23545. * @param {Camera} newCamera - new active camera
  23546. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23547. */
  23548. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23549. if (attachControl === void 0) { attachControl = true; }
  23550. var canvas = this._engine.getRenderingCanvas();
  23551. if (!canvas) {
  23552. return;
  23553. }
  23554. if (this.activeCamera) {
  23555. this.activeCamera.detachControl(canvas);
  23556. }
  23557. this.activeCamera = newCamera;
  23558. if (attachControl) {
  23559. newCamera.attachControl(canvas);
  23560. }
  23561. };
  23562. /**
  23563. * sets the active camera of the scene using its ID
  23564. * @param {string} id - the camera's ID
  23565. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23566. * @see activeCamera
  23567. */
  23568. Scene.prototype.setActiveCameraByID = function (id) {
  23569. var camera = this.getCameraByID(id);
  23570. if (camera) {
  23571. this.activeCamera = camera;
  23572. return camera;
  23573. }
  23574. return null;
  23575. };
  23576. /**
  23577. * sets the active camera of the scene using its name
  23578. * @param {string} name - the camera's name
  23579. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23580. * @see activeCamera
  23581. */
  23582. Scene.prototype.setActiveCameraByName = function (name) {
  23583. var camera = this.getCameraByName(name);
  23584. if (camera) {
  23585. this.activeCamera = camera;
  23586. return camera;
  23587. }
  23588. return null;
  23589. };
  23590. /**
  23591. * get an animation group using its name
  23592. * @param {string} the material's name
  23593. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23594. */
  23595. Scene.prototype.getAnimationGroupByName = function (name) {
  23596. for (var index = 0; index < this.animationGroups.length; index++) {
  23597. if (this.animationGroups[index].name === name) {
  23598. return this.animationGroups[index];
  23599. }
  23600. }
  23601. return null;
  23602. };
  23603. /**
  23604. * get a material using its id
  23605. * @param {string} the material's ID
  23606. * @return {BABYLON.Material|null} the material or null if none found.
  23607. */
  23608. Scene.prototype.getMaterialByID = function (id) {
  23609. for (var index = 0; index < this.materials.length; index++) {
  23610. if (this.materials[index].id === id) {
  23611. return this.materials[index];
  23612. }
  23613. }
  23614. return null;
  23615. };
  23616. /**
  23617. * get a material using its name
  23618. * @param {string} the material's name
  23619. * @return {BABYLON.Material|null} the material or null if none found.
  23620. */
  23621. Scene.prototype.getMaterialByName = function (name) {
  23622. for (var index = 0; index < this.materials.length; index++) {
  23623. if (this.materials[index].name === name) {
  23624. return this.materials[index];
  23625. }
  23626. }
  23627. return null;
  23628. };
  23629. Scene.prototype.getLensFlareSystemByName = function (name) {
  23630. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23631. if (this.lensFlareSystems[index].name === name) {
  23632. return this.lensFlareSystems[index];
  23633. }
  23634. }
  23635. return null;
  23636. };
  23637. Scene.prototype.getLensFlareSystemByID = function (id) {
  23638. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23639. if (this.lensFlareSystems[index].id === id) {
  23640. return this.lensFlareSystems[index];
  23641. }
  23642. }
  23643. return null;
  23644. };
  23645. Scene.prototype.getCameraByID = function (id) {
  23646. for (var index = 0; index < this.cameras.length; index++) {
  23647. if (this.cameras[index].id === id) {
  23648. return this.cameras[index];
  23649. }
  23650. }
  23651. return null;
  23652. };
  23653. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23654. for (var index = 0; index < this.cameras.length; index++) {
  23655. if (this.cameras[index].uniqueId === uniqueId) {
  23656. return this.cameras[index];
  23657. }
  23658. }
  23659. return null;
  23660. };
  23661. /**
  23662. * get a camera using its name
  23663. * @param {string} the camera's name
  23664. * @return {BABYLON.Camera|null} the camera or null if none found.
  23665. */
  23666. Scene.prototype.getCameraByName = function (name) {
  23667. for (var index = 0; index < this.cameras.length; index++) {
  23668. if (this.cameras[index].name === name) {
  23669. return this.cameras[index];
  23670. }
  23671. }
  23672. return null;
  23673. };
  23674. /**
  23675. * get a bone using its id
  23676. * @param {string} the bone's id
  23677. * @return {BABYLON.Bone|null} the bone or null if not found
  23678. */
  23679. Scene.prototype.getBoneByID = function (id) {
  23680. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23681. var skeleton = this.skeletons[skeletonIndex];
  23682. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23683. if (skeleton.bones[boneIndex].id === id) {
  23684. return skeleton.bones[boneIndex];
  23685. }
  23686. }
  23687. }
  23688. return null;
  23689. };
  23690. /**
  23691. * get a bone using its id
  23692. * @param {string} the bone's name
  23693. * @return {BABYLON.Bone|null} the bone or null if not found
  23694. */
  23695. Scene.prototype.getBoneByName = function (name) {
  23696. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23697. var skeleton = this.skeletons[skeletonIndex];
  23698. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23699. if (skeleton.bones[boneIndex].name === name) {
  23700. return skeleton.bones[boneIndex];
  23701. }
  23702. }
  23703. }
  23704. return null;
  23705. };
  23706. /**
  23707. * get a light node using its name
  23708. * @param {string} the light's name
  23709. * @return {BABYLON.Light|null} the light or null if none found.
  23710. */
  23711. Scene.prototype.getLightByName = function (name) {
  23712. for (var index = 0; index < this.lights.length; index++) {
  23713. if (this.lights[index].name === name) {
  23714. return this.lights[index];
  23715. }
  23716. }
  23717. return null;
  23718. };
  23719. /**
  23720. * get a light node using its ID
  23721. * @param {string} the light's id
  23722. * @return {BABYLON.Light|null} the light or null if none found.
  23723. */
  23724. Scene.prototype.getLightByID = function (id) {
  23725. for (var index = 0; index < this.lights.length; index++) {
  23726. if (this.lights[index].id === id) {
  23727. return this.lights[index];
  23728. }
  23729. }
  23730. return null;
  23731. };
  23732. /**
  23733. * get a light node using its scene-generated unique ID
  23734. * @param {number} the light's unique id
  23735. * @return {BABYLON.Light|null} the light or null if none found.
  23736. */
  23737. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23738. for (var index = 0; index < this.lights.length; index++) {
  23739. if (this.lights[index].uniqueId === uniqueId) {
  23740. return this.lights[index];
  23741. }
  23742. }
  23743. return null;
  23744. };
  23745. /**
  23746. * get a particle system by id
  23747. * @param id {number} the particle system id
  23748. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23749. */
  23750. Scene.prototype.getParticleSystemByID = function (id) {
  23751. for (var index = 0; index < this.particleSystems.length; index++) {
  23752. if (this.particleSystems[index].id === id) {
  23753. return this.particleSystems[index];
  23754. }
  23755. }
  23756. return null;
  23757. };
  23758. /**
  23759. * get a geometry using its ID
  23760. * @param {string} the geometry's id
  23761. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23762. */
  23763. Scene.prototype.getGeometryByID = function (id) {
  23764. for (var index = 0; index < this._geometries.length; index++) {
  23765. if (this._geometries[index].id === id) {
  23766. return this._geometries[index];
  23767. }
  23768. }
  23769. return null;
  23770. };
  23771. /**
  23772. * add a new geometry to this scene.
  23773. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23774. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23775. * @return {boolean} was the geometry added or not
  23776. */
  23777. Scene.prototype.pushGeometry = function (geometry, force) {
  23778. if (!force && this.getGeometryByID(geometry.id)) {
  23779. return false;
  23780. }
  23781. this._geometries.push(geometry);
  23782. //notify the collision coordinator
  23783. if (this.collisionCoordinator) {
  23784. this.collisionCoordinator.onGeometryAdded(geometry);
  23785. }
  23786. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23787. return true;
  23788. };
  23789. /**
  23790. * Removes an existing geometry
  23791. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23792. * @return {boolean} was the geometry removed or not
  23793. */
  23794. Scene.prototype.removeGeometry = function (geometry) {
  23795. var index = this._geometries.indexOf(geometry);
  23796. if (index > -1) {
  23797. this._geometries.splice(index, 1);
  23798. //notify the collision coordinator
  23799. if (this.collisionCoordinator) {
  23800. this.collisionCoordinator.onGeometryDeleted(geometry);
  23801. }
  23802. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23803. return true;
  23804. }
  23805. return false;
  23806. };
  23807. Scene.prototype.getGeometries = function () {
  23808. return this._geometries;
  23809. };
  23810. /**
  23811. * Get the first added mesh found of a given ID
  23812. * @param {string} id - the id to search for
  23813. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23814. */
  23815. Scene.prototype.getMeshByID = function (id) {
  23816. for (var index = 0; index < this.meshes.length; index++) {
  23817. if (this.meshes[index].id === id) {
  23818. return this.meshes[index];
  23819. }
  23820. }
  23821. return null;
  23822. };
  23823. Scene.prototype.getMeshesByID = function (id) {
  23824. return this.meshes.filter(function (m) {
  23825. return m.id === id;
  23826. });
  23827. };
  23828. /**
  23829. * Get the first added transform node found of a given ID
  23830. * @param {string} id - the id to search for
  23831. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23832. */
  23833. Scene.prototype.getTransformNodeByID = function (id) {
  23834. for (var index = 0; index < this.transformNodes.length; index++) {
  23835. if (this.transformNodes[index].id === id) {
  23836. return this.transformNodes[index];
  23837. }
  23838. }
  23839. return null;
  23840. };
  23841. Scene.prototype.getTransformNodesByID = function (id) {
  23842. return this.transformNodes.filter(function (m) {
  23843. return m.id === id;
  23844. });
  23845. };
  23846. /**
  23847. * Get a mesh with its auto-generated unique id
  23848. * @param {number} uniqueId - the unique id to search for
  23849. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23850. */
  23851. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23852. for (var index = 0; index < this.meshes.length; index++) {
  23853. if (this.meshes[index].uniqueId === uniqueId) {
  23854. return this.meshes[index];
  23855. }
  23856. }
  23857. return null;
  23858. };
  23859. /**
  23860. * Get a the last added mesh found of a given ID
  23861. * @param {string} id - the id to search for
  23862. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23863. */
  23864. Scene.prototype.getLastMeshByID = function (id) {
  23865. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23866. if (this.meshes[index].id === id) {
  23867. return this.meshes[index];
  23868. }
  23869. }
  23870. return null;
  23871. };
  23872. /**
  23873. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23874. * @param {string} id - the id to search for
  23875. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23876. */
  23877. Scene.prototype.getLastEntryByID = function (id) {
  23878. var index;
  23879. for (index = this.meshes.length - 1; index >= 0; index--) {
  23880. if (this.meshes[index].id === id) {
  23881. return this.meshes[index];
  23882. }
  23883. }
  23884. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23885. if (this.transformNodes[index].id === id) {
  23886. return this.transformNodes[index];
  23887. }
  23888. }
  23889. for (index = this.cameras.length - 1; index >= 0; index--) {
  23890. if (this.cameras[index].id === id) {
  23891. return this.cameras[index];
  23892. }
  23893. }
  23894. for (index = this.lights.length - 1; index >= 0; index--) {
  23895. if (this.lights[index].id === id) {
  23896. return this.lights[index];
  23897. }
  23898. }
  23899. return null;
  23900. };
  23901. Scene.prototype.getNodeByID = function (id) {
  23902. var mesh = this.getMeshByID(id);
  23903. if (mesh) {
  23904. return mesh;
  23905. }
  23906. var light = this.getLightByID(id);
  23907. if (light) {
  23908. return light;
  23909. }
  23910. var camera = this.getCameraByID(id);
  23911. if (camera) {
  23912. return camera;
  23913. }
  23914. var bone = this.getBoneByID(id);
  23915. return bone;
  23916. };
  23917. Scene.prototype.getNodeByName = function (name) {
  23918. var mesh = this.getMeshByName(name);
  23919. if (mesh) {
  23920. return mesh;
  23921. }
  23922. var light = this.getLightByName(name);
  23923. if (light) {
  23924. return light;
  23925. }
  23926. var camera = this.getCameraByName(name);
  23927. if (camera) {
  23928. return camera;
  23929. }
  23930. var bone = this.getBoneByName(name);
  23931. return bone;
  23932. };
  23933. Scene.prototype.getMeshByName = function (name) {
  23934. for (var index = 0; index < this.meshes.length; index++) {
  23935. if (this.meshes[index].name === name) {
  23936. return this.meshes[index];
  23937. }
  23938. }
  23939. return null;
  23940. };
  23941. Scene.prototype.getTransformNodeByName = function (name) {
  23942. for (var index = 0; index < this.transformNodes.length; index++) {
  23943. if (this.transformNodes[index].name === name) {
  23944. return this.transformNodes[index];
  23945. }
  23946. }
  23947. return null;
  23948. };
  23949. Scene.prototype.getSoundByName = function (name) {
  23950. var index;
  23951. if (BABYLON.AudioEngine) {
  23952. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23953. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23954. return this.mainSoundTrack.soundCollection[index];
  23955. }
  23956. }
  23957. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23958. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23959. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23960. return this.soundTracks[sdIndex].soundCollection[index];
  23961. }
  23962. }
  23963. }
  23964. }
  23965. return null;
  23966. };
  23967. Scene.prototype.getLastSkeletonByID = function (id) {
  23968. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23969. if (this.skeletons[index].id === id) {
  23970. return this.skeletons[index];
  23971. }
  23972. }
  23973. return null;
  23974. };
  23975. Scene.prototype.getSkeletonById = function (id) {
  23976. for (var index = 0; index < this.skeletons.length; index++) {
  23977. if (this.skeletons[index].id === id) {
  23978. return this.skeletons[index];
  23979. }
  23980. }
  23981. return null;
  23982. };
  23983. Scene.prototype.getSkeletonByName = function (name) {
  23984. for (var index = 0; index < this.skeletons.length; index++) {
  23985. if (this.skeletons[index].name === name) {
  23986. return this.skeletons[index];
  23987. }
  23988. }
  23989. return null;
  23990. };
  23991. Scene.prototype.getMorphTargetManagerById = function (id) {
  23992. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23993. if (this.morphTargetManagers[index].uniqueId === id) {
  23994. return this.morphTargetManagers[index];
  23995. }
  23996. }
  23997. return null;
  23998. };
  23999. Scene.prototype.isActiveMesh = function (mesh) {
  24000. return (this._activeMeshes.indexOf(mesh) !== -1);
  24001. };
  24002. /**
  24003. * Return a the first highlight layer of the scene with a given name.
  24004. * @param name The name of the highlight layer to look for.
  24005. * @return The highlight layer if found otherwise null.
  24006. */
  24007. Scene.prototype.getHighlightLayerByName = function (name) {
  24008. for (var index = 0; index < this.effectLayers.length; index++) {
  24009. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  24010. return this.effectLayers[index];
  24011. }
  24012. }
  24013. return null;
  24014. };
  24015. /**
  24016. * Return a the first highlight layer of the scene with a given name.
  24017. * @param name The name of the highlight layer to look for.
  24018. * @return The highlight layer if found otherwise null.
  24019. */
  24020. Scene.prototype.getGlowLayerByName = function (name) {
  24021. for (var index = 0; index < this.effectLayers.length; index++) {
  24022. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  24023. return this.effectLayers[index];
  24024. }
  24025. }
  24026. return null;
  24027. };
  24028. Object.defineProperty(Scene.prototype, "uid", {
  24029. /**
  24030. * Return a unique id as a string which can serve as an identifier for the scene
  24031. */
  24032. get: function () {
  24033. if (!this._uid) {
  24034. this._uid = BABYLON.Tools.RandomId();
  24035. }
  24036. return this._uid;
  24037. },
  24038. enumerable: true,
  24039. configurable: true
  24040. });
  24041. /**
  24042. * Add an externaly attached data from its key.
  24043. * This method call will fail and return false, if such key already exists.
  24044. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  24045. * @param key the unique key that identifies the data
  24046. * @param data the data object to associate to the key for this Engine instance
  24047. * @return true if no such key were already present and the data was added successfully, false otherwise
  24048. */
  24049. Scene.prototype.addExternalData = function (key, data) {
  24050. if (!this._externalData) {
  24051. this._externalData = new BABYLON.StringDictionary();
  24052. }
  24053. return this._externalData.add(key, data);
  24054. };
  24055. /**
  24056. * Get an externaly attached data from its key
  24057. * @param key the unique key that identifies the data
  24058. * @return the associated data, if present (can be null), or undefined if not present
  24059. */
  24060. Scene.prototype.getExternalData = function (key) {
  24061. if (!this._externalData) {
  24062. return null;
  24063. }
  24064. return this._externalData.get(key);
  24065. };
  24066. /**
  24067. * Get an externaly attached data from its key, create it using a factory if it's not already present
  24068. * @param key the unique key that identifies the data
  24069. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  24070. * @return the associated data, can be null if the factory returned null.
  24071. */
  24072. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  24073. if (!this._externalData) {
  24074. this._externalData = new BABYLON.StringDictionary();
  24075. }
  24076. return this._externalData.getOrAddWithFactory(key, factory);
  24077. };
  24078. /**
  24079. * Remove an externaly attached data from the Engine instance
  24080. * @param key the unique key that identifies the data
  24081. * @return true if the data was successfully removed, false if it doesn't exist
  24082. */
  24083. Scene.prototype.removeExternalData = function (key) {
  24084. return this._externalData.remove(key);
  24085. };
  24086. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  24087. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  24088. if (mesh.showSubMeshesBoundingBox) {
  24089. var boundingInfo = subMesh.getBoundingInfo();
  24090. if (boundingInfo !== null && boundingInfo !== undefined) {
  24091. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24092. }
  24093. }
  24094. var material = subMesh.getMaterial();
  24095. if (material !== null && material !== undefined) {
  24096. // Render targets
  24097. if (material.getRenderTargetTextures !== undefined) {
  24098. if (this._processedMaterials.indexOf(material) === -1) {
  24099. this._processedMaterials.push(material);
  24100. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  24101. }
  24102. }
  24103. // Dispatch
  24104. this._activeIndices.addCount(subMesh.indexCount, false);
  24105. this._renderingManager.dispatch(subMesh, mesh, material);
  24106. }
  24107. }
  24108. };
  24109. /**
  24110. * Clear the processed materials smart array preventing retention point in material dispose.
  24111. */
  24112. Scene.prototype.freeProcessedMaterials = function () {
  24113. this._processedMaterials.dispose();
  24114. };
  24115. /**
  24116. * Clear the active meshes smart array preventing retention point in mesh dispose.
  24117. */
  24118. Scene.prototype.freeActiveMeshes = function () {
  24119. this._activeMeshes.dispose();
  24120. if (this.activeCamera && this.activeCamera._activeMeshes) {
  24121. this.activeCamera._activeMeshes.dispose();
  24122. }
  24123. if (this.activeCameras) {
  24124. for (var i = 0; i < this.activeCameras.length; i++) {
  24125. var activeCamera = this.activeCameras[i];
  24126. if (activeCamera && activeCamera._activeMeshes) {
  24127. activeCamera._activeMeshes.dispose();
  24128. }
  24129. }
  24130. }
  24131. };
  24132. /**
  24133. * Clear the info related to rendering groups preventing retention points during dispose.
  24134. */
  24135. Scene.prototype.freeRenderingGroups = function () {
  24136. if (this._renderingManager) {
  24137. this._renderingManager.freeRenderingGroups();
  24138. }
  24139. if (this.textures) {
  24140. for (var i = 0; i < this.textures.length; i++) {
  24141. var texture = this.textures[i];
  24142. if (texture && texture.renderList) {
  24143. texture.freeRenderingGroups();
  24144. }
  24145. }
  24146. }
  24147. };
  24148. Scene.prototype._isInIntermediateRendering = function () {
  24149. return this._intermediateRendering;
  24150. };
  24151. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24152. this._activeMeshCandidateProvider = provider;
  24153. };
  24154. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24155. return this._activeMeshCandidateProvider;
  24156. };
  24157. /**
  24158. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24159. */
  24160. Scene.prototype.freezeActiveMeshes = function () {
  24161. if (!this.activeCamera) {
  24162. return this;
  24163. }
  24164. if (!this._frustumPlanes) {
  24165. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24166. }
  24167. this._evaluateActiveMeshes();
  24168. this._activeMeshesFrozen = true;
  24169. return this;
  24170. };
  24171. /**
  24172. * Use this function to restart evaluating active meshes on every frame
  24173. */
  24174. Scene.prototype.unfreezeActiveMeshes = function () {
  24175. this._activeMeshesFrozen = false;
  24176. return this;
  24177. };
  24178. Scene.prototype._evaluateActiveMeshes = function () {
  24179. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24180. return;
  24181. }
  24182. if (!this.activeCamera) {
  24183. return;
  24184. }
  24185. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24186. this.activeCamera._activeMeshes.reset();
  24187. this._activeMeshes.reset();
  24188. this._renderingManager.reset();
  24189. this._processedMaterials.reset();
  24190. this._activeParticleSystems.reset();
  24191. this._activeSkeletons.reset();
  24192. this._softwareSkinnedMeshes.reset();
  24193. if (this._boundingBoxRenderer) {
  24194. this._boundingBoxRenderer.reset();
  24195. }
  24196. // Meshes
  24197. var meshes;
  24198. var len;
  24199. var checkIsEnabled = true;
  24200. // Determine mesh candidates
  24201. if (this._activeMeshCandidateProvider !== undefined) {
  24202. // Use _activeMeshCandidateProvider
  24203. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24204. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24205. if (meshes !== undefined) {
  24206. len = meshes.length;
  24207. }
  24208. else {
  24209. len = 0;
  24210. }
  24211. }
  24212. else if (this._selectionOctree !== undefined) {
  24213. // Octree
  24214. var selection = this._selectionOctree.select(this._frustumPlanes);
  24215. meshes = selection.data;
  24216. len = selection.length;
  24217. }
  24218. else {
  24219. // Full scene traversal
  24220. len = this.meshes.length;
  24221. meshes = this.meshes;
  24222. }
  24223. // Check each mesh
  24224. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24225. mesh = meshes[meshIndex];
  24226. if (mesh.isBlocked) {
  24227. continue;
  24228. }
  24229. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24230. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24231. continue;
  24232. }
  24233. mesh.computeWorldMatrix();
  24234. // Intersections
  24235. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24236. this._meshesForIntersections.pushNoDuplicate(mesh);
  24237. }
  24238. // Switch to current LOD
  24239. meshLOD = mesh.getLOD(this.activeCamera);
  24240. if (meshLOD === undefined || meshLOD === null) {
  24241. continue;
  24242. }
  24243. mesh._preActivate();
  24244. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24245. this._activeMeshes.push(mesh);
  24246. this.activeCamera._activeMeshes.push(mesh);
  24247. mesh._activate(this._renderId);
  24248. if (meshLOD !== mesh) {
  24249. meshLOD._activate(this._renderId);
  24250. }
  24251. this._activeMesh(mesh, meshLOD);
  24252. }
  24253. }
  24254. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24255. // Particle systems
  24256. if (this.particlesEnabled) {
  24257. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24258. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24259. var particleSystem = this.particleSystems[particleIndex];
  24260. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24261. continue;
  24262. }
  24263. var emitter = particleSystem.emitter;
  24264. if (!emitter.position || emitter.isEnabled()) {
  24265. this._activeParticleSystems.push(particleSystem);
  24266. particleSystem.animate();
  24267. this._renderingManager.dispatchParticles(particleSystem);
  24268. }
  24269. }
  24270. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24271. }
  24272. };
  24273. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24274. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24275. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24276. mesh.skeleton.prepare();
  24277. }
  24278. if (!mesh.computeBonesUsingShaders) {
  24279. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24280. }
  24281. }
  24282. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24283. var boundingInfo = sourceMesh.getBoundingInfo();
  24284. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24285. }
  24286. if (mesh !== undefined && mesh !== null
  24287. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24288. // Submeshes Octrees
  24289. var len;
  24290. var subMeshes;
  24291. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24292. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24293. len = intersections.length;
  24294. subMeshes = intersections.data;
  24295. }
  24296. else {
  24297. subMeshes = mesh.subMeshes;
  24298. len = subMeshes.length;
  24299. }
  24300. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24301. subMesh = subMeshes[subIndex];
  24302. this._evaluateSubMesh(subMesh, mesh);
  24303. }
  24304. }
  24305. };
  24306. Scene.prototype.updateTransformMatrix = function (force) {
  24307. if (!this.activeCamera) {
  24308. return;
  24309. }
  24310. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24311. };
  24312. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24313. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24314. };
  24315. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24316. if (camera && camera._skipRendering) {
  24317. return;
  24318. }
  24319. var engine = this._engine;
  24320. this.activeCamera = camera;
  24321. if (!this.activeCamera)
  24322. throw new Error("Active camera not set");
  24323. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24324. // Viewport
  24325. engine.setViewport(this.activeCamera.viewport);
  24326. // Camera
  24327. this.resetCachedMaterial();
  24328. this._renderId++;
  24329. this.updateTransformMatrix();
  24330. if (camera._alternateCamera) {
  24331. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24332. this._alternateRendering = true;
  24333. }
  24334. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24335. // Meshes
  24336. this._evaluateActiveMeshes();
  24337. // Software skinning
  24338. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24339. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24340. mesh.applySkeleton(mesh.skeleton);
  24341. }
  24342. // Render targets
  24343. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24344. var needsRestoreFrameBuffer = false;
  24345. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24346. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24347. }
  24348. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24349. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24350. }
  24351. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24352. this._intermediateRendering = true;
  24353. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24354. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24355. var renderTarget = this._renderTargets.data[renderIndex];
  24356. if (renderTarget._shouldRender()) {
  24357. this._renderId++;
  24358. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24359. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24360. }
  24361. }
  24362. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24363. this._intermediateRendering = false;
  24364. this._renderId++;
  24365. needsRestoreFrameBuffer = true; // Restore back buffer
  24366. }
  24367. // Render EffecttLayer Texture
  24368. var stencilState = this._engine.getStencilBuffer();
  24369. var renderEffects = false;
  24370. var needStencil = false;
  24371. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24372. this._intermediateRendering = true;
  24373. for (var i = 0; i < this.effectLayers.length; i++) {
  24374. var effectLayer = this.effectLayers[i];
  24375. if (effectLayer.shouldRender() &&
  24376. (!effectLayer.camera ||
  24377. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24378. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24379. renderEffects = true;
  24380. needStencil = needStencil || effectLayer.needStencil();
  24381. var renderTarget = effectLayer._mainTexture;
  24382. if (renderTarget._shouldRender()) {
  24383. this._renderId++;
  24384. renderTarget.render(false, false);
  24385. needsRestoreFrameBuffer = true;
  24386. }
  24387. }
  24388. }
  24389. this._intermediateRendering = false;
  24390. this._renderId++;
  24391. }
  24392. if (needsRestoreFrameBuffer) {
  24393. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24394. }
  24395. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24396. // Prepare Frame
  24397. this.postProcessManager._prepareFrame();
  24398. // Backgrounds
  24399. var layerIndex;
  24400. var layer;
  24401. if (this.layers.length) {
  24402. engine.setDepthBuffer(false);
  24403. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24404. layer = this.layers[layerIndex];
  24405. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24406. layer.render();
  24407. }
  24408. }
  24409. engine.setDepthBuffer(true);
  24410. }
  24411. // Activate effect Layer stencil
  24412. if (needStencil) {
  24413. this._engine.setStencilBuffer(true);
  24414. }
  24415. // Render
  24416. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24417. this._renderingManager.render(null, null, true, true);
  24418. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24419. // Restore effect Layer stencil
  24420. if (needStencil) {
  24421. this._engine.setStencilBuffer(stencilState);
  24422. }
  24423. // Bounding boxes
  24424. if (this._boundingBoxRenderer) {
  24425. this._boundingBoxRenderer.render();
  24426. }
  24427. // Lens flares
  24428. if (this.lensFlaresEnabled) {
  24429. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24430. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24431. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24432. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24433. lensFlareSystem.render();
  24434. }
  24435. }
  24436. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24437. }
  24438. // Foregrounds
  24439. if (this.layers.length) {
  24440. engine.setDepthBuffer(false);
  24441. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24442. layer = this.layers[layerIndex];
  24443. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24444. layer.render();
  24445. }
  24446. }
  24447. engine.setDepthBuffer(true);
  24448. }
  24449. // Effect Layer
  24450. if (renderEffects) {
  24451. engine.setDepthBuffer(false);
  24452. for (var i = 0; i < this.effectLayers.length; i++) {
  24453. if (this.effectLayers[i].shouldRender()) {
  24454. this.effectLayers[i].render();
  24455. }
  24456. }
  24457. engine.setDepthBuffer(true);
  24458. }
  24459. // Finalize frame
  24460. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24461. // Reset some special arrays
  24462. this._renderTargets.reset();
  24463. this._alternateRendering = false;
  24464. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24465. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24466. };
  24467. Scene.prototype._processSubCameras = function (camera) {
  24468. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24469. this._renderForCamera(camera);
  24470. return;
  24471. }
  24472. // rig cameras
  24473. for (var index = 0; index < camera._rigCameras.length; index++) {
  24474. this._renderForCamera(camera._rigCameras[index], camera);
  24475. }
  24476. this.activeCamera = camera;
  24477. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24478. };
  24479. Scene.prototype._checkIntersections = function () {
  24480. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24481. var sourceMesh = this._meshesForIntersections.data[index];
  24482. if (!sourceMesh.actionManager) {
  24483. continue;
  24484. }
  24485. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24486. var action = sourceMesh.actionManager.actions[actionIndex];
  24487. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24488. var parameters = action.getTriggerParameter();
  24489. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24490. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24491. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24492. if (areIntersecting && currentIntersectionInProgress === -1) {
  24493. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24494. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24495. sourceMesh._intersectionsInProgress.push(otherMesh);
  24496. }
  24497. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24498. sourceMesh._intersectionsInProgress.push(otherMesh);
  24499. }
  24500. }
  24501. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24502. //They intersected, and now they don't.
  24503. //is this trigger an exit trigger? execute an event.
  24504. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24505. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24506. }
  24507. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24508. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24509. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24510. }
  24511. }
  24512. }
  24513. }
  24514. }
  24515. };
  24516. Scene.prototype.render = function () {
  24517. if (this.isDisposed) {
  24518. return;
  24519. }
  24520. this._activeParticles.fetchNewFrame();
  24521. this._totalVertices.fetchNewFrame();
  24522. this._activeIndices.fetchNewFrame();
  24523. this._activeBones.fetchNewFrame();
  24524. this._meshesForIntersections.reset();
  24525. this.resetCachedMaterial();
  24526. this.onBeforeAnimationsObservable.notifyObservers(this);
  24527. // Actions
  24528. if (this.actionManager) {
  24529. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24530. }
  24531. //Simplification Queue
  24532. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24533. this.simplificationQueue.executeNext();
  24534. }
  24535. if (this._engine.isDeterministicLockStep()) {
  24536. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24537. var defaultFPS = (60.0 / 1000.0);
  24538. var defaultFrameTime = 1000 / 60; // frame time in MS
  24539. if (this._physicsEngine) {
  24540. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24541. }
  24542. var stepsTaken = 0;
  24543. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24544. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24545. internalSteps = Math.min(internalSteps, maxSubSteps);
  24546. do {
  24547. this.onBeforeStepObservable.notifyObservers(this);
  24548. // Animations
  24549. this._animationRatio = defaultFrameTime * defaultFPS;
  24550. this._animate();
  24551. this.onAfterAnimationsObservable.notifyObservers(this);
  24552. // Physics
  24553. if (this._physicsEngine) {
  24554. this.onBeforePhysicsObservable.notifyObservers(this);
  24555. this._physicsEngine._step(defaultFrameTime / 1000);
  24556. this.onAfterPhysicsObservable.notifyObservers(this);
  24557. }
  24558. this.onAfterStepObservable.notifyObservers(this);
  24559. this._currentStepId++;
  24560. stepsTaken++;
  24561. deltaTime -= defaultFrameTime;
  24562. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24563. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24564. }
  24565. else {
  24566. // Animations
  24567. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24568. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24569. this._animate();
  24570. this.onAfterAnimationsObservable.notifyObservers(this);
  24571. // Physics
  24572. if (this._physicsEngine) {
  24573. this.onBeforePhysicsObservable.notifyObservers(this);
  24574. this._physicsEngine._step(deltaTime / 1000.0);
  24575. this.onAfterPhysicsObservable.notifyObservers(this);
  24576. }
  24577. }
  24578. // update gamepad manager
  24579. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24580. this._gamepadManager._checkGamepadsStatus();
  24581. }
  24582. // Update Cameras
  24583. if (this.activeCameras.length > 0) {
  24584. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24585. var camera = this.activeCameras[cameraIndex];
  24586. camera.update();
  24587. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24588. // rig cameras
  24589. for (var index = 0; index < camera._rigCameras.length; index++) {
  24590. camera._rigCameras[index].update();
  24591. }
  24592. }
  24593. }
  24594. }
  24595. else if (this.activeCamera) {
  24596. this.activeCamera.update();
  24597. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24598. // rig cameras
  24599. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24600. this.activeCamera._rigCameras[index].update();
  24601. }
  24602. }
  24603. }
  24604. // Before render
  24605. this.onBeforeRenderObservable.notifyObservers(this);
  24606. // Customs render targets
  24607. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24608. var engine = this.getEngine();
  24609. var currentActiveCamera = this.activeCamera;
  24610. if (this.renderTargetsEnabled) {
  24611. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24612. this._intermediateRendering = true;
  24613. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24614. var renderTarget = this.customRenderTargets[customIndex];
  24615. if (renderTarget._shouldRender()) {
  24616. this._renderId++;
  24617. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24618. if (!this.activeCamera)
  24619. throw new Error("Active camera not set");
  24620. // Viewport
  24621. engine.setViewport(this.activeCamera.viewport);
  24622. // Camera
  24623. this.updateTransformMatrix();
  24624. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24625. }
  24626. }
  24627. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24628. this._intermediateRendering = false;
  24629. this._renderId++;
  24630. }
  24631. // Restore back buffer
  24632. if (this.customRenderTargets.length > 0) {
  24633. engine.restoreDefaultFramebuffer();
  24634. }
  24635. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24636. this.activeCamera = currentActiveCamera;
  24637. // Procedural textures
  24638. if (this.proceduralTexturesEnabled) {
  24639. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24640. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24641. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24642. if (proceduralTexture._shouldRender()) {
  24643. proceduralTexture.render();
  24644. }
  24645. }
  24646. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24647. }
  24648. // Clear
  24649. if (this.autoClearDepthAndStencil || this.autoClear) {
  24650. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24651. }
  24652. // Shadows
  24653. if (this.shadowsEnabled) {
  24654. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24655. var light = this.lights[lightIndex];
  24656. var shadowGenerator = light.getShadowGenerator();
  24657. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24658. var shadowMap = (shadowGenerator.getShadowMap());
  24659. if (this.textures.indexOf(shadowMap) !== -1) {
  24660. this._renderTargets.push(shadowMap);
  24661. }
  24662. }
  24663. }
  24664. }
  24665. // Depth renderer
  24666. for (var key in this._depthRenderer) {
  24667. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24668. }
  24669. // Geometry renderer
  24670. if (this._geometryBufferRenderer) {
  24671. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24672. }
  24673. // RenderPipeline
  24674. if (this._postProcessRenderPipelineManager) {
  24675. this._postProcessRenderPipelineManager.update();
  24676. }
  24677. // Multi-cameras?
  24678. if (this.activeCameras.length > 0) {
  24679. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24680. if (cameraIndex > 0) {
  24681. this._engine.clear(null, false, true, true);
  24682. }
  24683. this._processSubCameras(this.activeCameras[cameraIndex]);
  24684. }
  24685. }
  24686. else {
  24687. if (!this.activeCamera) {
  24688. throw new Error("No camera defined");
  24689. }
  24690. this._processSubCameras(this.activeCamera);
  24691. }
  24692. // Intersection checks
  24693. this._checkIntersections();
  24694. // Update the audio listener attached to the camera
  24695. if (BABYLON.AudioEngine) {
  24696. this._updateAudioParameters();
  24697. }
  24698. // After render
  24699. if (this.afterRender) {
  24700. this.afterRender();
  24701. }
  24702. this.onAfterRenderObservable.notifyObservers(this);
  24703. // Cleaning
  24704. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24705. var data = this._toBeDisposed.data[index];
  24706. if (data) {
  24707. data.dispose();
  24708. }
  24709. this._toBeDisposed[index] = null;
  24710. }
  24711. this._toBeDisposed.reset();
  24712. if (this.dumpNextRenderTargets) {
  24713. this.dumpNextRenderTargets = false;
  24714. }
  24715. this._activeBones.addCount(0, true);
  24716. this._activeIndices.addCount(0, true);
  24717. this._activeParticles.addCount(0, true);
  24718. };
  24719. Scene.prototype._updateAudioParameters = function () {
  24720. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24721. return;
  24722. }
  24723. var listeningCamera;
  24724. var audioEngine = BABYLON.Engine.audioEngine;
  24725. if (this.activeCameras.length > 0) {
  24726. listeningCamera = this.activeCameras[0];
  24727. }
  24728. else {
  24729. listeningCamera = this.activeCamera;
  24730. }
  24731. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24732. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24733. // for VR cameras
  24734. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24735. listeningCamera = listeningCamera.rigCameras[0];
  24736. }
  24737. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24738. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24739. cameraDirection.normalize();
  24740. // To avoid some errors on GearVR
  24741. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24742. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24743. }
  24744. var i;
  24745. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24746. var sound = this.mainSoundTrack.soundCollection[i];
  24747. if (sound.useCustomAttenuation) {
  24748. sound.updateDistanceFromListener();
  24749. }
  24750. }
  24751. for (i = 0; i < this.soundTracks.length; i++) {
  24752. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24753. sound = this.soundTracks[i].soundCollection[j];
  24754. if (sound.useCustomAttenuation) {
  24755. sound.updateDistanceFromListener();
  24756. }
  24757. }
  24758. }
  24759. }
  24760. };
  24761. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24762. // Audio
  24763. get: function () {
  24764. return this._audioEnabled;
  24765. },
  24766. set: function (value) {
  24767. this._audioEnabled = value;
  24768. if (BABYLON.AudioEngine) {
  24769. if (this._audioEnabled) {
  24770. this._enableAudio();
  24771. }
  24772. else {
  24773. this._disableAudio();
  24774. }
  24775. }
  24776. },
  24777. enumerable: true,
  24778. configurable: true
  24779. });
  24780. Scene.prototype._disableAudio = function () {
  24781. var i;
  24782. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24783. this.mainSoundTrack.soundCollection[i].pause();
  24784. }
  24785. for (i = 0; i < this.soundTracks.length; i++) {
  24786. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24787. this.soundTracks[i].soundCollection[j].pause();
  24788. }
  24789. }
  24790. };
  24791. Scene.prototype._enableAudio = function () {
  24792. var i;
  24793. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24794. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24795. this.mainSoundTrack.soundCollection[i].play();
  24796. }
  24797. }
  24798. for (i = 0; i < this.soundTracks.length; i++) {
  24799. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24800. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24801. this.soundTracks[i].soundCollection[j].play();
  24802. }
  24803. }
  24804. }
  24805. };
  24806. Object.defineProperty(Scene.prototype, "headphone", {
  24807. get: function () {
  24808. return this._headphone;
  24809. },
  24810. set: function (value) {
  24811. this._headphone = value;
  24812. if (BABYLON.AudioEngine) {
  24813. if (this._headphone) {
  24814. this._switchAudioModeForHeadphones();
  24815. }
  24816. else {
  24817. this._switchAudioModeForNormalSpeakers();
  24818. }
  24819. }
  24820. },
  24821. enumerable: true,
  24822. configurable: true
  24823. });
  24824. Scene.prototype._switchAudioModeForHeadphones = function () {
  24825. this.mainSoundTrack.switchPanningModelToHRTF();
  24826. for (var i = 0; i < this.soundTracks.length; i++) {
  24827. this.soundTracks[i].switchPanningModelToHRTF();
  24828. }
  24829. };
  24830. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24831. this.mainSoundTrack.switchPanningModelToEqualPower();
  24832. for (var i = 0; i < this.soundTracks.length; i++) {
  24833. this.soundTracks[i].switchPanningModelToEqualPower();
  24834. }
  24835. };
  24836. /**
  24837. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  24838. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  24839. * @returns the created depth renderer
  24840. */
  24841. Scene.prototype.enableDepthRenderer = function (camera) {
  24842. camera = camera || this.activeCamera;
  24843. if (!camera) {
  24844. throw "No camera available to enable depth renderer";
  24845. }
  24846. if (!this._depthRenderer[camera.id]) {
  24847. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  24848. }
  24849. return this._depthRenderer[camera.id];
  24850. };
  24851. /**
  24852. * Disables a depth renderer for a given camera
  24853. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  24854. */
  24855. Scene.prototype.disableDepthRenderer = function (camera) {
  24856. camera = camera || this.activeCamera;
  24857. if (!camera || !this._depthRenderer[camera.id]) {
  24858. return;
  24859. }
  24860. this._depthRenderer[camera.id].dispose();
  24861. delete this._depthRenderer[camera.id];
  24862. };
  24863. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24864. if (ratio === void 0) { ratio = 1; }
  24865. if (this._geometryBufferRenderer) {
  24866. return this._geometryBufferRenderer;
  24867. }
  24868. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24869. if (!this._geometryBufferRenderer.isSupported) {
  24870. this._geometryBufferRenderer = null;
  24871. }
  24872. return this._geometryBufferRenderer;
  24873. };
  24874. Scene.prototype.disableGeometryBufferRenderer = function () {
  24875. if (!this._geometryBufferRenderer) {
  24876. return;
  24877. }
  24878. this._geometryBufferRenderer.dispose();
  24879. this._geometryBufferRenderer = null;
  24880. };
  24881. Scene.prototype.freezeMaterials = function () {
  24882. for (var i = 0; i < this.materials.length; i++) {
  24883. this.materials[i].freeze();
  24884. }
  24885. };
  24886. Scene.prototype.unfreezeMaterials = function () {
  24887. for (var i = 0; i < this.materials.length; i++) {
  24888. this.materials[i].unfreeze();
  24889. }
  24890. };
  24891. Scene.prototype.dispose = function () {
  24892. this.beforeRender = null;
  24893. this.afterRender = null;
  24894. this.skeletons = [];
  24895. this.morphTargetManagers = [];
  24896. this.importedMeshesFiles = new Array();
  24897. this.stopAllAnimations();
  24898. this.resetCachedMaterial();
  24899. for (var key in this._depthRenderer) {
  24900. this._depthRenderer[key].dispose();
  24901. }
  24902. if (this._gamepadManager) {
  24903. this._gamepadManager.dispose();
  24904. this._gamepadManager = null;
  24905. }
  24906. // Smart arrays
  24907. if (this.activeCamera) {
  24908. this.activeCamera._activeMeshes.dispose();
  24909. this.activeCamera = null;
  24910. }
  24911. this._activeMeshes.dispose();
  24912. this._renderingManager.dispose();
  24913. this._processedMaterials.dispose();
  24914. this._activeParticleSystems.dispose();
  24915. this._activeSkeletons.dispose();
  24916. this._softwareSkinnedMeshes.dispose();
  24917. this._renderTargets.dispose();
  24918. if (this._boundingBoxRenderer) {
  24919. this._boundingBoxRenderer.dispose();
  24920. }
  24921. this._meshesForIntersections.dispose();
  24922. this._toBeDisposed.dispose();
  24923. // Abort active requests
  24924. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24925. var request = _a[_i];
  24926. request.abort();
  24927. }
  24928. // Debug layer
  24929. if (this._debugLayer) {
  24930. this._debugLayer.hide();
  24931. }
  24932. // Events
  24933. this.onDisposeObservable.notifyObservers(this);
  24934. this.onDisposeObservable.clear();
  24935. this.onBeforeRenderObservable.clear();
  24936. this.onAfterRenderObservable.clear();
  24937. this.OnBeforeRenderTargetsRenderObservable.clear();
  24938. this.OnAfterRenderTargetsRenderObservable.clear();
  24939. this.onAfterStepObservable.clear();
  24940. this.onBeforeStepObservable.clear();
  24941. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24942. this.onAfterActiveMeshesEvaluationObservable.clear();
  24943. this.onBeforeParticlesRenderingObservable.clear();
  24944. this.onAfterParticlesRenderingObservable.clear();
  24945. this.onBeforeSpritesRenderingObservable.clear();
  24946. this.onAfterSpritesRenderingObservable.clear();
  24947. this.onBeforeDrawPhaseObservable.clear();
  24948. this.onAfterDrawPhaseObservable.clear();
  24949. this.onBeforePhysicsObservable.clear();
  24950. this.onAfterPhysicsObservable.clear();
  24951. this.onBeforeAnimationsObservable.clear();
  24952. this.onAfterAnimationsObservable.clear();
  24953. this.onDataLoadedObservable.clear();
  24954. this.detachControl();
  24955. // Release sounds & sounds tracks
  24956. if (BABYLON.AudioEngine) {
  24957. this.disposeSounds();
  24958. }
  24959. // VR Helper
  24960. if (this.VRHelper) {
  24961. this.VRHelper.dispose();
  24962. }
  24963. // Detach cameras
  24964. var canvas = this._engine.getRenderingCanvas();
  24965. if (canvas) {
  24966. var index;
  24967. for (index = 0; index < this.cameras.length; index++) {
  24968. this.cameras[index].detachControl(canvas);
  24969. }
  24970. }
  24971. // Release animation groups
  24972. while (this.animationGroups.length) {
  24973. this.animationGroups[0].dispose();
  24974. }
  24975. // Release lights
  24976. while (this.lights.length) {
  24977. this.lights[0].dispose();
  24978. }
  24979. // Release meshes
  24980. while (this.meshes.length) {
  24981. this.meshes[0].dispose(true);
  24982. }
  24983. while (this.transformNodes.length) {
  24984. this.removeTransformNode(this.transformNodes[0]);
  24985. }
  24986. // Release cameras
  24987. while (this.cameras.length) {
  24988. this.cameras[0].dispose();
  24989. }
  24990. // Release materials
  24991. if (this.defaultMaterial) {
  24992. this.defaultMaterial.dispose();
  24993. }
  24994. while (this.multiMaterials.length) {
  24995. this.multiMaterials[0].dispose();
  24996. }
  24997. while (this.materials.length) {
  24998. this.materials[0].dispose();
  24999. }
  25000. // Release particles
  25001. while (this.particleSystems.length) {
  25002. this.particleSystems[0].dispose();
  25003. }
  25004. // Release sprites
  25005. while (this.spriteManagers.length) {
  25006. this.spriteManagers[0].dispose();
  25007. }
  25008. // Release postProcesses
  25009. while (this.postProcesses.length) {
  25010. this.postProcesses[0].dispose();
  25011. }
  25012. // Release layers
  25013. while (this.layers.length) {
  25014. this.layers[0].dispose();
  25015. }
  25016. while (this.effectLayers.length) {
  25017. this.effectLayers[0].dispose();
  25018. }
  25019. // Release textures
  25020. while (this.textures.length) {
  25021. this.textures[0].dispose();
  25022. }
  25023. // Release UBO
  25024. this._sceneUbo.dispose();
  25025. if (this._alternateSceneUbo) {
  25026. this._alternateSceneUbo.dispose();
  25027. }
  25028. // Post-processes
  25029. this.postProcessManager.dispose();
  25030. if (this._postProcessRenderPipelineManager) {
  25031. this._postProcessRenderPipelineManager.dispose();
  25032. }
  25033. // Physics
  25034. if (this._physicsEngine) {
  25035. this.disablePhysicsEngine();
  25036. }
  25037. // Remove from engine
  25038. index = this._engine.scenes.indexOf(this);
  25039. if (index > -1) {
  25040. this._engine.scenes.splice(index, 1);
  25041. }
  25042. this._engine.wipeCaches(true);
  25043. this._isDisposed = true;
  25044. };
  25045. Object.defineProperty(Scene.prototype, "isDisposed", {
  25046. get: function () {
  25047. return this._isDisposed;
  25048. },
  25049. enumerable: true,
  25050. configurable: true
  25051. });
  25052. // Release sounds & sounds tracks
  25053. Scene.prototype.disposeSounds = function () {
  25054. if (!this._mainSoundTrack) {
  25055. return;
  25056. }
  25057. this.mainSoundTrack.dispose();
  25058. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  25059. this.soundTracks[scIndex].dispose();
  25060. }
  25061. };
  25062. // Octrees
  25063. /**
  25064. * Get the world extend vectors with an optional filter
  25065. *
  25066. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  25067. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  25068. */
  25069. Scene.prototype.getWorldExtends = function (filterPredicate) {
  25070. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  25071. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  25072. filterPredicate = filterPredicate || (function () { return true; });
  25073. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  25074. mesh.computeWorldMatrix(true);
  25075. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  25076. return;
  25077. }
  25078. var boundingInfo = mesh.getBoundingInfo();
  25079. var minBox = boundingInfo.boundingBox.minimumWorld;
  25080. var maxBox = boundingInfo.boundingBox.maximumWorld;
  25081. BABYLON.Tools.CheckExtends(minBox, min, max);
  25082. BABYLON.Tools.CheckExtends(maxBox, min, max);
  25083. });
  25084. return {
  25085. min: min,
  25086. max: max
  25087. };
  25088. };
  25089. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  25090. if (maxCapacity === void 0) { maxCapacity = 64; }
  25091. if (maxDepth === void 0) { maxDepth = 2; }
  25092. if (!this._selectionOctree) {
  25093. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  25094. }
  25095. var worldExtends = this.getWorldExtends();
  25096. // Update octree
  25097. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  25098. return this._selectionOctree;
  25099. };
  25100. // Picking
  25101. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  25102. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25103. var result = BABYLON.Ray.Zero();
  25104. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  25105. return result;
  25106. };
  25107. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  25108. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25109. var engine = this._engine;
  25110. if (!camera) {
  25111. if (!this.activeCamera)
  25112. throw new Error("Active camera not set");
  25113. camera = this.activeCamera;
  25114. }
  25115. var cameraViewport = camera.viewport;
  25116. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25117. // Moving coordinates to local viewport world
  25118. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25119. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25120. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  25121. return this;
  25122. };
  25123. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  25124. var result = BABYLON.Ray.Zero();
  25125. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  25126. return result;
  25127. };
  25128. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  25129. if (!BABYLON.PickingInfo) {
  25130. return this;
  25131. }
  25132. var engine = this._engine;
  25133. if (!camera) {
  25134. if (!this.activeCamera)
  25135. throw new Error("Active camera not set");
  25136. camera = this.activeCamera;
  25137. }
  25138. var cameraViewport = camera.viewport;
  25139. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25140. var identity = BABYLON.Matrix.Identity();
  25141. // Moving coordinates to local viewport world
  25142. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25143. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25144. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  25145. return this;
  25146. };
  25147. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  25148. if (!BABYLON.PickingInfo) {
  25149. return null;
  25150. }
  25151. var pickingInfo = null;
  25152. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25153. var mesh = this.meshes[meshIndex];
  25154. if (predicate) {
  25155. if (!predicate(mesh)) {
  25156. continue;
  25157. }
  25158. }
  25159. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25160. continue;
  25161. }
  25162. var world = mesh.getWorldMatrix();
  25163. var ray = rayFunction(world);
  25164. var result = mesh.intersects(ray, fastCheck);
  25165. if (!result || !result.hit)
  25166. continue;
  25167. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25168. continue;
  25169. pickingInfo = result;
  25170. if (fastCheck) {
  25171. break;
  25172. }
  25173. }
  25174. return pickingInfo || new BABYLON.PickingInfo();
  25175. };
  25176. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25177. if (!BABYLON.PickingInfo) {
  25178. return null;
  25179. }
  25180. var pickingInfos = new Array();
  25181. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25182. var mesh = this.meshes[meshIndex];
  25183. if (predicate) {
  25184. if (!predicate(mesh)) {
  25185. continue;
  25186. }
  25187. }
  25188. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25189. continue;
  25190. }
  25191. var world = mesh.getWorldMatrix();
  25192. var ray = rayFunction(world);
  25193. var result = mesh.intersects(ray, false);
  25194. if (!result || !result.hit)
  25195. continue;
  25196. pickingInfos.push(result);
  25197. }
  25198. return pickingInfos;
  25199. };
  25200. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25201. if (!BABYLON.PickingInfo) {
  25202. return null;
  25203. }
  25204. var pickingInfo = null;
  25205. if (!camera) {
  25206. if (!this.activeCamera) {
  25207. return null;
  25208. }
  25209. camera = this.activeCamera;
  25210. }
  25211. if (this.spriteManagers.length > 0) {
  25212. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25213. var spriteManager = this.spriteManagers[spriteIndex];
  25214. if (!spriteManager.isPickable) {
  25215. continue;
  25216. }
  25217. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25218. if (!result || !result.hit)
  25219. continue;
  25220. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25221. continue;
  25222. pickingInfo = result;
  25223. if (fastCheck) {
  25224. break;
  25225. }
  25226. }
  25227. }
  25228. return pickingInfo || new BABYLON.PickingInfo();
  25229. };
  25230. /** Launch a ray to try to pick a mesh in the scene
  25231. * @param x position on screen
  25232. * @param y position on screen
  25233. * @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
  25234. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25235. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25236. */
  25237. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25238. var _this = this;
  25239. if (!BABYLON.PickingInfo) {
  25240. return null;
  25241. }
  25242. return this._internalPick(function (world) {
  25243. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25244. return _this._tempPickingRay;
  25245. }, predicate, fastCheck);
  25246. };
  25247. /** Launch a ray to try to pick a sprite in the scene
  25248. * @param x position on screen
  25249. * @param y position on screen
  25250. * @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
  25251. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25252. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25253. */
  25254. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25255. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25256. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25257. };
  25258. /** Use the given ray to pick a mesh in the scene
  25259. * @param ray The ray to use to pick meshes
  25260. * @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
  25261. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25262. */
  25263. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25264. var _this = this;
  25265. return this._internalPick(function (world) {
  25266. if (!_this._pickWithRayInverseMatrix) {
  25267. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25268. }
  25269. world.invertToRef(_this._pickWithRayInverseMatrix);
  25270. if (!_this._cachedRayForTransform) {
  25271. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25272. }
  25273. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25274. return _this._cachedRayForTransform;
  25275. }, predicate, fastCheck);
  25276. };
  25277. /**
  25278. * Launch a ray to try to pick a mesh in the scene
  25279. * @param x X position on screen
  25280. * @param y Y position on screen
  25281. * @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
  25282. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25283. */
  25284. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25285. var _this = this;
  25286. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25287. };
  25288. /**
  25289. * Launch a ray to try to pick a mesh in the scene
  25290. * @param ray Ray to use
  25291. * @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
  25292. */
  25293. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25294. var _this = this;
  25295. return this._internalMultiPick(function (world) {
  25296. if (!_this._pickWithRayInverseMatrix) {
  25297. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25298. }
  25299. world.invertToRef(_this._pickWithRayInverseMatrix);
  25300. if (!_this._cachedRayForTransform) {
  25301. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25302. }
  25303. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25304. return _this._cachedRayForTransform;
  25305. }, predicate);
  25306. };
  25307. Scene.prototype.setPointerOverMesh = function (mesh) {
  25308. if (this._pointerOverMesh === mesh) {
  25309. return;
  25310. }
  25311. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25312. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25313. }
  25314. this._pointerOverMesh = mesh;
  25315. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25316. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25317. }
  25318. };
  25319. Scene.prototype.getPointerOverMesh = function () {
  25320. return this._pointerOverMesh;
  25321. };
  25322. Scene.prototype.setPointerOverSprite = function (sprite) {
  25323. if (this._pointerOverSprite === sprite) {
  25324. return;
  25325. }
  25326. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25327. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25328. }
  25329. this._pointerOverSprite = sprite;
  25330. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25331. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25332. }
  25333. };
  25334. Scene.prototype.getPointerOverSprite = function () {
  25335. return this._pointerOverSprite;
  25336. };
  25337. // Physics
  25338. Scene.prototype.getPhysicsEngine = function () {
  25339. return this._physicsEngine;
  25340. };
  25341. /**
  25342. * Enables physics to the current scene
  25343. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25344. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25345. * @return {boolean} was the physics engine initialized
  25346. */
  25347. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25348. if (gravity === void 0) { gravity = null; }
  25349. if (this._physicsEngine) {
  25350. return true;
  25351. }
  25352. try {
  25353. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25354. return true;
  25355. }
  25356. catch (e) {
  25357. BABYLON.Tools.Error(e.message);
  25358. return false;
  25359. }
  25360. };
  25361. Scene.prototype.disablePhysicsEngine = function () {
  25362. if (!this._physicsEngine) {
  25363. return;
  25364. }
  25365. this._physicsEngine.dispose();
  25366. this._physicsEngine = null;
  25367. };
  25368. Scene.prototype.isPhysicsEnabled = function () {
  25369. return this._physicsEngine !== undefined;
  25370. };
  25371. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25372. var mesh = compound.parts[0].mesh;
  25373. if (mesh.physicsImpostor) {
  25374. mesh.physicsImpostor.dispose();
  25375. mesh.physicsImpostor = null;
  25376. }
  25377. };
  25378. // Misc.
  25379. Scene.prototype._rebuildGeometries = function () {
  25380. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25381. var geometry = _a[_i];
  25382. geometry._rebuild();
  25383. }
  25384. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25385. var mesh = _c[_b];
  25386. mesh._rebuild();
  25387. }
  25388. if (this.postProcessManager) {
  25389. this.postProcessManager._rebuild();
  25390. }
  25391. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25392. var layer = _e[_d];
  25393. layer._rebuild();
  25394. }
  25395. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25396. var effectLayer = _g[_f];
  25397. effectLayer._rebuild();
  25398. }
  25399. if (this._boundingBoxRenderer) {
  25400. this._boundingBoxRenderer._rebuild();
  25401. }
  25402. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25403. var system = _j[_h];
  25404. system.rebuild();
  25405. }
  25406. if (this._postProcessRenderPipelineManager) {
  25407. this._postProcessRenderPipelineManager._rebuild();
  25408. }
  25409. };
  25410. Scene.prototype._rebuildTextures = function () {
  25411. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25412. var texture = _a[_i];
  25413. texture._rebuild();
  25414. }
  25415. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25416. };
  25417. /**
  25418. * Creates a default light for the scene.
  25419. * @param replace Whether to replace the existing lights in the scene.
  25420. */
  25421. Scene.prototype.createDefaultLight = function (replace) {
  25422. if (replace === void 0) { replace = false; }
  25423. // Dispose existing light in replace mode.
  25424. if (replace) {
  25425. if (this.lights) {
  25426. for (var i = 0; i < this.lights.length; i++) {
  25427. this.lights[i].dispose();
  25428. }
  25429. }
  25430. }
  25431. // Light
  25432. if (this.lights.length === 0) {
  25433. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25434. }
  25435. };
  25436. /**
  25437. * Creates a default camera for the scene.
  25438. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25439. * @param replace Whether to replace the existing active camera in the scene.
  25440. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25441. */
  25442. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25443. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25444. if (replace === void 0) { replace = false; }
  25445. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25446. // Dispose existing camera in replace mode.
  25447. if (replace) {
  25448. if (this.activeCamera) {
  25449. this.activeCamera.dispose();
  25450. this.activeCamera = null;
  25451. }
  25452. }
  25453. // Camera
  25454. if (!this.activeCamera) {
  25455. var worldExtends = this.getWorldExtends();
  25456. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25457. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25458. var camera;
  25459. var radius = worldSize.length() * 1.5;
  25460. // empty scene scenario!
  25461. if (!isFinite(radius)) {
  25462. radius = 1;
  25463. worldCenter.copyFromFloats(0, 0, 0);
  25464. }
  25465. if (createArcRotateCamera) {
  25466. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25467. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25468. arcRotateCamera.wheelPrecision = 100 / radius;
  25469. camera = arcRotateCamera;
  25470. }
  25471. else {
  25472. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25473. freeCamera.setTarget(worldCenter);
  25474. camera = freeCamera;
  25475. }
  25476. camera.minZ = radius * 0.01;
  25477. camera.maxZ = radius * 1000;
  25478. camera.speed = radius * 0.2;
  25479. this.activeCamera = camera;
  25480. var canvas = this.getEngine().getRenderingCanvas();
  25481. if (attachCameraControls && canvas) {
  25482. camera.attachControl(canvas);
  25483. }
  25484. }
  25485. };
  25486. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25487. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25488. if (replace === void 0) { replace = false; }
  25489. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25490. this.createDefaultLight(replace);
  25491. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25492. };
  25493. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25494. if (pbr === void 0) { pbr = false; }
  25495. if (scale === void 0) { scale = 1000; }
  25496. if (blur === void 0) { blur = 0; }
  25497. if (environmentTexture) {
  25498. this.environmentTexture = environmentTexture;
  25499. }
  25500. if (!this.environmentTexture) {
  25501. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25502. return null;
  25503. }
  25504. // Skybox
  25505. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25506. if (pbr) {
  25507. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25508. hdrSkyboxMaterial.backFaceCulling = false;
  25509. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25510. if (hdrSkyboxMaterial.reflectionTexture) {
  25511. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25512. }
  25513. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25514. hdrSkyboxMaterial.disableLighting = true;
  25515. hdrSkyboxMaterial.twoSidedLighting = true;
  25516. hdrSkybox.infiniteDistance = true;
  25517. hdrSkybox.material = hdrSkyboxMaterial;
  25518. }
  25519. else {
  25520. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25521. skyboxMaterial.backFaceCulling = false;
  25522. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25523. if (skyboxMaterial.reflectionTexture) {
  25524. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25525. }
  25526. skyboxMaterial.disableLighting = true;
  25527. hdrSkybox.infiniteDistance = true;
  25528. hdrSkybox.material = skyboxMaterial;
  25529. }
  25530. return hdrSkybox;
  25531. };
  25532. Scene.prototype.createDefaultEnvironment = function (options) {
  25533. if (BABYLON.EnvironmentHelper) {
  25534. return new BABYLON.EnvironmentHelper(options, this);
  25535. }
  25536. return null;
  25537. };
  25538. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25539. if (webVROptions === void 0) { webVROptions = {}; }
  25540. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25541. };
  25542. // Tags
  25543. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25544. if (tagsQuery === undefined) {
  25545. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25546. return list;
  25547. }
  25548. var listByTags = [];
  25549. forEach = forEach || (function (item) { return; });
  25550. for (var i in list) {
  25551. var item = list[i];
  25552. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25553. listByTags.push(item);
  25554. forEach(item);
  25555. }
  25556. }
  25557. return listByTags;
  25558. };
  25559. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25560. return this._getByTags(this.meshes, tagsQuery, forEach);
  25561. };
  25562. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25563. return this._getByTags(this.cameras, tagsQuery, forEach);
  25564. };
  25565. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25566. return this._getByTags(this.lights, tagsQuery, forEach);
  25567. };
  25568. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25569. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25570. };
  25571. /**
  25572. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25573. * This allowed control for front to back rendering or reversly depending of the special needs.
  25574. *
  25575. * @param renderingGroupId The rendering group id corresponding to its index
  25576. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25577. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25578. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25579. */
  25580. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25581. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25582. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25583. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25584. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25585. };
  25586. /**
  25587. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25588. *
  25589. * @param renderingGroupId The rendering group id corresponding to its index
  25590. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25591. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25592. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25593. */
  25594. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25595. if (depth === void 0) { depth = true; }
  25596. if (stencil === void 0) { stencil = true; }
  25597. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25598. };
  25599. /**
  25600. * Will flag all materials as dirty to trigger new shader compilation
  25601. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25602. */
  25603. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25604. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25605. var material = _a[_i];
  25606. if (predicate && !predicate(material)) {
  25607. continue;
  25608. }
  25609. material.markAsDirty(flag);
  25610. }
  25611. };
  25612. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25613. var _this = this;
  25614. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25615. this._activeRequests.push(request);
  25616. request.onCompleteObservable.add(function (request) {
  25617. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25618. });
  25619. return request;
  25620. };
  25621. /** @ignore */
  25622. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25623. var _this = this;
  25624. return new Promise(function (resolve, reject) {
  25625. _this._loadFile(url, function (data) {
  25626. resolve(data);
  25627. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25628. reject(exception);
  25629. });
  25630. });
  25631. };
  25632. // Statics
  25633. Scene._FOGMODE_NONE = 0;
  25634. Scene._FOGMODE_EXP = 1;
  25635. Scene._FOGMODE_EXP2 = 2;
  25636. Scene._FOGMODE_LINEAR = 3;
  25637. Scene._uniqueIdCounter = 0;
  25638. Scene.MinDeltaTime = 1.0;
  25639. Scene.MaxDeltaTime = 1000.0;
  25640. /** The distance in pixel that you have to move to prevent some events */
  25641. Scene.DragMovementThreshold = 10; // in pixels
  25642. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25643. Scene.LongPressDelay = 500; // in milliseconds
  25644. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25645. Scene.DoubleClickDelay = 300; // in milliseconds
  25646. /** If you need to check double click without raising a single click at first click, enable this flag */
  25647. Scene.ExclusiveDoubleClickMode = false;
  25648. return Scene;
  25649. }());
  25650. BABYLON.Scene = Scene;
  25651. })(BABYLON || (BABYLON = {}));
  25652. //# sourceMappingURL=babylon.scene.js.map
  25653. var BABYLON;
  25654. (function (BABYLON) {
  25655. /**
  25656. * Set of assets to keep when moving a scene into an asset container.
  25657. */
  25658. var KeepAssets = /** @class */ (function () {
  25659. function KeepAssets() {
  25660. /**
  25661. * Cameras to keep.
  25662. */
  25663. this.cameras = new Array();
  25664. /**
  25665. * Lights to keep.
  25666. */
  25667. this.lights = new Array();
  25668. /**
  25669. * Meshes to keep.
  25670. */
  25671. this.meshes = new Array();
  25672. /**
  25673. * Skeletons to keep.
  25674. */
  25675. this.skeletons = new Array();
  25676. /**
  25677. * ParticleSystems to keep.
  25678. */
  25679. this.particleSystems = new Array();
  25680. /**
  25681. * Animations to keep.
  25682. */
  25683. this.animations = new Array();
  25684. /**
  25685. * MultiMaterials to keep.
  25686. */
  25687. this.multiMaterials = new Array();
  25688. /**
  25689. * Materials to keep.
  25690. */
  25691. this.materials = new Array();
  25692. /**
  25693. * MorphTargetManagers to keep.
  25694. */
  25695. this.morphTargetManagers = new Array();
  25696. /**
  25697. * Geometries to keep.
  25698. */
  25699. this.geometries = new Array();
  25700. /**
  25701. * TransformNodes to keep.
  25702. */
  25703. this.transformNodes = new Array();
  25704. /**
  25705. * LensFlareSystems to keep.
  25706. */
  25707. this.lensFlareSystems = new Array();
  25708. /**
  25709. * ShadowGenerators to keep.
  25710. */
  25711. this.shadowGenerators = new Array();
  25712. /**
  25713. * ActionManagers to keep.
  25714. */
  25715. this.actionManagers = new Array();
  25716. /**
  25717. * Sounds to keep.
  25718. */
  25719. this.sounds = new Array();
  25720. }
  25721. return KeepAssets;
  25722. }());
  25723. BABYLON.KeepAssets = KeepAssets;
  25724. /**
  25725. * Container with a set of assets that can be added or removed from a scene.
  25726. */
  25727. var AssetContainer = /** @class */ (function () {
  25728. /**
  25729. * Instantiates an AssetContainer.
  25730. * @param scene The scene the AssetContainer belongs to.
  25731. */
  25732. function AssetContainer(scene) {
  25733. // Objects
  25734. /**
  25735. * Cameras populated in the container.
  25736. */
  25737. this.cameras = new Array();
  25738. /**
  25739. * Lights populated in the container.
  25740. */
  25741. this.lights = new Array();
  25742. /**
  25743. * Meshes populated in the container.
  25744. */
  25745. this.meshes = new Array();
  25746. /**
  25747. * Skeletons populated in the container.
  25748. */
  25749. this.skeletons = new Array();
  25750. /**
  25751. * ParticleSystems populated in the container.
  25752. */
  25753. this.particleSystems = new Array();
  25754. /**
  25755. * Animations populated in the container.
  25756. */
  25757. this.animations = new Array();
  25758. /**
  25759. * MultiMaterials populated in the container.
  25760. */
  25761. this.multiMaterials = new Array();
  25762. /**
  25763. * Materials populated in the container.
  25764. */
  25765. this.materials = new Array();
  25766. /**
  25767. * MorphTargetManagers populated in the container.
  25768. */
  25769. this.morphTargetManagers = new Array();
  25770. /**
  25771. * Geometries populated in the container.
  25772. */
  25773. this.geometries = new Array();
  25774. /**
  25775. * TransformNodes populated in the container.
  25776. */
  25777. this.transformNodes = new Array();
  25778. /**
  25779. * LensFlareSystems populated in the container.
  25780. */
  25781. this.lensFlareSystems = new Array();
  25782. /**
  25783. * ShadowGenerators populated in the container.
  25784. */
  25785. this.shadowGenerators = new Array();
  25786. /**
  25787. * ActionManagers populated in the container.
  25788. */
  25789. this.actionManagers = new Array();
  25790. /**
  25791. * Sounds populated in the container.
  25792. */
  25793. this.sounds = new Array();
  25794. this.scene = scene;
  25795. }
  25796. /**
  25797. * Adds all the assets from the container to the scene.
  25798. */
  25799. AssetContainer.prototype.addAllToScene = function () {
  25800. var _this = this;
  25801. this.cameras.forEach(function (o) {
  25802. _this.scene.addCamera(o);
  25803. });
  25804. this.lights.forEach(function (o) {
  25805. _this.scene.addLight(o);
  25806. });
  25807. this.meshes.forEach(function (o) {
  25808. _this.scene.addMesh(o);
  25809. });
  25810. this.skeletons.forEach(function (o) {
  25811. _this.scene.addSkeleton(o);
  25812. });
  25813. this.particleSystems.forEach(function (o) {
  25814. _this.scene.addParticleSystem(o);
  25815. });
  25816. this.animations.forEach(function (o) {
  25817. _this.scene.addAnimation(o);
  25818. });
  25819. this.multiMaterials.forEach(function (o) {
  25820. _this.scene.addMultiMaterial(o);
  25821. });
  25822. this.materials.forEach(function (o) {
  25823. _this.scene.addMaterial(o);
  25824. });
  25825. this.morphTargetManagers.forEach(function (o) {
  25826. _this.scene.addMorphTargetManager(o);
  25827. });
  25828. this.geometries.forEach(function (o) {
  25829. _this.scene.addGeometry(o);
  25830. });
  25831. this.transformNodes.forEach(function (o) {
  25832. _this.scene.addTransformNode(o);
  25833. });
  25834. this.lensFlareSystems.forEach(function (o) {
  25835. _this.scene.addLensFlareSystem(o);
  25836. });
  25837. this.actionManagers.forEach(function (o) {
  25838. _this.scene.addActionManager(o);
  25839. });
  25840. this.sounds.forEach(function (o) {
  25841. o.play();
  25842. o.autoplay = true;
  25843. _this.scene.mainSoundTrack.AddSound(o);
  25844. });
  25845. };
  25846. /**
  25847. * Removes all the assets in the container from the scene
  25848. */
  25849. AssetContainer.prototype.removeAllFromScene = function () {
  25850. var _this = this;
  25851. this.cameras.forEach(function (o) {
  25852. _this.scene.removeCamera(o);
  25853. });
  25854. this.lights.forEach(function (o) {
  25855. _this.scene.removeLight(o);
  25856. });
  25857. this.meshes.forEach(function (o) {
  25858. _this.scene.removeMesh(o);
  25859. });
  25860. this.skeletons.forEach(function (o) {
  25861. _this.scene.removeSkeleton(o);
  25862. });
  25863. this.particleSystems.forEach(function (o) {
  25864. _this.scene.removeParticleSystem(o);
  25865. });
  25866. this.animations.forEach(function (o) {
  25867. _this.scene.removeAnimation(o);
  25868. });
  25869. this.multiMaterials.forEach(function (o) {
  25870. _this.scene.removeMultiMaterial(o);
  25871. });
  25872. this.materials.forEach(function (o) {
  25873. _this.scene.removeMaterial(o);
  25874. });
  25875. this.morphTargetManagers.forEach(function (o) {
  25876. _this.scene.removeMorphTargetManager(o);
  25877. });
  25878. this.geometries.forEach(function (o) {
  25879. _this.scene.removeGeometry(o);
  25880. });
  25881. this.transformNodes.forEach(function (o) {
  25882. _this.scene.removeTransformNode(o);
  25883. });
  25884. this.lensFlareSystems.forEach(function (o) {
  25885. _this.scene.removeLensFlareSystem(o);
  25886. });
  25887. this.actionManagers.forEach(function (o) {
  25888. _this.scene.removeActionManager(o);
  25889. });
  25890. this.sounds.forEach(function (o) {
  25891. o.stop();
  25892. o.autoplay = false;
  25893. _this.scene.mainSoundTrack.RemoveSound(o);
  25894. });
  25895. };
  25896. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25897. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25898. var asset = sourceAssets_1[_i];
  25899. var move = true;
  25900. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25901. var keepAsset = keepAssets_1[_a];
  25902. if (asset === keepAsset) {
  25903. move = false;
  25904. break;
  25905. }
  25906. }
  25907. if (move) {
  25908. targetAssets.push(asset);
  25909. }
  25910. }
  25911. };
  25912. /**
  25913. * Removes all the assets contained in the scene and adds them to the container.
  25914. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25915. */
  25916. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25917. if (keepAssets === undefined) {
  25918. keepAssets = new KeepAssets();
  25919. }
  25920. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25921. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25922. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25923. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25924. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25925. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25926. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25927. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25928. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25929. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25930. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25931. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25932. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25933. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25934. this.removeAllFromScene();
  25935. };
  25936. return AssetContainer;
  25937. }());
  25938. BABYLON.AssetContainer = AssetContainer;
  25939. })(BABYLON || (BABYLON = {}));
  25940. //# sourceMappingURL=babylon.assetContainer.js.map
  25941. var BABYLON;
  25942. (function (BABYLON) {
  25943. var Buffer = /** @class */ (function () {
  25944. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25945. if (instanced === void 0) { instanced = false; }
  25946. if (engine instanceof BABYLON.Mesh) {
  25947. this._engine = engine.getScene().getEngine();
  25948. }
  25949. else {
  25950. this._engine = engine;
  25951. }
  25952. this._updatable = updatable;
  25953. this._instanced = instanced;
  25954. this._data = data;
  25955. this._strideSize = stride;
  25956. if (!postponeInternalCreation) {
  25957. this.create();
  25958. }
  25959. }
  25960. /**
  25961. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25962. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25963. * @param offset defines offset in the buffer (0 by default)
  25964. * @param size defines the size in floats of attributes (position is 3 for instance)
  25965. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25966. * @param instanced defines if the vertex buffer contains indexed data
  25967. * @returns the new vertex buffer
  25968. */
  25969. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25970. // a lot of these parameters are ignored as they are overriden by the buffer
  25971. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25972. };
  25973. // Properties
  25974. Buffer.prototype.isUpdatable = function () {
  25975. return this._updatable;
  25976. };
  25977. Buffer.prototype.getData = function () {
  25978. return this._data;
  25979. };
  25980. Buffer.prototype.getBuffer = function () {
  25981. return this._buffer;
  25982. };
  25983. Buffer.prototype.getStrideSize = function () {
  25984. return this._strideSize;
  25985. };
  25986. // public getIsInstanced(): boolean {
  25987. // return this._instanced;
  25988. // }
  25989. // public get instanceDivisor(): number {
  25990. // return this._instanceDivisor;
  25991. // }
  25992. // public set instanceDivisor(value: number) {
  25993. // this._instanceDivisor = value;
  25994. // if (value == 0) {
  25995. // this._instanced = false;
  25996. // } else {
  25997. // this._instanced = true;
  25998. // }
  25999. // }
  26000. // Methods
  26001. Buffer.prototype.create = function (data) {
  26002. if (data === void 0) { data = null; }
  26003. if (!data && this._buffer) {
  26004. return; // nothing to do
  26005. }
  26006. data = data || this._data;
  26007. if (!data) {
  26008. return;
  26009. }
  26010. if (!this._buffer) {
  26011. if (this._updatable) {
  26012. this._buffer = this._engine.createDynamicVertexBuffer(data);
  26013. this._data = data;
  26014. }
  26015. else {
  26016. this._buffer = this._engine.createVertexBuffer(data);
  26017. }
  26018. }
  26019. else if (this._updatable) {
  26020. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  26021. this._data = data;
  26022. }
  26023. };
  26024. Buffer.prototype._rebuild = function () {
  26025. this._buffer = null;
  26026. this.create(this._data);
  26027. };
  26028. Buffer.prototype.update = function (data) {
  26029. this.create(data);
  26030. };
  26031. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  26032. if (!this._buffer) {
  26033. return;
  26034. }
  26035. if (this._updatable) {
  26036. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  26037. this._data = null;
  26038. }
  26039. };
  26040. Buffer.prototype.dispose = function () {
  26041. if (!this._buffer) {
  26042. return;
  26043. }
  26044. if (this._engine._releaseBuffer(this._buffer)) {
  26045. this._buffer = null;
  26046. }
  26047. };
  26048. return Buffer;
  26049. }());
  26050. BABYLON.Buffer = Buffer;
  26051. })(BABYLON || (BABYLON = {}));
  26052. //# sourceMappingURL=babylon.buffer.js.map
  26053. var BABYLON;
  26054. (function (BABYLON) {
  26055. var VertexBuffer = /** @class */ (function () {
  26056. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  26057. if (data instanceof BABYLON.Buffer) {
  26058. if (!stride) {
  26059. stride = data.getStrideSize();
  26060. }
  26061. this._buffer = data;
  26062. this._ownsBuffer = false;
  26063. }
  26064. else {
  26065. if (!stride) {
  26066. stride = VertexBuffer.DeduceStride(kind);
  26067. }
  26068. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  26069. this._ownsBuffer = true;
  26070. }
  26071. this._stride = stride;
  26072. this._instanced = instanced !== undefined ? instanced : false;
  26073. this._instanceDivisor = instanced ? 1 : 0;
  26074. this._offset = offset ? offset : 0;
  26075. this._size = size ? size : stride;
  26076. this._kind = kind;
  26077. }
  26078. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  26079. /**
  26080. * Gets or sets the instance divisor when in instanced mode
  26081. */
  26082. get: function () {
  26083. return this._instanceDivisor;
  26084. },
  26085. set: function (value) {
  26086. this._instanceDivisor = value;
  26087. if (value == 0) {
  26088. this._instanced = false;
  26089. }
  26090. else {
  26091. this._instanced = true;
  26092. }
  26093. },
  26094. enumerable: true,
  26095. configurable: true
  26096. });
  26097. VertexBuffer.prototype._rebuild = function () {
  26098. if (!this._buffer) {
  26099. return;
  26100. }
  26101. this._buffer._rebuild();
  26102. };
  26103. /**
  26104. * Returns the kind of the VertexBuffer (string).
  26105. */
  26106. VertexBuffer.prototype.getKind = function () {
  26107. return this._kind;
  26108. };
  26109. // Properties
  26110. /**
  26111. * Boolean : is the VertexBuffer updatable ?
  26112. */
  26113. VertexBuffer.prototype.isUpdatable = function () {
  26114. return this._buffer.isUpdatable();
  26115. };
  26116. /**
  26117. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  26118. */
  26119. VertexBuffer.prototype.getData = function () {
  26120. return this._buffer.getData();
  26121. };
  26122. /**
  26123. * Returns the WebGLBuffer associated to the VertexBuffer.
  26124. */
  26125. VertexBuffer.prototype.getBuffer = function () {
  26126. return this._buffer.getBuffer();
  26127. };
  26128. /**
  26129. * Returns the stride of the VertexBuffer (integer).
  26130. */
  26131. VertexBuffer.prototype.getStrideSize = function () {
  26132. return this._stride;
  26133. };
  26134. /**
  26135. * Returns the offset (integer).
  26136. */
  26137. VertexBuffer.prototype.getOffset = function () {
  26138. return this._offset;
  26139. };
  26140. /**
  26141. * Returns the VertexBuffer total size (integer).
  26142. */
  26143. VertexBuffer.prototype.getSize = function () {
  26144. return this._size;
  26145. };
  26146. /**
  26147. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  26148. */
  26149. VertexBuffer.prototype.getIsInstanced = function () {
  26150. return this._instanced;
  26151. };
  26152. /**
  26153. * Returns the instancing divisor, zero for non-instanced (integer).
  26154. */
  26155. VertexBuffer.prototype.getInstanceDivisor = function () {
  26156. return this._instanceDivisor;
  26157. };
  26158. // Methods
  26159. /**
  26160. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  26161. * Returns the created WebGLBuffer.
  26162. */
  26163. VertexBuffer.prototype.create = function (data) {
  26164. return this._buffer.create(data);
  26165. };
  26166. /**
  26167. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26168. * This function will create a new buffer if the current one is not updatable
  26169. * Returns the updated WebGLBuffer.
  26170. */
  26171. VertexBuffer.prototype.update = function (data) {
  26172. return this._buffer.update(data);
  26173. };
  26174. /**
  26175. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26176. * Returns the directly updated WebGLBuffer.
  26177. */
  26178. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26179. return this._buffer.updateDirectly(data, offset);
  26180. };
  26181. /**
  26182. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26183. */
  26184. VertexBuffer.prototype.dispose = function () {
  26185. if (this._ownsBuffer) {
  26186. this._buffer.dispose();
  26187. }
  26188. };
  26189. Object.defineProperty(VertexBuffer, "PositionKind", {
  26190. get: function () {
  26191. return VertexBuffer._PositionKind;
  26192. },
  26193. enumerable: true,
  26194. configurable: true
  26195. });
  26196. Object.defineProperty(VertexBuffer, "NormalKind", {
  26197. get: function () {
  26198. return VertexBuffer._NormalKind;
  26199. },
  26200. enumerable: true,
  26201. configurable: true
  26202. });
  26203. Object.defineProperty(VertexBuffer, "TangentKind", {
  26204. get: function () {
  26205. return VertexBuffer._TangentKind;
  26206. },
  26207. enumerable: true,
  26208. configurable: true
  26209. });
  26210. Object.defineProperty(VertexBuffer, "UVKind", {
  26211. get: function () {
  26212. return VertexBuffer._UVKind;
  26213. },
  26214. enumerable: true,
  26215. configurable: true
  26216. });
  26217. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26218. get: function () {
  26219. return VertexBuffer._UV2Kind;
  26220. },
  26221. enumerable: true,
  26222. configurable: true
  26223. });
  26224. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26225. get: function () {
  26226. return VertexBuffer._UV3Kind;
  26227. },
  26228. enumerable: true,
  26229. configurable: true
  26230. });
  26231. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26232. get: function () {
  26233. return VertexBuffer._UV4Kind;
  26234. },
  26235. enumerable: true,
  26236. configurable: true
  26237. });
  26238. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26239. get: function () {
  26240. return VertexBuffer._UV5Kind;
  26241. },
  26242. enumerable: true,
  26243. configurable: true
  26244. });
  26245. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26246. get: function () {
  26247. return VertexBuffer._UV6Kind;
  26248. },
  26249. enumerable: true,
  26250. configurable: true
  26251. });
  26252. Object.defineProperty(VertexBuffer, "ColorKind", {
  26253. get: function () {
  26254. return VertexBuffer._ColorKind;
  26255. },
  26256. enumerable: true,
  26257. configurable: true
  26258. });
  26259. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26260. get: function () {
  26261. return VertexBuffer._MatricesIndicesKind;
  26262. },
  26263. enumerable: true,
  26264. configurable: true
  26265. });
  26266. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26267. get: function () {
  26268. return VertexBuffer._MatricesWeightsKind;
  26269. },
  26270. enumerable: true,
  26271. configurable: true
  26272. });
  26273. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26274. get: function () {
  26275. return VertexBuffer._MatricesIndicesExtraKind;
  26276. },
  26277. enumerable: true,
  26278. configurable: true
  26279. });
  26280. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26281. get: function () {
  26282. return VertexBuffer._MatricesWeightsExtraKind;
  26283. },
  26284. enumerable: true,
  26285. configurable: true
  26286. });
  26287. /**
  26288. * Deduces the stride given a kind.
  26289. * @param kind The kind string to deduce
  26290. * @returns The deduced stride
  26291. */
  26292. VertexBuffer.DeduceStride = function (kind) {
  26293. switch (kind) {
  26294. case VertexBuffer.UVKind:
  26295. case VertexBuffer.UV2Kind:
  26296. case VertexBuffer.UV3Kind:
  26297. case VertexBuffer.UV4Kind:
  26298. case VertexBuffer.UV5Kind:
  26299. case VertexBuffer.UV6Kind:
  26300. return 2;
  26301. case VertexBuffer.NormalKind:
  26302. case VertexBuffer.PositionKind:
  26303. return 3;
  26304. case VertexBuffer.ColorKind:
  26305. case VertexBuffer.MatricesIndicesKind:
  26306. case VertexBuffer.MatricesIndicesExtraKind:
  26307. case VertexBuffer.MatricesWeightsKind:
  26308. case VertexBuffer.MatricesWeightsExtraKind:
  26309. case VertexBuffer.TangentKind:
  26310. return 4;
  26311. default:
  26312. throw new Error("Invalid kind '" + kind + "'");
  26313. }
  26314. };
  26315. // Enums
  26316. VertexBuffer._PositionKind = "position";
  26317. VertexBuffer._NormalKind = "normal";
  26318. VertexBuffer._TangentKind = "tangent";
  26319. VertexBuffer._UVKind = "uv";
  26320. VertexBuffer._UV2Kind = "uv2";
  26321. VertexBuffer._UV3Kind = "uv3";
  26322. VertexBuffer._UV4Kind = "uv4";
  26323. VertexBuffer._UV5Kind = "uv5";
  26324. VertexBuffer._UV6Kind = "uv6";
  26325. VertexBuffer._ColorKind = "color";
  26326. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26327. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26328. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26329. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26330. return VertexBuffer;
  26331. }());
  26332. BABYLON.VertexBuffer = VertexBuffer;
  26333. })(BABYLON || (BABYLON = {}));
  26334. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26335. var BABYLON;
  26336. (function (BABYLON) {
  26337. /**
  26338. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26339. */
  26340. var DummyInternalTextureTracker = /** @class */ (function () {
  26341. function DummyInternalTextureTracker() {
  26342. /**
  26343. * Gets or set the previous tracker in the list
  26344. */
  26345. this.previous = null;
  26346. /**
  26347. * Gets or set the next tracker in the list
  26348. */
  26349. this.next = null;
  26350. }
  26351. return DummyInternalTextureTracker;
  26352. }());
  26353. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26354. })(BABYLON || (BABYLON = {}));
  26355. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26356. var BABYLON;
  26357. (function (BABYLON) {
  26358. /**
  26359. * Class used to store data associated with WebGL texture data for the engine
  26360. * This class should not be used directly
  26361. */
  26362. var InternalTexture = /** @class */ (function () {
  26363. /**
  26364. * Creates a new InternalTexture
  26365. * @param engine defines the engine to use
  26366. * @param dataSource defines the type of data that will be used
  26367. */
  26368. function InternalTexture(engine, dataSource) {
  26369. /**
  26370. * Observable called when the texture is loaded
  26371. */
  26372. this.onLoadedObservable = new BABYLON.Observable();
  26373. /**
  26374. * Gets or set the previous tracker in the list
  26375. */
  26376. this.previous = null;
  26377. /**
  26378. * Gets or set the next tracker in the list
  26379. */
  26380. this.next = null;
  26381. // Private
  26382. /** @ignore */
  26383. this._initialSlot = -1;
  26384. /** @ignore */
  26385. this._designatedSlot = -1;
  26386. /** @ignore */
  26387. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26388. /** @ignore */
  26389. this._comparisonFunction = 0;
  26390. /** @ignore */
  26391. this._references = 1;
  26392. this._engine = engine;
  26393. this._dataSource = dataSource;
  26394. this._webGLTexture = engine._createTexture();
  26395. }
  26396. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26397. /**
  26398. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26399. */
  26400. get: function () {
  26401. return this._dataSource;
  26402. },
  26403. enumerable: true,
  26404. configurable: true
  26405. });
  26406. /**
  26407. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26408. */
  26409. InternalTexture.prototype.incrementReferences = function () {
  26410. this._references++;
  26411. };
  26412. /**
  26413. * Change the size of the texture (not the size of the content)
  26414. * @param width defines the new width
  26415. * @param height defines the new height
  26416. * @param depth defines the new depth (1 by default)
  26417. */
  26418. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26419. if (depth === void 0) { depth = 1; }
  26420. this.width = width;
  26421. this.height = height;
  26422. this.depth = depth;
  26423. this.baseWidth = width;
  26424. this.baseHeight = height;
  26425. this.baseDepth = depth;
  26426. this._size = width * height * depth;
  26427. };
  26428. /** @ignore */
  26429. InternalTexture.prototype._rebuild = function () {
  26430. var _this = this;
  26431. var proxy;
  26432. this.isReady = false;
  26433. this._cachedCoordinatesMode = null;
  26434. this._cachedWrapU = null;
  26435. this._cachedWrapV = null;
  26436. this._cachedAnisotropicFilteringLevel = null;
  26437. switch (this._dataSource) {
  26438. case InternalTexture.DATASOURCE_TEMP:
  26439. return;
  26440. case InternalTexture.DATASOURCE_URL:
  26441. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26442. _this.isReady = true;
  26443. }, null, this._buffer, undefined, this.format);
  26444. proxy._swapAndDie(this);
  26445. return;
  26446. case InternalTexture.DATASOURCE_RAW:
  26447. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26448. proxy._swapAndDie(this);
  26449. this.isReady = true;
  26450. return;
  26451. case InternalTexture.DATASOURCE_RAW3D:
  26452. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26453. proxy._swapAndDie(this);
  26454. this.isReady = true;
  26455. return;
  26456. case InternalTexture.DATASOURCE_DYNAMIC:
  26457. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26458. proxy._swapAndDie(this);
  26459. // The engine will make sure to update content so no need to flag it as isReady = true
  26460. return;
  26461. case InternalTexture.DATASOURCE_RENDERTARGET:
  26462. var options = new BABYLON.RenderTargetCreationOptions();
  26463. options.generateDepthBuffer = this._generateDepthBuffer;
  26464. options.generateMipMaps = this.generateMipMaps;
  26465. options.generateStencilBuffer = this._generateStencilBuffer;
  26466. options.samplingMode = this.samplingMode;
  26467. options.type = this.type;
  26468. if (this.isCube) {
  26469. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26470. }
  26471. else {
  26472. var size = {
  26473. width: this.width,
  26474. height: this.height
  26475. };
  26476. proxy = this._engine.createRenderTargetTexture(size, options);
  26477. }
  26478. proxy._swapAndDie(this);
  26479. this.isReady = true;
  26480. return;
  26481. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26482. var depthTextureOptions = {
  26483. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26484. comparisonFunction: this._comparisonFunction,
  26485. generateStencil: this._generateStencilBuffer,
  26486. isCube: this.isCube
  26487. };
  26488. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26489. proxy._swapAndDie(this);
  26490. this.isReady = true;
  26491. return;
  26492. case InternalTexture.DATASOURCE_CUBE:
  26493. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26494. _this.isReady = true;
  26495. }, null, this.format, this._extension);
  26496. proxy._swapAndDie(this);
  26497. return;
  26498. case InternalTexture.DATASOURCE_CUBERAW:
  26499. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26500. proxy._swapAndDie(this);
  26501. this.isReady = true;
  26502. return;
  26503. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26504. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26505. if (proxy) {
  26506. proxy._swapAndDie(_this);
  26507. }
  26508. _this.isReady = true;
  26509. }, null, this.format, this._extension);
  26510. return;
  26511. }
  26512. };
  26513. InternalTexture.prototype._swapAndDie = function (target) {
  26514. target._webGLTexture = this._webGLTexture;
  26515. if (this._framebuffer) {
  26516. target._framebuffer = this._framebuffer;
  26517. }
  26518. if (this._depthStencilBuffer) {
  26519. target._depthStencilBuffer = this._depthStencilBuffer;
  26520. }
  26521. if (this._lodTextureHigh) {
  26522. if (target._lodTextureHigh) {
  26523. target._lodTextureHigh.dispose();
  26524. }
  26525. target._lodTextureHigh = this._lodTextureHigh;
  26526. }
  26527. if (this._lodTextureMid) {
  26528. if (target._lodTextureMid) {
  26529. target._lodTextureMid.dispose();
  26530. }
  26531. target._lodTextureMid = this._lodTextureMid;
  26532. }
  26533. if (this._lodTextureLow) {
  26534. if (target._lodTextureLow) {
  26535. target._lodTextureLow.dispose();
  26536. }
  26537. target._lodTextureLow = this._lodTextureLow;
  26538. }
  26539. var cache = this._engine.getLoadedTexturesCache();
  26540. var index = cache.indexOf(this);
  26541. if (index !== -1) {
  26542. cache.splice(index, 1);
  26543. }
  26544. };
  26545. /**
  26546. * Dispose the current allocated resources
  26547. */
  26548. InternalTexture.prototype.dispose = function () {
  26549. if (!this._webGLTexture) {
  26550. return;
  26551. }
  26552. this._references--;
  26553. if (this._references === 0) {
  26554. this._engine._releaseTexture(this);
  26555. this._webGLTexture = null;
  26556. this.previous = null;
  26557. this.next = null;
  26558. }
  26559. };
  26560. /**
  26561. * The source of the texture data is unknown
  26562. */
  26563. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26564. /**
  26565. * Texture data comes from an URL
  26566. */
  26567. InternalTexture.DATASOURCE_URL = 1;
  26568. /**
  26569. * Texture data is only used for temporary storage
  26570. */
  26571. InternalTexture.DATASOURCE_TEMP = 2;
  26572. /**
  26573. * Texture data comes from raw data (ArrayBuffer)
  26574. */
  26575. InternalTexture.DATASOURCE_RAW = 3;
  26576. /**
  26577. * Texture content is dynamic (video or dynamic texture)
  26578. */
  26579. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26580. /**
  26581. * Texture content is generated by rendering to it
  26582. */
  26583. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26584. /**
  26585. * Texture content is part of a multi render target process
  26586. */
  26587. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26588. /**
  26589. * Texture data comes from a cube data file
  26590. */
  26591. InternalTexture.DATASOURCE_CUBE = 7;
  26592. /**
  26593. * Texture data comes from a raw cube data
  26594. */
  26595. InternalTexture.DATASOURCE_CUBERAW = 8;
  26596. /**
  26597. * Texture data come from a prefiltered cube data file
  26598. */
  26599. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26600. /**
  26601. * Texture content is raw 3D data
  26602. */
  26603. InternalTexture.DATASOURCE_RAW3D = 10;
  26604. /**
  26605. * Texture content is a depth texture
  26606. */
  26607. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26608. return InternalTexture;
  26609. }());
  26610. BABYLON.InternalTexture = InternalTexture;
  26611. })(BABYLON || (BABYLON = {}));
  26612. //# sourceMappingURL=babylon.internalTexture.js.map
  26613. var BABYLON;
  26614. (function (BABYLON) {
  26615. var BaseTexture = /** @class */ (function () {
  26616. function BaseTexture(scene) {
  26617. this._hasAlpha = false;
  26618. this.getAlphaFromRGB = false;
  26619. this.level = 1;
  26620. this.coordinatesIndex = 0;
  26621. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26622. /**
  26623. * | Value | Type | Description |
  26624. * | ----- | ------------------ | ----------- |
  26625. * | 0 | CLAMP_ADDRESSMODE | |
  26626. * | 1 | WRAP_ADDRESSMODE | |
  26627. * | 2 | MIRROR_ADDRESSMODE | |
  26628. */
  26629. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26630. /**
  26631. * | Value | Type | Description |
  26632. * | ----- | ------------------ | ----------- |
  26633. * | 0 | CLAMP_ADDRESSMODE | |
  26634. * | 1 | WRAP_ADDRESSMODE | |
  26635. * | 2 | MIRROR_ADDRESSMODE | |
  26636. */
  26637. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26638. /**
  26639. * | Value | Type | Description |
  26640. * | ----- | ------------------ | ----------- |
  26641. * | 0 | CLAMP_ADDRESSMODE | |
  26642. * | 1 | WRAP_ADDRESSMODE | |
  26643. * | 2 | MIRROR_ADDRESSMODE | |
  26644. */
  26645. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26646. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26647. this.isCube = false;
  26648. this.is3D = false;
  26649. this.gammaSpace = true;
  26650. this.invertZ = false;
  26651. this.lodLevelInAlpha = false;
  26652. this.lodGenerationOffset = 0.0;
  26653. this.lodGenerationScale = 0.8;
  26654. this.isRenderTarget = false;
  26655. this.animations = new Array();
  26656. /**
  26657. * An event triggered when the texture is disposed.
  26658. * @type {BABYLON.Observable}
  26659. */
  26660. this.onDisposeObservable = new BABYLON.Observable();
  26661. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26662. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26663. if (this._scene) {
  26664. this._scene.textures.push(this);
  26665. }
  26666. this._uid = null;
  26667. }
  26668. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26669. get: function () {
  26670. return this._hasAlpha;
  26671. },
  26672. set: function (value) {
  26673. if (this._hasAlpha === value) {
  26674. return;
  26675. }
  26676. this._hasAlpha = value;
  26677. if (this._scene) {
  26678. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26679. }
  26680. },
  26681. enumerable: true,
  26682. configurable: true
  26683. });
  26684. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26685. get: function () {
  26686. return this._coordinatesMode;
  26687. },
  26688. /**
  26689. * How a texture is mapped.
  26690. *
  26691. * | Value | Type | Description |
  26692. * | ----- | ----------------------------------- | ----------- |
  26693. * | 0 | EXPLICIT_MODE | |
  26694. * | 1 | SPHERICAL_MODE | |
  26695. * | 2 | PLANAR_MODE | |
  26696. * | 3 | CUBIC_MODE | |
  26697. * | 4 | PROJECTION_MODE | |
  26698. * | 5 | SKYBOX_MODE | |
  26699. * | 6 | INVCUBIC_MODE | |
  26700. * | 7 | EQUIRECTANGULAR_MODE | |
  26701. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26702. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26703. */
  26704. set: function (value) {
  26705. if (this._coordinatesMode === value) {
  26706. return;
  26707. }
  26708. this._coordinatesMode = value;
  26709. if (this._scene) {
  26710. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26711. }
  26712. },
  26713. enumerable: true,
  26714. configurable: true
  26715. });
  26716. Object.defineProperty(BaseTexture.prototype, "uid", {
  26717. get: function () {
  26718. if (!this._uid) {
  26719. this._uid = BABYLON.Tools.RandomId();
  26720. }
  26721. return this._uid;
  26722. },
  26723. enumerable: true,
  26724. configurable: true
  26725. });
  26726. BaseTexture.prototype.toString = function () {
  26727. return this.name;
  26728. };
  26729. BaseTexture.prototype.getClassName = function () {
  26730. return "BaseTexture";
  26731. };
  26732. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26733. set: function (callback) {
  26734. if (this._onDisposeObserver) {
  26735. this.onDisposeObservable.remove(this._onDisposeObserver);
  26736. }
  26737. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26738. },
  26739. enumerable: true,
  26740. configurable: true
  26741. });
  26742. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26743. get: function () {
  26744. return true;
  26745. },
  26746. enumerable: true,
  26747. configurable: true
  26748. });
  26749. BaseTexture.prototype.getScene = function () {
  26750. return this._scene;
  26751. };
  26752. BaseTexture.prototype.getTextureMatrix = function () {
  26753. return BABYLON.Matrix.IdentityReadOnly;
  26754. };
  26755. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26756. return BABYLON.Matrix.IdentityReadOnly;
  26757. };
  26758. BaseTexture.prototype.getInternalTexture = function () {
  26759. return this._texture;
  26760. };
  26761. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26762. return !this.isBlocking || this.isReady();
  26763. };
  26764. BaseTexture.prototype.isReady = function () {
  26765. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26766. this.delayLoad();
  26767. return false;
  26768. }
  26769. if (this._texture) {
  26770. return this._texture.isReady;
  26771. }
  26772. return false;
  26773. };
  26774. BaseTexture.prototype.getSize = function () {
  26775. if (this._texture && this._texture.width) {
  26776. return new BABYLON.Size(this._texture.width, this._texture.height);
  26777. }
  26778. if (this._texture && this._texture._size) {
  26779. return new BABYLON.Size(this._texture._size, this._texture._size);
  26780. }
  26781. return BABYLON.Size.Zero();
  26782. };
  26783. BaseTexture.prototype.getBaseSize = function () {
  26784. if (!this.isReady() || !this._texture)
  26785. return BABYLON.Size.Zero();
  26786. if (this._texture._size) {
  26787. return new BABYLON.Size(this._texture._size, this._texture._size);
  26788. }
  26789. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26790. };
  26791. BaseTexture.prototype.scale = function (ratio) {
  26792. };
  26793. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26794. get: function () {
  26795. return false;
  26796. },
  26797. enumerable: true,
  26798. configurable: true
  26799. });
  26800. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26801. if (!this._scene) {
  26802. return null;
  26803. }
  26804. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26805. for (var index = 0; index < texturesCache.length; index++) {
  26806. var texturesCacheEntry = texturesCache[index];
  26807. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26808. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26809. texturesCacheEntry.incrementReferences();
  26810. return texturesCacheEntry;
  26811. }
  26812. }
  26813. }
  26814. return null;
  26815. };
  26816. BaseTexture.prototype._rebuild = function () {
  26817. };
  26818. BaseTexture.prototype.delayLoad = function () {
  26819. };
  26820. BaseTexture.prototype.clone = function () {
  26821. return null;
  26822. };
  26823. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26824. get: function () {
  26825. if (!this._texture) {
  26826. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26827. }
  26828. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26829. },
  26830. enumerable: true,
  26831. configurable: true
  26832. });
  26833. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26834. get: function () {
  26835. if (!this._texture) {
  26836. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26837. }
  26838. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26839. },
  26840. enumerable: true,
  26841. configurable: true
  26842. });
  26843. BaseTexture.prototype.readPixels = function (faceIndex) {
  26844. if (faceIndex === void 0) { faceIndex = 0; }
  26845. if (!this._texture) {
  26846. return null;
  26847. }
  26848. var size = this.getSize();
  26849. var scene = this.getScene();
  26850. if (!scene) {
  26851. return null;
  26852. }
  26853. var engine = scene.getEngine();
  26854. if (this._texture.isCube) {
  26855. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26856. }
  26857. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26858. };
  26859. BaseTexture.prototype.releaseInternalTexture = function () {
  26860. if (this._texture) {
  26861. this._texture.dispose();
  26862. this._texture = null;
  26863. }
  26864. };
  26865. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26866. get: function () {
  26867. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26868. return null;
  26869. }
  26870. if (!this._texture._sphericalPolynomial) {
  26871. this._texture._sphericalPolynomial =
  26872. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26873. }
  26874. return this._texture._sphericalPolynomial;
  26875. },
  26876. set: function (value) {
  26877. if (this._texture) {
  26878. this._texture._sphericalPolynomial = value;
  26879. }
  26880. },
  26881. enumerable: true,
  26882. configurable: true
  26883. });
  26884. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26885. get: function () {
  26886. if (this._texture) {
  26887. return this._texture._lodTextureHigh;
  26888. }
  26889. return null;
  26890. },
  26891. enumerable: true,
  26892. configurable: true
  26893. });
  26894. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26895. get: function () {
  26896. if (this._texture) {
  26897. return this._texture._lodTextureMid;
  26898. }
  26899. return null;
  26900. },
  26901. enumerable: true,
  26902. configurable: true
  26903. });
  26904. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26905. get: function () {
  26906. if (this._texture) {
  26907. return this._texture._lodTextureLow;
  26908. }
  26909. return null;
  26910. },
  26911. enumerable: true,
  26912. configurable: true
  26913. });
  26914. BaseTexture.prototype.dispose = function () {
  26915. if (!this._scene) {
  26916. return;
  26917. }
  26918. // Animations
  26919. this._scene.stopAnimation(this);
  26920. // Remove from scene
  26921. this._scene._removePendingData(this);
  26922. var index = this._scene.textures.indexOf(this);
  26923. if (index >= 0) {
  26924. this._scene.textures.splice(index, 1);
  26925. }
  26926. if (this._texture === undefined) {
  26927. return;
  26928. }
  26929. // Release
  26930. this.releaseInternalTexture();
  26931. // Callback
  26932. this.onDisposeObservable.notifyObservers(this);
  26933. this.onDisposeObservable.clear();
  26934. };
  26935. BaseTexture.prototype.serialize = function () {
  26936. if (!this.name) {
  26937. return null;
  26938. }
  26939. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26940. // Animations
  26941. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26942. return serializationObject;
  26943. };
  26944. BaseTexture.WhenAllReady = function (textures, callback) {
  26945. var numRemaining = textures.length;
  26946. if (numRemaining === 0) {
  26947. callback();
  26948. return;
  26949. }
  26950. var _loop_1 = function () {
  26951. texture = textures[i];
  26952. if (texture.isReady()) {
  26953. if (--numRemaining === 0) {
  26954. callback();
  26955. }
  26956. }
  26957. else {
  26958. onLoadObservable = texture.onLoadObservable;
  26959. var onLoadCallback_1 = function () {
  26960. onLoadObservable.removeCallback(onLoadCallback_1);
  26961. if (--numRemaining === 0) {
  26962. callback();
  26963. }
  26964. };
  26965. onLoadObservable.add(onLoadCallback_1);
  26966. }
  26967. };
  26968. var texture, onLoadObservable;
  26969. for (var i = 0; i < textures.length; i++) {
  26970. _loop_1();
  26971. }
  26972. };
  26973. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26974. __decorate([
  26975. BABYLON.serialize()
  26976. ], BaseTexture.prototype, "name", void 0);
  26977. __decorate([
  26978. BABYLON.serialize("hasAlpha")
  26979. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26980. __decorate([
  26981. BABYLON.serialize()
  26982. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26983. __decorate([
  26984. BABYLON.serialize()
  26985. ], BaseTexture.prototype, "level", void 0);
  26986. __decorate([
  26987. BABYLON.serialize()
  26988. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26989. __decorate([
  26990. BABYLON.serialize("coordinatesMode")
  26991. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26992. __decorate([
  26993. BABYLON.serialize()
  26994. ], BaseTexture.prototype, "wrapU", void 0);
  26995. __decorate([
  26996. BABYLON.serialize()
  26997. ], BaseTexture.prototype, "wrapV", void 0);
  26998. __decorate([
  26999. BABYLON.serialize()
  27000. ], BaseTexture.prototype, "wrapR", void 0);
  27001. __decorate([
  27002. BABYLON.serialize()
  27003. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  27004. __decorate([
  27005. BABYLON.serialize()
  27006. ], BaseTexture.prototype, "isCube", void 0);
  27007. __decorate([
  27008. BABYLON.serialize()
  27009. ], BaseTexture.prototype, "is3D", void 0);
  27010. __decorate([
  27011. BABYLON.serialize()
  27012. ], BaseTexture.prototype, "gammaSpace", void 0);
  27013. __decorate([
  27014. BABYLON.serialize()
  27015. ], BaseTexture.prototype, "invertZ", void 0);
  27016. __decorate([
  27017. BABYLON.serialize()
  27018. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  27019. __decorate([
  27020. BABYLON.serialize()
  27021. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  27022. __decorate([
  27023. BABYLON.serialize()
  27024. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  27025. __decorate([
  27026. BABYLON.serialize()
  27027. ], BaseTexture.prototype, "isRenderTarget", void 0);
  27028. return BaseTexture;
  27029. }());
  27030. BABYLON.BaseTexture = BaseTexture;
  27031. })(BABYLON || (BABYLON = {}));
  27032. //# sourceMappingURL=babylon.baseTexture.js.map
  27033. var BABYLON;
  27034. (function (BABYLON) {
  27035. var Texture = /** @class */ (function (_super) {
  27036. __extends(Texture, _super);
  27037. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  27038. if (noMipmap === void 0) { noMipmap = false; }
  27039. if (invertY === void 0) { invertY = true; }
  27040. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27041. if (onLoad === void 0) { onLoad = null; }
  27042. if (onError === void 0) { onError = null; }
  27043. if (buffer === void 0) { buffer = null; }
  27044. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27045. var _this = _super.call(this, scene) || this;
  27046. _this.uOffset = 0;
  27047. _this.vOffset = 0;
  27048. _this.uScale = 1.0;
  27049. _this.vScale = 1.0;
  27050. _this.uAng = 0;
  27051. _this.vAng = 0;
  27052. _this.wAng = 0;
  27053. _this._isBlocking = true;
  27054. _this.name = url || "";
  27055. _this.url = url;
  27056. _this._noMipmap = noMipmap;
  27057. _this._invertY = invertY;
  27058. _this._samplingMode = samplingMode;
  27059. _this._buffer = buffer;
  27060. _this._deleteBuffer = deleteBuffer;
  27061. if (format) {
  27062. _this._format = format;
  27063. }
  27064. scene = _this.getScene();
  27065. if (!scene) {
  27066. return _this;
  27067. }
  27068. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  27069. var load = function () {
  27070. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  27071. _this.onLoadObservable.notifyObservers(_this);
  27072. }
  27073. if (onLoad) {
  27074. onLoad();
  27075. }
  27076. if (!_this.isBlocking && scene) {
  27077. scene.resetCachedMaterial();
  27078. }
  27079. };
  27080. if (!_this.url) {
  27081. _this._delayedOnLoad = load;
  27082. _this._delayedOnError = onError;
  27083. return _this;
  27084. }
  27085. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  27086. if (!_this._texture) {
  27087. if (!scene.useDelayedTextureLoading) {
  27088. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  27089. if (deleteBuffer) {
  27090. delete _this._buffer;
  27091. }
  27092. }
  27093. else {
  27094. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27095. _this._delayedOnLoad = load;
  27096. _this._delayedOnError = onError;
  27097. }
  27098. }
  27099. else {
  27100. if (_this._texture.isReady) {
  27101. BABYLON.Tools.SetImmediate(function () { return load(); });
  27102. }
  27103. else {
  27104. _this._texture.onLoadedObservable.add(load);
  27105. }
  27106. }
  27107. return _this;
  27108. }
  27109. Object.defineProperty(Texture.prototype, "noMipmap", {
  27110. get: function () {
  27111. return this._noMipmap;
  27112. },
  27113. enumerable: true,
  27114. configurable: true
  27115. });
  27116. Object.defineProperty(Texture.prototype, "isBlocking", {
  27117. get: function () {
  27118. return this._isBlocking;
  27119. },
  27120. set: function (value) {
  27121. this._isBlocking = value;
  27122. },
  27123. enumerable: true,
  27124. configurable: true
  27125. });
  27126. Object.defineProperty(Texture.prototype, "samplingMode", {
  27127. get: function () {
  27128. return this._samplingMode;
  27129. },
  27130. enumerable: true,
  27131. configurable: true
  27132. });
  27133. Texture.prototype.updateURL = function (url) {
  27134. this.url = url;
  27135. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27136. this.delayLoad();
  27137. };
  27138. Texture.prototype.delayLoad = function () {
  27139. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27140. return;
  27141. }
  27142. var scene = this.getScene();
  27143. if (!scene) {
  27144. return;
  27145. }
  27146. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27147. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27148. if (!this._texture) {
  27149. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27150. if (this._deleteBuffer) {
  27151. delete this._buffer;
  27152. }
  27153. }
  27154. else {
  27155. if (this._delayedOnLoad) {
  27156. if (this._texture.isReady) {
  27157. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  27158. }
  27159. else {
  27160. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27161. }
  27162. }
  27163. }
  27164. this._delayedOnLoad = null;
  27165. this._delayedOnError = null;
  27166. };
  27167. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27168. if (!this._texture) {
  27169. return;
  27170. }
  27171. var scene = this.getScene();
  27172. if (!scene) {
  27173. return;
  27174. }
  27175. this._samplingMode = samplingMode;
  27176. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27177. };
  27178. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27179. x *= this.uScale;
  27180. y *= this.vScale;
  27181. x -= 0.5 * this.uScale;
  27182. y -= 0.5 * this.vScale;
  27183. z -= 0.5;
  27184. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27185. t.x += 0.5 * this.uScale + this.uOffset;
  27186. t.y += 0.5 * this.vScale + this.vOffset;
  27187. t.z += 0.5;
  27188. };
  27189. Texture.prototype.getTextureMatrix = function () {
  27190. var _this = this;
  27191. if (this.uOffset === this._cachedUOffset &&
  27192. this.vOffset === this._cachedVOffset &&
  27193. this.uScale === this._cachedUScale &&
  27194. this.vScale === this._cachedVScale &&
  27195. this.uAng === this._cachedUAng &&
  27196. this.vAng === this._cachedVAng &&
  27197. this.wAng === this._cachedWAng) {
  27198. return this._cachedTextureMatrix;
  27199. }
  27200. this._cachedUOffset = this.uOffset;
  27201. this._cachedVOffset = this.vOffset;
  27202. this._cachedUScale = this.uScale;
  27203. this._cachedVScale = this.vScale;
  27204. this._cachedUAng = this.uAng;
  27205. this._cachedVAng = this.vAng;
  27206. this._cachedWAng = this.wAng;
  27207. if (!this._cachedTextureMatrix) {
  27208. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27209. this._rowGenerationMatrix = new BABYLON.Matrix();
  27210. this._t0 = BABYLON.Vector3.Zero();
  27211. this._t1 = BABYLON.Vector3.Zero();
  27212. this._t2 = BABYLON.Vector3.Zero();
  27213. }
  27214. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27215. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27216. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27217. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27218. this._t1.subtractInPlace(this._t0);
  27219. this._t2.subtractInPlace(this._t0);
  27220. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27221. this._cachedTextureMatrix.m[0] = this._t1.x;
  27222. this._cachedTextureMatrix.m[1] = this._t1.y;
  27223. this._cachedTextureMatrix.m[2] = this._t1.z;
  27224. this._cachedTextureMatrix.m[4] = this._t2.x;
  27225. this._cachedTextureMatrix.m[5] = this._t2.y;
  27226. this._cachedTextureMatrix.m[6] = this._t2.z;
  27227. this._cachedTextureMatrix.m[8] = this._t0.x;
  27228. this._cachedTextureMatrix.m[9] = this._t0.y;
  27229. this._cachedTextureMatrix.m[10] = this._t0.z;
  27230. var scene = this.getScene();
  27231. if (!scene) {
  27232. return this._cachedTextureMatrix;
  27233. }
  27234. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27235. return mat.hasTexture(_this);
  27236. });
  27237. return this._cachedTextureMatrix;
  27238. };
  27239. Texture.prototype.getReflectionTextureMatrix = function () {
  27240. var _this = this;
  27241. var scene = this.getScene();
  27242. if (!scene) {
  27243. return this._cachedTextureMatrix;
  27244. }
  27245. if (this.uOffset === this._cachedUOffset &&
  27246. this.vOffset === this._cachedVOffset &&
  27247. this.uScale === this._cachedUScale &&
  27248. this.vScale === this._cachedVScale &&
  27249. this.coordinatesMode === this._cachedCoordinatesMode) {
  27250. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27251. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27252. return this._cachedTextureMatrix;
  27253. }
  27254. }
  27255. else {
  27256. return this._cachedTextureMatrix;
  27257. }
  27258. }
  27259. if (!this._cachedTextureMatrix) {
  27260. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27261. }
  27262. if (!this._projectionModeMatrix) {
  27263. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27264. }
  27265. this._cachedUOffset = this.uOffset;
  27266. this._cachedVOffset = this.vOffset;
  27267. this._cachedUScale = this.uScale;
  27268. this._cachedVScale = this.vScale;
  27269. this._cachedCoordinatesMode = this.coordinatesMode;
  27270. switch (this.coordinatesMode) {
  27271. case Texture.PLANAR_MODE:
  27272. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27273. this._cachedTextureMatrix[0] = this.uScale;
  27274. this._cachedTextureMatrix[5] = this.vScale;
  27275. this._cachedTextureMatrix[12] = this.uOffset;
  27276. this._cachedTextureMatrix[13] = this.vOffset;
  27277. break;
  27278. case Texture.PROJECTION_MODE:
  27279. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27280. this._projectionModeMatrix.m[0] = 0.5;
  27281. this._projectionModeMatrix.m[5] = -0.5;
  27282. this._projectionModeMatrix.m[10] = 0.0;
  27283. this._projectionModeMatrix.m[12] = 0.5;
  27284. this._projectionModeMatrix.m[13] = 0.5;
  27285. this._projectionModeMatrix.m[14] = 1.0;
  27286. this._projectionModeMatrix.m[15] = 1.0;
  27287. var projectionMatrix = scene.getProjectionMatrix();
  27288. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27289. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27290. break;
  27291. default:
  27292. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27293. break;
  27294. }
  27295. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27296. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27297. });
  27298. return this._cachedTextureMatrix;
  27299. };
  27300. Texture.prototype.clone = function () {
  27301. var _this = this;
  27302. return BABYLON.SerializationHelper.Clone(function () {
  27303. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27304. }, this);
  27305. };
  27306. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27307. get: function () {
  27308. if (!this._onLoadObservable) {
  27309. this._onLoadObservable = new BABYLON.Observable();
  27310. }
  27311. return this._onLoadObservable;
  27312. },
  27313. enumerable: true,
  27314. configurable: true
  27315. });
  27316. Texture.prototype.serialize = function () {
  27317. var serializationObject = _super.prototype.serialize.call(this);
  27318. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27319. serializationObject.base64String = this._buffer;
  27320. serializationObject.name = serializationObject.name.replace("data:", "");
  27321. }
  27322. return serializationObject;
  27323. };
  27324. Texture.prototype.getClassName = function () {
  27325. return "Texture";
  27326. };
  27327. Texture.prototype.dispose = function () {
  27328. _super.prototype.dispose.call(this);
  27329. if (this.onLoadObservable) {
  27330. this.onLoadObservable.clear();
  27331. this._onLoadObservable = null;
  27332. }
  27333. this._delayedOnLoad = null;
  27334. this._delayedOnError = null;
  27335. };
  27336. // Statics
  27337. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27338. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27339. if (onLoad === void 0) { onLoad = null; }
  27340. if (onError === void 0) { onError = null; }
  27341. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27342. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27343. };
  27344. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27345. if (parsedTexture.customType) {
  27346. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27347. // Update Sampling Mode
  27348. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27349. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27350. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27351. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27352. }
  27353. }
  27354. return parsedCustomTexture;
  27355. }
  27356. if (parsedTexture.isCube) {
  27357. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27358. }
  27359. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27360. return null;
  27361. }
  27362. var texture = BABYLON.SerializationHelper.Parse(function () {
  27363. var generateMipMaps = true;
  27364. if (parsedTexture.noMipmap) {
  27365. generateMipMaps = false;
  27366. }
  27367. if (parsedTexture.mirrorPlane) {
  27368. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27369. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27370. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27371. return mirrorTexture;
  27372. }
  27373. else if (parsedTexture.isRenderTarget) {
  27374. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27375. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27376. return renderTargetTexture;
  27377. }
  27378. else {
  27379. var texture;
  27380. if (parsedTexture.base64String) {
  27381. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27382. }
  27383. else {
  27384. var url = rootUrl + parsedTexture.name;
  27385. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27386. url = parsedTexture.url;
  27387. }
  27388. texture = new Texture(url, scene, !generateMipMaps);
  27389. }
  27390. return texture;
  27391. }
  27392. }, parsedTexture, scene);
  27393. // Update Sampling Mode
  27394. if (parsedTexture.samplingMode) {
  27395. var sampling = parsedTexture.samplingMode;
  27396. if (texture._samplingMode !== sampling) {
  27397. texture.updateSamplingMode(sampling);
  27398. }
  27399. }
  27400. // Animations
  27401. if (parsedTexture.animations) {
  27402. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27403. var parsedAnimation = parsedTexture.animations[animationIndex];
  27404. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27405. }
  27406. }
  27407. return texture;
  27408. };
  27409. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27410. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27411. if (noMipmap === void 0) { noMipmap = false; }
  27412. if (invertY === void 0) { invertY = true; }
  27413. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27414. if (onLoad === void 0) { onLoad = null; }
  27415. if (onError === void 0) { onError = null; }
  27416. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27417. if (name.substr(0, 5) !== "data:") {
  27418. name = "data:" + name;
  27419. }
  27420. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27421. };
  27422. // Constants
  27423. Texture.NEAREST_SAMPLINGMODE = 1;
  27424. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27425. Texture.BILINEAR_SAMPLINGMODE = 2;
  27426. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27427. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27428. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27429. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27430. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27431. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27432. Texture.NEAREST_LINEAR = 7;
  27433. Texture.NEAREST_NEAREST = 8;
  27434. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27435. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27436. Texture.LINEAR_LINEAR = 11;
  27437. Texture.LINEAR_NEAREST = 12;
  27438. Texture.EXPLICIT_MODE = 0;
  27439. Texture.SPHERICAL_MODE = 1;
  27440. Texture.PLANAR_MODE = 2;
  27441. Texture.CUBIC_MODE = 3;
  27442. Texture.PROJECTION_MODE = 4;
  27443. Texture.SKYBOX_MODE = 5;
  27444. Texture.INVCUBIC_MODE = 6;
  27445. Texture.EQUIRECTANGULAR_MODE = 7;
  27446. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27447. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27448. Texture.CLAMP_ADDRESSMODE = 0;
  27449. Texture.WRAP_ADDRESSMODE = 1;
  27450. Texture.MIRROR_ADDRESSMODE = 2;
  27451. /**
  27452. * 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
  27453. */
  27454. Texture.UseSerializedUrlIfAny = false;
  27455. __decorate([
  27456. BABYLON.serialize()
  27457. ], Texture.prototype, "url", void 0);
  27458. __decorate([
  27459. BABYLON.serialize()
  27460. ], Texture.prototype, "uOffset", void 0);
  27461. __decorate([
  27462. BABYLON.serialize()
  27463. ], Texture.prototype, "vOffset", void 0);
  27464. __decorate([
  27465. BABYLON.serialize()
  27466. ], Texture.prototype, "uScale", void 0);
  27467. __decorate([
  27468. BABYLON.serialize()
  27469. ], Texture.prototype, "vScale", void 0);
  27470. __decorate([
  27471. BABYLON.serialize()
  27472. ], Texture.prototype, "uAng", void 0);
  27473. __decorate([
  27474. BABYLON.serialize()
  27475. ], Texture.prototype, "vAng", void 0);
  27476. __decorate([
  27477. BABYLON.serialize()
  27478. ], Texture.prototype, "wAng", void 0);
  27479. __decorate([
  27480. BABYLON.serialize()
  27481. ], Texture.prototype, "isBlocking", null);
  27482. return Texture;
  27483. }(BABYLON.BaseTexture));
  27484. BABYLON.Texture = Texture;
  27485. })(BABYLON || (BABYLON = {}));
  27486. //# sourceMappingURL=babylon.texture.js.map
  27487. var BABYLON;
  27488. (function (BABYLON) {
  27489. var _InstancesBatch = /** @class */ (function () {
  27490. function _InstancesBatch() {
  27491. this.mustReturn = false;
  27492. this.visibleInstances = new Array();
  27493. this.renderSelf = new Array();
  27494. }
  27495. return _InstancesBatch;
  27496. }());
  27497. BABYLON._InstancesBatch = _InstancesBatch;
  27498. var Mesh = /** @class */ (function (_super) {
  27499. __extends(Mesh, _super);
  27500. /**
  27501. * @constructor
  27502. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27503. * @param {Scene} scene The scene to add this mesh to.
  27504. * @param {Node} parent The parent of this mesh, if it has one
  27505. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27506. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27507. * When false, achieved by calling a clone(), also passing False.
  27508. * This will make creation of children, recursive.
  27509. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27510. */
  27511. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27512. if (scene === void 0) { scene = null; }
  27513. if (parent === void 0) { parent = null; }
  27514. if (source === void 0) { source = null; }
  27515. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27516. var _this = _super.call(this, name, scene) || this;
  27517. // Events
  27518. /**
  27519. * An event triggered before rendering the mesh
  27520. * @type {BABYLON.Observable}
  27521. */
  27522. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27523. /**
  27524. * An event triggered after rendering the mesh
  27525. * @type {BABYLON.Observable}
  27526. */
  27527. _this.onAfterRenderObservable = new BABYLON.Observable();
  27528. /**
  27529. * An event triggered before drawing the mesh
  27530. * @type {BABYLON.Observable}
  27531. */
  27532. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27533. // Members
  27534. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27535. _this.instances = new Array();
  27536. _this._LODLevels = new Array();
  27537. _this._visibleInstances = {};
  27538. _this._renderIdForInstances = new Array();
  27539. _this._batchCache = new _InstancesBatch();
  27540. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27541. // Use by builder only to know what orientation were the mesh build in.
  27542. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27543. _this.overrideMaterialSideOrientation = null;
  27544. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27545. // Will be used to save a source mesh reference, If any
  27546. _this._source = null;
  27547. scene = _this.getScene();
  27548. if (source) {
  27549. // Source mesh
  27550. _this._source = source;
  27551. // Geometry
  27552. if (source._geometry) {
  27553. source._geometry.applyToMesh(_this);
  27554. }
  27555. // Deep copy
  27556. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27557. // Metadata
  27558. if (source.metadata && source.metadata.clone) {
  27559. _this.metadata = source.metadata.clone();
  27560. }
  27561. else {
  27562. _this.metadata = source.metadata;
  27563. }
  27564. // Tags
  27565. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27566. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27567. }
  27568. // Parent
  27569. _this.parent = source.parent;
  27570. // Pivot
  27571. _this.setPivotMatrix(source.getPivotMatrix());
  27572. _this.id = name + "." + source.id;
  27573. // Material
  27574. _this.material = source.material;
  27575. var index;
  27576. if (!doNotCloneChildren) {
  27577. // Children
  27578. var directDescendants = source.getDescendants(true);
  27579. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27580. var child = directDescendants[index_1];
  27581. if (child.clone) {
  27582. child.clone(name + "." + child.name, _this);
  27583. }
  27584. }
  27585. }
  27586. // Physics clone
  27587. var physicsEngine = _this.getScene().getPhysicsEngine();
  27588. if (clonePhysicsImpostor && physicsEngine) {
  27589. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27590. if (impostor) {
  27591. _this.physicsImpostor = impostor.clone(_this);
  27592. }
  27593. }
  27594. // Particles
  27595. for (index = 0; index < scene.particleSystems.length; index++) {
  27596. var system = scene.particleSystems[index];
  27597. if (system.emitter === source) {
  27598. system.clone(system.name, _this);
  27599. }
  27600. }
  27601. _this.computeWorldMatrix(true);
  27602. }
  27603. // Parent
  27604. if (parent !== null) {
  27605. _this.parent = parent;
  27606. }
  27607. return _this;
  27608. }
  27609. Object.defineProperty(Mesh, "FRONTSIDE", {
  27610. /**
  27611. * Mesh side orientation : usually the external or front surface
  27612. */
  27613. get: function () {
  27614. return Mesh._FRONTSIDE;
  27615. },
  27616. enumerable: true,
  27617. configurable: true
  27618. });
  27619. Object.defineProperty(Mesh, "BACKSIDE", {
  27620. /**
  27621. * Mesh side orientation : usually the internal or back surface
  27622. */
  27623. get: function () {
  27624. return Mesh._BACKSIDE;
  27625. },
  27626. enumerable: true,
  27627. configurable: true
  27628. });
  27629. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27630. /**
  27631. * Mesh side orientation : both internal and external or front and back surfaces
  27632. */
  27633. get: function () {
  27634. return Mesh._DOUBLESIDE;
  27635. },
  27636. enumerable: true,
  27637. configurable: true
  27638. });
  27639. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27640. /**
  27641. * Mesh side orientation : by default, `FRONTSIDE`
  27642. */
  27643. get: function () {
  27644. return Mesh._DEFAULTSIDE;
  27645. },
  27646. enumerable: true,
  27647. configurable: true
  27648. });
  27649. Object.defineProperty(Mesh, "NO_CAP", {
  27650. /**
  27651. * Mesh cap setting : no cap
  27652. */
  27653. get: function () {
  27654. return Mesh._NO_CAP;
  27655. },
  27656. enumerable: true,
  27657. configurable: true
  27658. });
  27659. Object.defineProperty(Mesh, "CAP_START", {
  27660. /**
  27661. * Mesh cap setting : one cap at the beginning of the mesh
  27662. */
  27663. get: function () {
  27664. return Mesh._CAP_START;
  27665. },
  27666. enumerable: true,
  27667. configurable: true
  27668. });
  27669. Object.defineProperty(Mesh, "CAP_END", {
  27670. /**
  27671. * Mesh cap setting : one cap at the end of the mesh
  27672. */
  27673. get: function () {
  27674. return Mesh._CAP_END;
  27675. },
  27676. enumerable: true,
  27677. configurable: true
  27678. });
  27679. Object.defineProperty(Mesh, "CAP_ALL", {
  27680. /**
  27681. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27682. */
  27683. get: function () {
  27684. return Mesh._CAP_ALL;
  27685. },
  27686. enumerable: true,
  27687. configurable: true
  27688. });
  27689. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27690. set: function (callback) {
  27691. if (this._onBeforeDrawObserver) {
  27692. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27693. }
  27694. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27695. },
  27696. enumerable: true,
  27697. configurable: true
  27698. });
  27699. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27700. get: function () {
  27701. return this._morphTargetManager;
  27702. },
  27703. set: function (value) {
  27704. if (this._morphTargetManager === value) {
  27705. return;
  27706. }
  27707. this._morphTargetManager = value;
  27708. this._syncGeometryWithMorphTargetManager();
  27709. },
  27710. enumerable: true,
  27711. configurable: true
  27712. });
  27713. Object.defineProperty(Mesh.prototype, "source", {
  27714. get: function () {
  27715. return this._source;
  27716. },
  27717. enumerable: true,
  27718. configurable: true
  27719. });
  27720. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27721. get: function () {
  27722. return this._unIndexed;
  27723. },
  27724. set: function (value) {
  27725. if (this._unIndexed !== value) {
  27726. this._unIndexed = value;
  27727. this._markSubMeshesAsAttributesDirty();
  27728. }
  27729. },
  27730. enumerable: true,
  27731. configurable: true
  27732. });
  27733. // Methods
  27734. /**
  27735. * Returns the string "Mesh".
  27736. */
  27737. Mesh.prototype.getClassName = function () {
  27738. return "Mesh";
  27739. };
  27740. /**
  27741. * Returns a string.
  27742. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27743. */
  27744. Mesh.prototype.toString = function (fullDetails) {
  27745. var ret = _super.prototype.toString.call(this, fullDetails);
  27746. ret += ", n vertices: " + this.getTotalVertices();
  27747. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27748. if (this.animations) {
  27749. for (var i = 0; i < this.animations.length; i++) {
  27750. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27751. }
  27752. }
  27753. if (fullDetails) {
  27754. if (this._geometry) {
  27755. var ib = this.getIndices();
  27756. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27757. if (vb && ib) {
  27758. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27759. }
  27760. }
  27761. else {
  27762. ret += ", flat shading: UNKNOWN";
  27763. }
  27764. }
  27765. return ret;
  27766. };
  27767. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27768. /**
  27769. * True if the mesh has some Levels Of Details (LOD).
  27770. * Returns a boolean.
  27771. */
  27772. get: function () {
  27773. return this._LODLevels.length > 0;
  27774. },
  27775. enumerable: true,
  27776. configurable: true
  27777. });
  27778. /**
  27779. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27780. * @returns an array of {BABYLON.MeshLODLevel}
  27781. */
  27782. Mesh.prototype.getLODLevels = function () {
  27783. return this._LODLevels;
  27784. };
  27785. Mesh.prototype._sortLODLevels = function () {
  27786. this._LODLevels.sort(function (a, b) {
  27787. if (a.distance < b.distance) {
  27788. return 1;
  27789. }
  27790. if (a.distance > b.distance) {
  27791. return -1;
  27792. }
  27793. return 0;
  27794. });
  27795. };
  27796. /**
  27797. * Add a mesh as LOD level triggered at the given distance.
  27798. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27799. * @param {number} distance The distance from the center of the object to show this level
  27800. * @param {Mesh} mesh The mesh to be added as LOD level
  27801. * @return {Mesh} This mesh (for chaining)
  27802. */
  27803. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27804. if (mesh && mesh._masterMesh) {
  27805. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27806. return this;
  27807. }
  27808. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27809. this._LODLevels.push(level);
  27810. if (mesh) {
  27811. mesh._masterMesh = this;
  27812. }
  27813. this._sortLODLevels();
  27814. return this;
  27815. };
  27816. /**
  27817. * Returns the LOD level mesh at the passed distance or null if not found.
  27818. * It is related to the method `addLODLevel(distance, mesh)`.
  27819. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27820. * Returns an object Mesh or `null`.
  27821. */
  27822. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27823. for (var index = 0; index < this._LODLevels.length; index++) {
  27824. var level = this._LODLevels[index];
  27825. if (level.distance === distance) {
  27826. return level.mesh;
  27827. }
  27828. }
  27829. return null;
  27830. };
  27831. /**
  27832. * Remove a mesh from the LOD array
  27833. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27834. * @param {Mesh} mesh The mesh to be removed.
  27835. * @return {Mesh} This mesh (for chaining)
  27836. */
  27837. Mesh.prototype.removeLODLevel = function (mesh) {
  27838. for (var index = 0; index < this._LODLevels.length; index++) {
  27839. if (this._LODLevels[index].mesh === mesh) {
  27840. this._LODLevels.splice(index, 1);
  27841. if (mesh) {
  27842. mesh._masterMesh = null;
  27843. }
  27844. }
  27845. }
  27846. this._sortLODLevels();
  27847. return this;
  27848. };
  27849. /**
  27850. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27851. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27852. */
  27853. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27854. if (!this._LODLevels || this._LODLevels.length === 0) {
  27855. return this;
  27856. }
  27857. var bSphere;
  27858. if (boundingSphere) {
  27859. bSphere = boundingSphere;
  27860. }
  27861. else {
  27862. var boundingInfo = this.getBoundingInfo();
  27863. bSphere = boundingInfo.boundingSphere;
  27864. }
  27865. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27866. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27867. if (this.onLODLevelSelection) {
  27868. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27869. }
  27870. return this;
  27871. }
  27872. for (var index = 0; index < this._LODLevels.length; index++) {
  27873. var level = this._LODLevels[index];
  27874. if (level.distance < distanceToCamera) {
  27875. if (level.mesh) {
  27876. level.mesh._preActivate();
  27877. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27878. }
  27879. if (this.onLODLevelSelection) {
  27880. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27881. }
  27882. return level.mesh;
  27883. }
  27884. }
  27885. if (this.onLODLevelSelection) {
  27886. this.onLODLevelSelection(distanceToCamera, this, this);
  27887. }
  27888. return this;
  27889. };
  27890. Object.defineProperty(Mesh.prototype, "geometry", {
  27891. /**
  27892. * Returns the mesh internal Geometry object.
  27893. */
  27894. get: function () {
  27895. return this._geometry;
  27896. },
  27897. enumerable: true,
  27898. configurable: true
  27899. });
  27900. /**
  27901. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27902. */
  27903. Mesh.prototype.getTotalVertices = function () {
  27904. if (this._geometry === null || this._geometry === undefined) {
  27905. return 0;
  27906. }
  27907. return this._geometry.getTotalVertices();
  27908. };
  27909. /**
  27910. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27911. * 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.
  27912. * You can force the copy with forceCopy === true
  27913. * Returns null if the mesh has no geometry or no vertex buffer.
  27914. * Possible `kind` values :
  27915. * - BABYLON.VertexBuffer.PositionKind
  27916. * - BABYLON.VertexBuffer.UVKind
  27917. * - BABYLON.VertexBuffer.UV2Kind
  27918. * - BABYLON.VertexBuffer.UV3Kind
  27919. * - BABYLON.VertexBuffer.UV4Kind
  27920. * - BABYLON.VertexBuffer.UV5Kind
  27921. * - BABYLON.VertexBuffer.UV6Kind
  27922. * - BABYLON.VertexBuffer.ColorKind
  27923. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27924. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27925. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27926. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27927. */
  27928. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27929. if (!this._geometry) {
  27930. return null;
  27931. }
  27932. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27933. };
  27934. /**
  27935. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27936. * Returns `null` if the mesh has no geometry.
  27937. * Possible `kind` values :
  27938. * - BABYLON.VertexBuffer.PositionKind
  27939. * - BABYLON.VertexBuffer.UVKind
  27940. * - BABYLON.VertexBuffer.UV2Kind
  27941. * - BABYLON.VertexBuffer.UV3Kind
  27942. * - BABYLON.VertexBuffer.UV4Kind
  27943. * - BABYLON.VertexBuffer.UV5Kind
  27944. * - BABYLON.VertexBuffer.UV6Kind
  27945. * - BABYLON.VertexBuffer.ColorKind
  27946. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27947. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27948. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27949. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27950. */
  27951. Mesh.prototype.getVertexBuffer = function (kind) {
  27952. if (!this._geometry) {
  27953. return null;
  27954. }
  27955. return this._geometry.getVertexBuffer(kind);
  27956. };
  27957. /**
  27958. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  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.isVerticesDataPresent = function (kind) {
  27974. if (!this._geometry) {
  27975. if (this._delayInfo) {
  27976. return this._delayInfo.indexOf(kind) !== -1;
  27977. }
  27978. return false;
  27979. }
  27980. return this._geometry.isVerticesDataPresent(kind);
  27981. };
  27982. /**
  27983. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27984. * Possible `kind` values :
  27985. * - BABYLON.VertexBuffer.PositionKind
  27986. * - BABYLON.VertexBuffer.UVKind
  27987. * - BABYLON.VertexBuffer.UV2Kind
  27988. * - BABYLON.VertexBuffer.UV3Kind
  27989. * - BABYLON.VertexBuffer.UV4Kind
  27990. * - BABYLON.VertexBuffer.UV5Kind
  27991. * - BABYLON.VertexBuffer.UV6Kind
  27992. * - BABYLON.VertexBuffer.ColorKind
  27993. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27994. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27995. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27996. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27997. */
  27998. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27999. if (!this._geometry) {
  28000. if (this._delayInfo) {
  28001. return this._delayInfo.indexOf(kind) !== -1;
  28002. }
  28003. return false;
  28004. }
  28005. return this._geometry.isVertexBufferUpdatable(kind);
  28006. };
  28007. /**
  28008. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  28009. * Possible `kind` values :
  28010. * - BABYLON.VertexBuffer.PositionKind
  28011. * - BABYLON.VertexBuffer.UVKind
  28012. * - BABYLON.VertexBuffer.UV2Kind
  28013. * - BABYLON.VertexBuffer.UV3Kind
  28014. * - BABYLON.VertexBuffer.UV4Kind
  28015. * - BABYLON.VertexBuffer.UV5Kind
  28016. * - BABYLON.VertexBuffer.UV6Kind
  28017. * - BABYLON.VertexBuffer.ColorKind
  28018. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28019. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28020. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28021. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28022. */
  28023. Mesh.prototype.getVerticesDataKinds = function () {
  28024. if (!this._geometry) {
  28025. var result = new Array();
  28026. if (this._delayInfo) {
  28027. this._delayInfo.forEach(function (kind, index, array) {
  28028. result.push(kind);
  28029. });
  28030. }
  28031. return result;
  28032. }
  28033. return this._geometry.getVerticesDataKinds();
  28034. };
  28035. /**
  28036. * Returns a positive integer : the total number of indices in this mesh geometry.
  28037. * Returns zero if the mesh has no geometry.
  28038. */
  28039. Mesh.prototype.getTotalIndices = function () {
  28040. if (!this._geometry) {
  28041. return 0;
  28042. }
  28043. return this._geometry.getTotalIndices();
  28044. };
  28045. /**
  28046. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  28047. * 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.
  28048. * Returns an empty array if the mesh has no geometry.
  28049. */
  28050. Mesh.prototype.getIndices = function (copyWhenShared) {
  28051. if (!this._geometry) {
  28052. return [];
  28053. }
  28054. return this._geometry.getIndices(copyWhenShared);
  28055. };
  28056. Object.defineProperty(Mesh.prototype, "isBlocked", {
  28057. get: function () {
  28058. return this._masterMesh !== null && this._masterMesh !== undefined;
  28059. },
  28060. enumerable: true,
  28061. configurable: true
  28062. });
  28063. /**
  28064. * Determine if the current mesh is ready to be rendered
  28065. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  28066. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  28067. * @returns true if all associated assets are ready (material, textures, shaders)
  28068. */
  28069. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  28070. if (completeCheck === void 0) { completeCheck = false; }
  28071. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  28072. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28073. return false;
  28074. }
  28075. if (!_super.prototype.isReady.call(this, completeCheck)) {
  28076. return false;
  28077. }
  28078. if (!this.subMeshes || this.subMeshes.length === 0) {
  28079. return true;
  28080. }
  28081. if (!completeCheck) {
  28082. return true;
  28083. }
  28084. var engine = this.getEngine();
  28085. var scene = this.getScene();
  28086. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  28087. this.computeWorldMatrix();
  28088. var mat = this.material || scene.defaultMaterial;
  28089. if (mat) {
  28090. if (mat.storeEffectOnSubMeshes) {
  28091. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28092. var subMesh = _a[_i];
  28093. var effectiveMaterial = subMesh.getMaterial();
  28094. if (effectiveMaterial) {
  28095. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28096. return false;
  28097. }
  28098. }
  28099. }
  28100. }
  28101. else {
  28102. if (!mat.isReady(this, hardwareInstancedRendering)) {
  28103. return false;
  28104. }
  28105. }
  28106. }
  28107. // Shadows
  28108. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  28109. var light = _c[_b];
  28110. var generator = light.getShadowGenerator();
  28111. if (generator) {
  28112. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  28113. var subMesh = _e[_d];
  28114. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  28115. return false;
  28116. }
  28117. }
  28118. }
  28119. }
  28120. // LOD
  28121. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  28122. var lod = _g[_f];
  28123. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  28124. return false;
  28125. }
  28126. }
  28127. return true;
  28128. };
  28129. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  28130. /**
  28131. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  28132. * This property is pertinent only for updatable parametric shapes.
  28133. */
  28134. get: function () {
  28135. return this._areNormalsFrozen;
  28136. },
  28137. enumerable: true,
  28138. configurable: true
  28139. });
  28140. /**
  28141. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28142. * It has no effect at all on other shapes.
  28143. * It prevents the mesh normals from being recomputed on next `positions` array update.
  28144. * Returns the Mesh.
  28145. */
  28146. Mesh.prototype.freezeNormals = function () {
  28147. this._areNormalsFrozen = true;
  28148. return this;
  28149. };
  28150. /**
  28151. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28152. * It has no effect at all on other shapes.
  28153. * It reactivates the mesh normals computation if it was previously frozen.
  28154. * Returns the Mesh.
  28155. */
  28156. Mesh.prototype.unfreezeNormals = function () {
  28157. this._areNormalsFrozen = false;
  28158. return this;
  28159. };
  28160. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28161. /**
  28162. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28163. */
  28164. set: function (count) {
  28165. this._overridenInstanceCount = count;
  28166. },
  28167. enumerable: true,
  28168. configurable: true
  28169. });
  28170. // Methods
  28171. Mesh.prototype._preActivate = function () {
  28172. var sceneRenderId = this.getScene().getRenderId();
  28173. if (this._preActivateId === sceneRenderId) {
  28174. return this;
  28175. }
  28176. this._preActivateId = sceneRenderId;
  28177. this._visibleInstances = null;
  28178. return this;
  28179. };
  28180. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28181. if (this._visibleInstances) {
  28182. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28183. }
  28184. return this;
  28185. };
  28186. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28187. if (!this._visibleInstances) {
  28188. this._visibleInstances = {};
  28189. this._visibleInstances.defaultRenderId = renderId;
  28190. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28191. }
  28192. if (!this._visibleInstances[renderId]) {
  28193. this._visibleInstances[renderId] = new Array();
  28194. }
  28195. this._visibleInstances[renderId].push(instance);
  28196. return this;
  28197. };
  28198. /**
  28199. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28200. * This means the mesh underlying bounding box and sphere are recomputed.
  28201. * Returns the Mesh.
  28202. */
  28203. Mesh.prototype.refreshBoundingInfo = function () {
  28204. return this._refreshBoundingInfo(false);
  28205. };
  28206. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28207. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28208. return this;
  28209. }
  28210. var data = this._getPositionData(applySkeleton);
  28211. if (data) {
  28212. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28213. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28214. }
  28215. if (this.subMeshes) {
  28216. for (var index = 0; index < this.subMeshes.length; index++) {
  28217. this.subMeshes[index].refreshBoundingInfo();
  28218. }
  28219. }
  28220. this._updateBoundingInfo();
  28221. return this;
  28222. };
  28223. Mesh.prototype._getPositionData = function (applySkeleton) {
  28224. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28225. if (data && applySkeleton && this.skeleton) {
  28226. data = BABYLON.Tools.Slice(data);
  28227. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28228. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28229. if (matricesWeightsData && matricesIndicesData) {
  28230. var needExtras = this.numBoneInfluencers > 4;
  28231. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28232. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28233. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28234. var tempVector = BABYLON.Tmp.Vector3[0];
  28235. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28236. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28237. var matWeightIdx = 0;
  28238. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28239. finalMatrix.reset();
  28240. var inf;
  28241. var weight;
  28242. for (inf = 0; inf < 4; inf++) {
  28243. weight = matricesWeightsData[matWeightIdx + inf];
  28244. if (weight <= 0)
  28245. break;
  28246. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28247. finalMatrix.addToSelf(tempMatrix);
  28248. }
  28249. if (needExtras) {
  28250. for (inf = 0; inf < 4; inf++) {
  28251. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28252. if (weight <= 0)
  28253. break;
  28254. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28255. finalMatrix.addToSelf(tempMatrix);
  28256. }
  28257. }
  28258. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28259. tempVector.toArray(data, index);
  28260. }
  28261. }
  28262. }
  28263. return data;
  28264. };
  28265. Mesh.prototype._createGlobalSubMesh = function (force) {
  28266. var totalVertices = this.getTotalVertices();
  28267. if (!totalVertices || !this.getIndices()) {
  28268. return null;
  28269. }
  28270. // Check if we need to recreate the submeshes
  28271. if (this.subMeshes && this.subMeshes.length > 0) {
  28272. var ib = this.getIndices();
  28273. if (!ib) {
  28274. return null;
  28275. }
  28276. var totalIndices = ib.length;
  28277. var needToRecreate = false;
  28278. if (force) {
  28279. needToRecreate = true;
  28280. }
  28281. else {
  28282. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28283. var submesh = _a[_i];
  28284. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28285. needToRecreate = true;
  28286. break;
  28287. }
  28288. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28289. needToRecreate = true;
  28290. break;
  28291. }
  28292. }
  28293. }
  28294. if (!needToRecreate) {
  28295. return this.subMeshes[0];
  28296. }
  28297. }
  28298. this.releaseSubMeshes();
  28299. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28300. };
  28301. Mesh.prototype.subdivide = function (count) {
  28302. if (count < 1) {
  28303. return;
  28304. }
  28305. var totalIndices = this.getTotalIndices();
  28306. var subdivisionSize = (totalIndices / count) | 0;
  28307. var offset = 0;
  28308. // Ensure that subdivisionSize is a multiple of 3
  28309. while (subdivisionSize % 3 !== 0) {
  28310. subdivisionSize++;
  28311. }
  28312. this.releaseSubMeshes();
  28313. for (var index = 0; index < count; index++) {
  28314. if (offset >= totalIndices) {
  28315. break;
  28316. }
  28317. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28318. offset += subdivisionSize;
  28319. }
  28320. this.synchronizeInstances();
  28321. };
  28322. /**
  28323. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28324. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28325. * The `data` are either a numeric array either a Float32Array.
  28326. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28327. * 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).
  28328. * Note that a new underlying VertexBuffer object is created each call.
  28329. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28330. *
  28331. * Possible `kind` values :
  28332. * - BABYLON.VertexBuffer.PositionKind
  28333. * - BABYLON.VertexBuffer.UVKind
  28334. * - BABYLON.VertexBuffer.UV2Kind
  28335. * - BABYLON.VertexBuffer.UV3Kind
  28336. * - BABYLON.VertexBuffer.UV4Kind
  28337. * - BABYLON.VertexBuffer.UV5Kind
  28338. * - BABYLON.VertexBuffer.UV6Kind
  28339. * - BABYLON.VertexBuffer.ColorKind
  28340. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28341. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28342. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28343. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28344. *
  28345. * Returns the Mesh.
  28346. */
  28347. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28348. if (updatable === void 0) { updatable = false; }
  28349. if (!this._geometry) {
  28350. var vertexData = new BABYLON.VertexData();
  28351. vertexData.set(data, kind);
  28352. var scene = this.getScene();
  28353. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28354. }
  28355. else {
  28356. this._geometry.setVerticesData(kind, data, updatable, stride);
  28357. }
  28358. return this;
  28359. };
  28360. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28361. if (updatable === void 0) { updatable = true; }
  28362. var vb = this.getVertexBuffer(kind);
  28363. if (!vb || vb.isUpdatable() === updatable) {
  28364. return;
  28365. }
  28366. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28367. };
  28368. /**
  28369. * Sets the mesh VertexBuffer.
  28370. * Returns the Mesh.
  28371. */
  28372. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28373. if (!this._geometry) {
  28374. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28375. }
  28376. this._geometry.setVerticesBuffer(buffer);
  28377. return this;
  28378. };
  28379. /**
  28380. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28381. * If the mesh has no geometry, it is simply returned as it is.
  28382. * The `data` are either a numeric array either a Float32Array.
  28383. * No new underlying VertexBuffer object is created.
  28384. * 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.
  28385. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28386. *
  28387. * Possible `kind` values :
  28388. * - BABYLON.VertexBuffer.PositionKind
  28389. * - BABYLON.VertexBuffer.UVKind
  28390. * - BABYLON.VertexBuffer.UV2Kind
  28391. * - BABYLON.VertexBuffer.UV3Kind
  28392. * - BABYLON.VertexBuffer.UV4Kind
  28393. * - BABYLON.VertexBuffer.UV5Kind
  28394. * - BABYLON.VertexBuffer.UV6Kind
  28395. * - BABYLON.VertexBuffer.ColorKind
  28396. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28397. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28398. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28399. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28400. *
  28401. * Returns the Mesh.
  28402. */
  28403. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28404. if (!this._geometry) {
  28405. return this;
  28406. }
  28407. if (!makeItUnique) {
  28408. this._geometry.updateVerticesData(kind, data, updateExtends);
  28409. }
  28410. else {
  28411. this.makeGeometryUnique();
  28412. this.updateVerticesData(kind, data, updateExtends, false);
  28413. }
  28414. return this;
  28415. };
  28416. /**
  28417. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28418. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28419. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28420. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28421. * Returns the Mesh.
  28422. */
  28423. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28424. if (computeNormals === void 0) { computeNormals = true; }
  28425. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28426. if (!positions) {
  28427. return this;
  28428. }
  28429. positionFunction(positions);
  28430. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28431. if (computeNormals) {
  28432. var indices = this.getIndices();
  28433. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28434. if (!normals) {
  28435. return this;
  28436. }
  28437. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28438. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28439. }
  28440. return this;
  28441. };
  28442. /**
  28443. * Creates a un-shared specific occurence of the geometry for the mesh.
  28444. * Returns the Mesh.
  28445. */
  28446. Mesh.prototype.makeGeometryUnique = function () {
  28447. if (!this._geometry) {
  28448. return this;
  28449. }
  28450. var oldGeometry = this._geometry;
  28451. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28452. oldGeometry.releaseForMesh(this, true);
  28453. geometry.applyToMesh(this);
  28454. return this;
  28455. };
  28456. /**
  28457. * Sets the mesh indices.
  28458. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28459. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28460. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28461. * This method creates a new index buffer each call.
  28462. * Returns the Mesh.
  28463. */
  28464. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28465. if (totalVertices === void 0) { totalVertices = null; }
  28466. if (updatable === void 0) { updatable = false; }
  28467. if (!this._geometry) {
  28468. var vertexData = new BABYLON.VertexData();
  28469. vertexData.indices = indices;
  28470. var scene = this.getScene();
  28471. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28472. }
  28473. else {
  28474. this._geometry.setIndices(indices, totalVertices, updatable);
  28475. }
  28476. return this;
  28477. };
  28478. /**
  28479. * Update the current index buffer
  28480. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28481. * Returns the Mesh.
  28482. */
  28483. Mesh.prototype.updateIndices = function (indices, offset) {
  28484. if (!this._geometry) {
  28485. return this;
  28486. }
  28487. this._geometry.updateIndices(indices, offset);
  28488. return this;
  28489. };
  28490. /**
  28491. * Invert the geometry to move from a right handed system to a left handed one.
  28492. * Returns the Mesh.
  28493. */
  28494. Mesh.prototype.toLeftHanded = function () {
  28495. if (!this._geometry) {
  28496. return this;
  28497. }
  28498. this._geometry.toLeftHanded();
  28499. return this;
  28500. };
  28501. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28502. if (!this._geometry) {
  28503. return this;
  28504. }
  28505. var engine = this.getScene().getEngine();
  28506. // Wireframe
  28507. var indexToBind;
  28508. if (this._unIndexed) {
  28509. indexToBind = null;
  28510. }
  28511. else {
  28512. switch (fillMode) {
  28513. case BABYLON.Material.PointFillMode:
  28514. indexToBind = null;
  28515. break;
  28516. case BABYLON.Material.WireFrameFillMode:
  28517. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28518. break;
  28519. default:
  28520. case BABYLON.Material.TriangleFillMode:
  28521. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28522. break;
  28523. }
  28524. }
  28525. // VBOs
  28526. this._geometry._bind(effect, indexToBind);
  28527. return this;
  28528. };
  28529. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28530. if (alternate === void 0) { alternate = false; }
  28531. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28532. return this;
  28533. }
  28534. this.onBeforeDrawObservable.notifyObservers(this);
  28535. var scene = this.getScene();
  28536. var engine = scene.getEngine();
  28537. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28538. // or triangles as points
  28539. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28540. }
  28541. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28542. // Triangles as wireframe
  28543. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28544. }
  28545. else {
  28546. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28547. }
  28548. if (scene._isAlternateRenderingEnabled && !alternate) {
  28549. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28550. if (!effect || !scene.activeCamera) {
  28551. return this;
  28552. }
  28553. scene._switchToAlternateCameraConfiguration(true);
  28554. this._effectiveMaterial.bindView(effect);
  28555. this._effectiveMaterial.bindViewProjection(effect);
  28556. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28557. this._draw(subMesh, fillMode, instancesCount, true);
  28558. engine.setViewport(scene.activeCamera.viewport);
  28559. scene._switchToAlternateCameraConfiguration(false);
  28560. this._effectiveMaterial.bindView(effect);
  28561. this._effectiveMaterial.bindViewProjection(effect);
  28562. }
  28563. return this;
  28564. };
  28565. /**
  28566. * Registers for this mesh a javascript function called just before the rendering process.
  28567. * This function is passed the current mesh.
  28568. * Return the Mesh.
  28569. */
  28570. Mesh.prototype.registerBeforeRender = function (func) {
  28571. this.onBeforeRenderObservable.add(func);
  28572. return this;
  28573. };
  28574. /**
  28575. * Disposes a previously registered javascript function called before the rendering.
  28576. * This function is passed the current mesh.
  28577. * Returns the Mesh.
  28578. */
  28579. Mesh.prototype.unregisterBeforeRender = function (func) {
  28580. this.onBeforeRenderObservable.removeCallback(func);
  28581. return this;
  28582. };
  28583. /**
  28584. * Registers for this mesh a javascript function called just after the rendering is complete.
  28585. * This function is passed the current mesh.
  28586. * Returns the Mesh.
  28587. */
  28588. Mesh.prototype.registerAfterRender = function (func) {
  28589. this.onAfterRenderObservable.add(func);
  28590. return this;
  28591. };
  28592. /**
  28593. * Disposes a previously registered javascript function called after the rendering.
  28594. * This function is passed the current mesh.
  28595. * Return the Mesh.
  28596. */
  28597. Mesh.prototype.unregisterAfterRender = function (func) {
  28598. this.onAfterRenderObservable.removeCallback(func);
  28599. return this;
  28600. };
  28601. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28602. var scene = this.getScene();
  28603. this._batchCache.mustReturn = false;
  28604. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28605. this._batchCache.visibleInstances[subMeshId] = null;
  28606. if (this._visibleInstances) {
  28607. var currentRenderId = scene.getRenderId();
  28608. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28609. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28610. var selfRenderId = this._renderId;
  28611. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28612. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28613. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28614. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28615. }
  28616. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28617. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28618. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28619. this._batchCache.mustReturn = true;
  28620. return this._batchCache;
  28621. }
  28622. if (currentRenderId !== selfRenderId) {
  28623. this._batchCache.renderSelf[subMeshId] = false;
  28624. }
  28625. }
  28626. this._renderIdForInstances[subMeshId] = currentRenderId;
  28627. }
  28628. return this._batchCache;
  28629. };
  28630. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28631. var visibleInstances = batch.visibleInstances[subMesh._id];
  28632. if (!visibleInstances) {
  28633. return this;
  28634. }
  28635. var matricesCount = visibleInstances.length + 1;
  28636. var bufferSize = matricesCount * 16 * 4;
  28637. var currentInstancesBufferSize = this._instancesBufferSize;
  28638. var instancesBuffer = this._instancesBuffer;
  28639. while (this._instancesBufferSize < bufferSize) {
  28640. this._instancesBufferSize *= 2;
  28641. }
  28642. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28643. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28644. }
  28645. var offset = 0;
  28646. var instancesCount = 0;
  28647. var world = this.getWorldMatrix();
  28648. if (batch.renderSelf[subMesh._id]) {
  28649. world.copyToArray(this._instancesData, offset);
  28650. offset += 16;
  28651. instancesCount++;
  28652. }
  28653. if (visibleInstances) {
  28654. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28655. var instance = visibleInstances[instanceIndex];
  28656. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28657. offset += 16;
  28658. instancesCount++;
  28659. }
  28660. }
  28661. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28662. if (instancesBuffer) {
  28663. instancesBuffer.dispose();
  28664. }
  28665. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28666. this._instancesBuffer = instancesBuffer;
  28667. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28668. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28669. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28670. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28671. }
  28672. else {
  28673. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28674. }
  28675. this._bind(subMesh, effect, fillMode);
  28676. this._draw(subMesh, fillMode, instancesCount);
  28677. engine.unbindInstanceAttributes();
  28678. return this;
  28679. };
  28680. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28681. var scene = this.getScene();
  28682. var engine = scene.getEngine();
  28683. if (hardwareInstancedRendering) {
  28684. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28685. }
  28686. else {
  28687. if (batch.renderSelf[subMesh._id]) {
  28688. // Draw
  28689. if (onBeforeDraw) {
  28690. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28691. }
  28692. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28693. }
  28694. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28695. if (visibleInstancesForSubMesh) {
  28696. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28697. var instance = visibleInstancesForSubMesh[instanceIndex];
  28698. // World
  28699. var world = instance.getWorldMatrix();
  28700. if (onBeforeDraw) {
  28701. onBeforeDraw(true, world, effectiveMaterial);
  28702. }
  28703. // Draw
  28704. this._draw(subMesh, fillMode);
  28705. }
  28706. }
  28707. }
  28708. return this;
  28709. };
  28710. /**
  28711. * Triggers the draw call for the mesh.
  28712. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28713. * Returns the Mesh.
  28714. */
  28715. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28716. this.checkOcclusionQuery();
  28717. if (this._isOccluded) {
  28718. return this;
  28719. }
  28720. var scene = this.getScene();
  28721. // Managing instances
  28722. var batch = this._getInstancesRenderList(subMesh._id);
  28723. if (batch.mustReturn) {
  28724. return this;
  28725. }
  28726. // Checking geometry state
  28727. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28728. return this;
  28729. }
  28730. this.onBeforeRenderObservable.notifyObservers(this);
  28731. var engine = scene.getEngine();
  28732. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28733. // Material
  28734. var material = subMesh.getMaterial();
  28735. if (!material) {
  28736. return this;
  28737. }
  28738. this._effectiveMaterial = material;
  28739. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28740. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28741. return this;
  28742. }
  28743. }
  28744. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28745. return this;
  28746. }
  28747. // Alpha mode
  28748. if (enableAlphaMode) {
  28749. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28750. }
  28751. // Outline - step 1
  28752. var savedDepthWrite = engine.getDepthWrite();
  28753. if (this.renderOutline) {
  28754. engine.setDepthWrite(false);
  28755. scene.getOutlineRenderer().render(subMesh, batch);
  28756. engine.setDepthWrite(savedDepthWrite);
  28757. }
  28758. var effect;
  28759. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28760. effect = subMesh.effect;
  28761. }
  28762. else {
  28763. effect = this._effectiveMaterial.getEffect();
  28764. }
  28765. if (!effect) {
  28766. return this;
  28767. }
  28768. var sideOrientation = this.overrideMaterialSideOrientation;
  28769. if (sideOrientation == null) {
  28770. sideOrientation = this._effectiveMaterial.sideOrientation;
  28771. if (this._getWorldMatrixDeterminant() < 0) {
  28772. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28773. }
  28774. }
  28775. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28776. if (this._effectiveMaterial.forceDepthWrite) {
  28777. engine.setDepthWrite(true);
  28778. }
  28779. // Bind
  28780. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28781. if (!hardwareInstancedRendering) {
  28782. this._bind(subMesh, effect, fillMode);
  28783. }
  28784. var world = this.getWorldMatrix();
  28785. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28786. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28787. }
  28788. else {
  28789. this._effectiveMaterial.bind(world, this);
  28790. }
  28791. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28792. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28793. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28794. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28795. }
  28796. // Draw
  28797. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28798. // Unbind
  28799. this._effectiveMaterial.unbind();
  28800. // Outline - step 2
  28801. if (this.renderOutline && savedDepthWrite) {
  28802. engine.setDepthWrite(true);
  28803. engine.setColorWrite(false);
  28804. scene.getOutlineRenderer().render(subMesh, batch);
  28805. engine.setColorWrite(true);
  28806. }
  28807. // Overlay
  28808. if (this.renderOverlay) {
  28809. var currentMode = engine.getAlphaMode();
  28810. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28811. scene.getOutlineRenderer().render(subMesh, batch, true);
  28812. engine.setAlphaMode(currentMode);
  28813. }
  28814. this.onAfterRenderObservable.notifyObservers(this);
  28815. return this;
  28816. };
  28817. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28818. if (isInstance && effectiveMaterial) {
  28819. effectiveMaterial.bindOnlyWorldMatrix(world);
  28820. }
  28821. };
  28822. /**
  28823. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28824. */
  28825. Mesh.prototype.getEmittedParticleSystems = function () {
  28826. var results = new Array();
  28827. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28828. var particleSystem = this.getScene().particleSystems[index];
  28829. if (particleSystem.emitter === this) {
  28830. results.push(particleSystem);
  28831. }
  28832. }
  28833. return results;
  28834. };
  28835. /**
  28836. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28837. */
  28838. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28839. var results = new Array();
  28840. var descendants = this.getDescendants();
  28841. descendants.push(this);
  28842. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28843. var particleSystem = this.getScene().particleSystems[index];
  28844. var emitter = particleSystem.emitter;
  28845. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28846. results.push(particleSystem);
  28847. }
  28848. }
  28849. return results;
  28850. };
  28851. Mesh.prototype._checkDelayState = function () {
  28852. var scene = this.getScene();
  28853. if (this._geometry) {
  28854. this._geometry.load(scene);
  28855. }
  28856. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28857. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28858. this._queueLoad(scene);
  28859. }
  28860. return this;
  28861. };
  28862. Mesh.prototype._queueLoad = function (scene) {
  28863. var _this = this;
  28864. scene._addPendingData(this);
  28865. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28866. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28867. if (data instanceof ArrayBuffer) {
  28868. _this._delayLoadingFunction(data, _this);
  28869. }
  28870. else {
  28871. _this._delayLoadingFunction(JSON.parse(data), _this);
  28872. }
  28873. _this.instances.forEach(function (instance) {
  28874. instance._syncSubMeshes();
  28875. });
  28876. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28877. scene._removePendingData(_this);
  28878. }, function () { }, scene.database, getBinaryData);
  28879. return this;
  28880. };
  28881. /**
  28882. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28883. */
  28884. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28885. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28886. return false;
  28887. }
  28888. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28889. return false;
  28890. }
  28891. this._checkDelayState();
  28892. return true;
  28893. };
  28894. /**
  28895. * Sets the mesh material by the material or multiMaterial `id` property.
  28896. * The material `id` is a string identifying the material or the multiMaterial.
  28897. * This method returns the Mesh.
  28898. */
  28899. Mesh.prototype.setMaterialByID = function (id) {
  28900. var materials = this.getScene().materials;
  28901. var index;
  28902. for (index = materials.length - 1; index > -1; index--) {
  28903. if (materials[index].id === id) {
  28904. this.material = materials[index];
  28905. return this;
  28906. }
  28907. }
  28908. // Multi
  28909. var multiMaterials = this.getScene().multiMaterials;
  28910. for (index = multiMaterials.length - 1; index > -1; index--) {
  28911. if (multiMaterials[index].id === id) {
  28912. this.material = multiMaterials[index];
  28913. return this;
  28914. }
  28915. }
  28916. return this;
  28917. };
  28918. /**
  28919. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28920. */
  28921. Mesh.prototype.getAnimatables = function () {
  28922. var results = new Array();
  28923. if (this.material) {
  28924. results.push(this.material);
  28925. }
  28926. if (this.skeleton) {
  28927. results.push(this.skeleton);
  28928. }
  28929. return results;
  28930. };
  28931. /**
  28932. * Modifies the mesh geometry according to the passed transformation matrix.
  28933. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28934. * The mesh normals are modified accordingly the same transformation.
  28935. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28936. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28937. * Returns the Mesh.
  28938. */
  28939. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28940. // Position
  28941. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28942. return this;
  28943. }
  28944. var submeshes = this.subMeshes.splice(0);
  28945. this._resetPointsArrayCache();
  28946. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28947. var temp = new Array();
  28948. var index;
  28949. for (index = 0; index < data.length; index += 3) {
  28950. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28951. }
  28952. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28953. // Normals
  28954. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28955. return this;
  28956. }
  28957. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28958. temp = [];
  28959. for (index = 0; index < data.length; index += 3) {
  28960. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28961. }
  28962. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28963. // flip faces?
  28964. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28965. this.flipFaces();
  28966. }
  28967. // Restore submeshes
  28968. this.releaseSubMeshes();
  28969. this.subMeshes = submeshes;
  28970. return this;
  28971. };
  28972. /**
  28973. * Modifies the mesh geometry according to its own current World Matrix.
  28974. * The mesh World Matrix is then reset.
  28975. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28976. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28977. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28978. * Returns the Mesh.
  28979. */
  28980. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28981. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28982. this.scaling.copyFromFloats(1, 1, 1);
  28983. this.position.copyFromFloats(0, 0, 0);
  28984. this.rotation.copyFromFloats(0, 0, 0);
  28985. //only if quaternion is already set
  28986. if (this.rotationQuaternion) {
  28987. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28988. }
  28989. this._worldMatrix = BABYLON.Matrix.Identity();
  28990. return this;
  28991. };
  28992. Object.defineProperty(Mesh.prototype, "_positions", {
  28993. // Cache
  28994. get: function () {
  28995. if (this._geometry) {
  28996. return this._geometry._positions;
  28997. }
  28998. return null;
  28999. },
  29000. enumerable: true,
  29001. configurable: true
  29002. });
  29003. Mesh.prototype._resetPointsArrayCache = function () {
  29004. if (this._geometry) {
  29005. this._geometry._resetPointsArrayCache();
  29006. }
  29007. return this;
  29008. };
  29009. Mesh.prototype._generatePointsArray = function () {
  29010. if (this._geometry) {
  29011. return this._geometry._generatePointsArray();
  29012. }
  29013. return false;
  29014. };
  29015. /**
  29016. * Returns a new Mesh object generated from the current mesh properties.
  29017. * This method must not get confused with createInstance().
  29018. * The parameter `name` is a string, the name given to the new mesh.
  29019. * The optional parameter `newParent` can be any Node object (default `null`).
  29020. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  29021. * 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.
  29022. */
  29023. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  29024. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  29025. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  29026. };
  29027. /**
  29028. * Releases resources associated with this mesh.
  29029. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  29030. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  29031. */
  29032. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  29033. var _this = this;
  29034. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  29035. this.morphTargetManager = null;
  29036. if (this._geometry) {
  29037. this._geometry.releaseForMesh(this, true);
  29038. }
  29039. // Sources
  29040. var meshes = this.getScene().meshes;
  29041. meshes.forEach(function (abstractMesh) {
  29042. var mesh = abstractMesh;
  29043. if (mesh._source && mesh._source === _this) {
  29044. mesh._source = null;
  29045. }
  29046. });
  29047. this._source = null;
  29048. // Instances
  29049. if (this._instancesBuffer) {
  29050. this._instancesBuffer.dispose();
  29051. this._instancesBuffer = null;
  29052. }
  29053. while (this.instances.length) {
  29054. this.instances[0].dispose();
  29055. }
  29056. // Effect layers.
  29057. var effectLayers = this.getScene().effectLayers;
  29058. for (var i = 0; i < effectLayers.length; i++) {
  29059. var effectLayer = effectLayers[i];
  29060. if (effectLayer) {
  29061. effectLayer._disposeMesh(this);
  29062. }
  29063. }
  29064. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  29065. };
  29066. /**
  29067. * Modifies the mesh geometry according to a displacement map.
  29068. * 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.
  29069. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29070. * This method returns nothing.
  29071. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  29072. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29073. * 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.
  29074. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29075. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29076. *
  29077. * Returns the Mesh.
  29078. */
  29079. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  29080. var _this = this;
  29081. var scene = this.getScene();
  29082. var onload = function (img) {
  29083. // Getting height map data
  29084. var canvas = document.createElement("canvas");
  29085. var context = canvas.getContext("2d");
  29086. var heightMapWidth = img.width;
  29087. var heightMapHeight = img.height;
  29088. canvas.width = heightMapWidth;
  29089. canvas.height = heightMapHeight;
  29090. context.drawImage(img, 0, 0);
  29091. // Create VertexData from map data
  29092. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  29093. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  29094. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  29095. //execute success callback, if set
  29096. if (onSuccess) {
  29097. onSuccess(_this);
  29098. }
  29099. };
  29100. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29101. return this;
  29102. };
  29103. /**
  29104. * Modifies the mesh geometry according to a displacementMap buffer.
  29105. * 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.
  29106. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29107. * This method returns nothing.
  29108. * 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.
  29109. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  29110. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29111. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29112. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29113. *
  29114. * Returns the Mesh.
  29115. */
  29116. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  29117. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  29118. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  29119. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29120. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  29121. return this;
  29122. }
  29123. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29124. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29125. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29126. var position = BABYLON.Vector3.Zero();
  29127. var normal = BABYLON.Vector3.Zero();
  29128. var uv = BABYLON.Vector2.Zero();
  29129. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  29130. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  29131. for (var index = 0; index < positions.length; index += 3) {
  29132. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  29133. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  29134. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  29135. // Compute height
  29136. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  29137. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  29138. var pos = (u + v * heightMapWidth) * 4;
  29139. var r = buffer[pos] / 255.0;
  29140. var g = buffer[pos + 1] / 255.0;
  29141. var b = buffer[pos + 2] / 255.0;
  29142. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29143. normal.normalize();
  29144. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  29145. position = position.add(normal);
  29146. position.toArray(positions, index);
  29147. }
  29148. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  29149. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  29150. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  29151. return this;
  29152. };
  29153. /**
  29154. * Modify the mesh to get a flat shading rendering.
  29155. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  29156. * This method returns the Mesh.
  29157. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  29158. */
  29159. Mesh.prototype.convertToFlatShadedMesh = function () {
  29160. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29161. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29162. var kinds = this.getVerticesDataKinds();
  29163. var vbs = {};
  29164. var data = {};
  29165. var newdata = {};
  29166. var updatableNormals = false;
  29167. var kindIndex;
  29168. var kind;
  29169. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29170. kind = kinds[kindIndex];
  29171. var vertexBuffer = this.getVertexBuffer(kind);
  29172. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29173. updatableNormals = vertexBuffer.isUpdatable();
  29174. kinds.splice(kindIndex, 1);
  29175. kindIndex--;
  29176. continue;
  29177. }
  29178. vbs[kind] = vertexBuffer;
  29179. data[kind] = vbs[kind].getData();
  29180. newdata[kind] = [];
  29181. }
  29182. // Save previous submeshes
  29183. var previousSubmeshes = this.subMeshes.slice(0);
  29184. var indices = this.getIndices();
  29185. var totalIndices = this.getTotalIndices();
  29186. // Generating unique vertices per face
  29187. var index;
  29188. for (index = 0; index < totalIndices; index++) {
  29189. var vertexIndex = indices[index];
  29190. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29191. kind = kinds[kindIndex];
  29192. var stride = vbs[kind].getStrideSize();
  29193. for (var offset = 0; offset < stride; offset++) {
  29194. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29195. }
  29196. }
  29197. }
  29198. // Updating faces & normal
  29199. var normals = [];
  29200. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29201. for (index = 0; index < totalIndices; index += 3) {
  29202. indices[index] = index;
  29203. indices[index + 1] = index + 1;
  29204. indices[index + 2] = index + 2;
  29205. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29206. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29207. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29208. var p1p2 = p1.subtract(p2);
  29209. var p3p2 = p3.subtract(p2);
  29210. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29211. // Store same normals for every vertex
  29212. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29213. normals.push(normal.x);
  29214. normals.push(normal.y);
  29215. normals.push(normal.z);
  29216. }
  29217. }
  29218. this.setIndices(indices);
  29219. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29220. // Updating vertex buffers
  29221. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29222. kind = kinds[kindIndex];
  29223. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29224. }
  29225. // Updating submeshes
  29226. this.releaseSubMeshes();
  29227. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29228. var previousOne = previousSubmeshes[submeshIndex];
  29229. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29230. }
  29231. this.synchronizeInstances();
  29232. return this;
  29233. };
  29234. /**
  29235. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29236. * In other words, more vertices, no more indices and a single bigger VBO.
  29237. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29238. * Returns the Mesh.
  29239. */
  29240. Mesh.prototype.convertToUnIndexedMesh = function () {
  29241. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29242. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29243. var kinds = this.getVerticesDataKinds();
  29244. var vbs = {};
  29245. var data = {};
  29246. var newdata = {};
  29247. var kindIndex;
  29248. var kind;
  29249. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29250. kind = kinds[kindIndex];
  29251. var vertexBuffer = this.getVertexBuffer(kind);
  29252. vbs[kind] = vertexBuffer;
  29253. data[kind] = vbs[kind].getData();
  29254. newdata[kind] = [];
  29255. }
  29256. // Save previous submeshes
  29257. var previousSubmeshes = this.subMeshes.slice(0);
  29258. var indices = this.getIndices();
  29259. var totalIndices = this.getTotalIndices();
  29260. // Generating unique vertices per face
  29261. var index;
  29262. for (index = 0; index < totalIndices; index++) {
  29263. var vertexIndex = indices[index];
  29264. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29265. kind = kinds[kindIndex];
  29266. var stride = vbs[kind].getStrideSize();
  29267. for (var offset = 0; offset < stride; offset++) {
  29268. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29269. }
  29270. }
  29271. }
  29272. // Updating indices
  29273. for (index = 0; index < totalIndices; index += 3) {
  29274. indices[index] = index;
  29275. indices[index + 1] = index + 1;
  29276. indices[index + 2] = index + 2;
  29277. }
  29278. this.setIndices(indices);
  29279. // Updating vertex buffers
  29280. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29281. kind = kinds[kindIndex];
  29282. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29283. }
  29284. // Updating submeshes
  29285. this.releaseSubMeshes();
  29286. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29287. var previousOne = previousSubmeshes[submeshIndex];
  29288. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29289. }
  29290. this._unIndexed = true;
  29291. this.synchronizeInstances();
  29292. return this;
  29293. };
  29294. /**
  29295. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29296. * This method returns the Mesh.
  29297. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29298. */
  29299. Mesh.prototype.flipFaces = function (flipNormals) {
  29300. if (flipNormals === void 0) { flipNormals = false; }
  29301. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29302. var i;
  29303. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29304. for (i = 0; i < vertex_data.normals.length; i++) {
  29305. vertex_data.normals[i] *= -1;
  29306. }
  29307. }
  29308. if (vertex_data.indices) {
  29309. var temp;
  29310. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29311. // reassign indices
  29312. temp = vertex_data.indices[i + 1];
  29313. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29314. vertex_data.indices[i + 2] = temp;
  29315. }
  29316. }
  29317. vertex_data.applyToMesh(this);
  29318. return this;
  29319. };
  29320. // Instances
  29321. /**
  29322. * Creates a new InstancedMesh object from the mesh model.
  29323. * An instance shares the same properties and the same material than its model.
  29324. * Only these properties of each instance can then be set individually :
  29325. * - position
  29326. * - rotation
  29327. * - rotationQuaternion
  29328. * - setPivotMatrix
  29329. * - scaling
  29330. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29331. * Warning : this method is not supported for Line mesh and LineSystem
  29332. */
  29333. Mesh.prototype.createInstance = function (name) {
  29334. return new BABYLON.InstancedMesh(name, this);
  29335. };
  29336. /**
  29337. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29338. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29339. * This method returns the Mesh.
  29340. */
  29341. Mesh.prototype.synchronizeInstances = function () {
  29342. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29343. var instance = this.instances[instanceIndex];
  29344. instance._syncSubMeshes();
  29345. }
  29346. return this;
  29347. };
  29348. /**
  29349. * Simplify the mesh according to the given array of settings.
  29350. * Function will return immediately and will simplify async. It returns the Mesh.
  29351. * @param settings a collection of simplification settings.
  29352. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29353. * @param type the type of simplification to run.
  29354. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29355. */
  29356. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29357. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29358. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29359. this.getScene().simplificationQueue.addTask({
  29360. settings: settings,
  29361. parallelProcessing: parallelProcessing,
  29362. mesh: this,
  29363. simplificationType: simplificationType,
  29364. successCallback: successCallback
  29365. });
  29366. return this;
  29367. };
  29368. /**
  29369. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29370. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29371. * This should be used together with the simplification to avoid disappearing triangles.
  29372. * Returns the Mesh.
  29373. * @param successCallback an optional success callback to be called after the optimization finished.
  29374. */
  29375. Mesh.prototype.optimizeIndices = function (successCallback) {
  29376. var _this = this;
  29377. var indices = this.getIndices();
  29378. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29379. if (!positions || !indices) {
  29380. return this;
  29381. }
  29382. var vectorPositions = new Array();
  29383. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29384. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29385. }
  29386. var dupes = new Array();
  29387. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29388. var realPos = vectorPositions.length - 1 - iteration;
  29389. var testedPosition = vectorPositions[realPos];
  29390. for (var j = 0; j < realPos; ++j) {
  29391. var againstPosition = vectorPositions[j];
  29392. if (testedPosition.equals(againstPosition)) {
  29393. dupes[realPos] = j;
  29394. break;
  29395. }
  29396. }
  29397. }, function () {
  29398. for (var i = 0; i < indices.length; ++i) {
  29399. indices[i] = dupes[indices[i]] || indices[i];
  29400. }
  29401. //indices are now reordered
  29402. var originalSubMeshes = _this.subMeshes.slice(0);
  29403. _this.setIndices(indices);
  29404. _this.subMeshes = originalSubMeshes;
  29405. if (successCallback) {
  29406. successCallback(_this);
  29407. }
  29408. });
  29409. return this;
  29410. };
  29411. Mesh.prototype.serialize = function (serializationObject) {
  29412. serializationObject.name = this.name;
  29413. serializationObject.id = this.id;
  29414. serializationObject.type = this.getClassName();
  29415. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29416. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29417. }
  29418. serializationObject.position = this.position.asArray();
  29419. if (this.rotationQuaternion) {
  29420. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29421. }
  29422. else if (this.rotation) {
  29423. serializationObject.rotation = this.rotation.asArray();
  29424. }
  29425. serializationObject.scaling = this.scaling.asArray();
  29426. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29427. serializationObject.isEnabled = this.isEnabled(false);
  29428. serializationObject.isVisible = this.isVisible;
  29429. serializationObject.infiniteDistance = this.infiniteDistance;
  29430. serializationObject.pickable = this.isPickable;
  29431. serializationObject.receiveShadows = this.receiveShadows;
  29432. serializationObject.billboardMode = this.billboardMode;
  29433. serializationObject.visibility = this.visibility;
  29434. serializationObject.checkCollisions = this.checkCollisions;
  29435. serializationObject.isBlocker = this.isBlocker;
  29436. // Parent
  29437. if (this.parent) {
  29438. serializationObject.parentId = this.parent.id;
  29439. }
  29440. // Geometry
  29441. serializationObject.isUnIndexed = this.isUnIndexed;
  29442. var geometry = this._geometry;
  29443. if (geometry) {
  29444. var geometryId = geometry.id;
  29445. serializationObject.geometryId = geometryId;
  29446. // SubMeshes
  29447. serializationObject.subMeshes = [];
  29448. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29449. var subMesh = this.subMeshes[subIndex];
  29450. serializationObject.subMeshes.push({
  29451. materialIndex: subMesh.materialIndex,
  29452. verticesStart: subMesh.verticesStart,
  29453. verticesCount: subMesh.verticesCount,
  29454. indexStart: subMesh.indexStart,
  29455. indexCount: subMesh.indexCount
  29456. });
  29457. }
  29458. }
  29459. // Material
  29460. if (this.material) {
  29461. serializationObject.materialId = this.material.id;
  29462. }
  29463. else {
  29464. this.material = null;
  29465. }
  29466. // Morph targets
  29467. if (this.morphTargetManager) {
  29468. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29469. }
  29470. // Skeleton
  29471. if (this.skeleton) {
  29472. serializationObject.skeletonId = this.skeleton.id;
  29473. }
  29474. // Physics
  29475. //TODO implement correct serialization for physics impostors.
  29476. var impostor = this.getPhysicsImpostor();
  29477. if (impostor) {
  29478. serializationObject.physicsMass = impostor.getParam("mass");
  29479. serializationObject.physicsFriction = impostor.getParam("friction");
  29480. serializationObject.physicsRestitution = impostor.getParam("mass");
  29481. serializationObject.physicsImpostor = impostor.type;
  29482. }
  29483. // Metadata
  29484. if (this.metadata) {
  29485. serializationObject.metadata = this.metadata;
  29486. }
  29487. // Instances
  29488. serializationObject.instances = [];
  29489. for (var index = 0; index < this.instances.length; index++) {
  29490. var instance = this.instances[index];
  29491. var serializationInstance = {
  29492. name: instance.name,
  29493. id: instance.id,
  29494. position: instance.position.asArray(),
  29495. scaling: instance.scaling.asArray()
  29496. };
  29497. if (instance.rotationQuaternion) {
  29498. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29499. }
  29500. else if (instance.rotation) {
  29501. serializationInstance.rotation = instance.rotation.asArray();
  29502. }
  29503. serializationObject.instances.push(serializationInstance);
  29504. // Animations
  29505. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29506. serializationInstance.ranges = instance.serializeAnimationRanges();
  29507. }
  29508. //
  29509. // Animations
  29510. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29511. serializationObject.ranges = this.serializeAnimationRanges();
  29512. // Layer mask
  29513. serializationObject.layerMask = this.layerMask;
  29514. // Alpha
  29515. serializationObject.alphaIndex = this.alphaIndex;
  29516. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29517. // Overlay
  29518. serializationObject.overlayAlpha = this.overlayAlpha;
  29519. serializationObject.overlayColor = this.overlayColor.asArray();
  29520. serializationObject.renderOverlay = this.renderOverlay;
  29521. // Fog
  29522. serializationObject.applyFog = this.applyFog;
  29523. // Action Manager
  29524. if (this.actionManager) {
  29525. serializationObject.actions = this.actionManager.serialize(this.name);
  29526. }
  29527. };
  29528. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29529. if (!this.geometry) {
  29530. return;
  29531. }
  29532. this._markSubMeshesAsAttributesDirty();
  29533. var morphTargetManager = this._morphTargetManager;
  29534. if (morphTargetManager && morphTargetManager.vertexCount) {
  29535. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29536. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29537. this.morphTargetManager = null;
  29538. return;
  29539. }
  29540. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29541. var morphTarget = morphTargetManager.getActiveTarget(index);
  29542. var positions = morphTarget.getPositions();
  29543. if (!positions) {
  29544. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29545. return;
  29546. }
  29547. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29548. var normals = morphTarget.getNormals();
  29549. if (normals) {
  29550. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29551. }
  29552. var tangents = morphTarget.getTangents();
  29553. if (tangents) {
  29554. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29555. }
  29556. }
  29557. }
  29558. else {
  29559. var index = 0;
  29560. // Positions
  29561. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29562. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29563. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29564. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29565. }
  29566. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29567. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29568. }
  29569. index++;
  29570. }
  29571. }
  29572. };
  29573. // Statics
  29574. /**
  29575. * Returns a new Mesh object parsed from the source provided.
  29576. * The parameter `parsedMesh` is the source.
  29577. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29578. */
  29579. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29580. var mesh;
  29581. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29582. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29583. }
  29584. else {
  29585. mesh = new Mesh(parsedMesh.name, scene);
  29586. }
  29587. mesh.id = parsedMesh.id;
  29588. if (BABYLON.Tags) {
  29589. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29590. }
  29591. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29592. if (parsedMesh.metadata !== undefined) {
  29593. mesh.metadata = parsedMesh.metadata;
  29594. }
  29595. if (parsedMesh.rotationQuaternion) {
  29596. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29597. }
  29598. else if (parsedMesh.rotation) {
  29599. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29600. }
  29601. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29602. if (parsedMesh.localMatrix) {
  29603. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29604. }
  29605. else if (parsedMesh.pivotMatrix) {
  29606. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29607. }
  29608. mesh.setEnabled(parsedMesh.isEnabled);
  29609. mesh.isVisible = parsedMesh.isVisible;
  29610. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29611. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29612. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29613. if (parsedMesh.applyFog !== undefined) {
  29614. mesh.applyFog = parsedMesh.applyFog;
  29615. }
  29616. if (parsedMesh.pickable !== undefined) {
  29617. mesh.isPickable = parsedMesh.pickable;
  29618. }
  29619. if (parsedMesh.alphaIndex !== undefined) {
  29620. mesh.alphaIndex = parsedMesh.alphaIndex;
  29621. }
  29622. mesh.receiveShadows = parsedMesh.receiveShadows;
  29623. mesh.billboardMode = parsedMesh.billboardMode;
  29624. if (parsedMesh.visibility !== undefined) {
  29625. mesh.visibility = parsedMesh.visibility;
  29626. }
  29627. mesh.checkCollisions = parsedMesh.checkCollisions;
  29628. if (parsedMesh.isBlocker !== undefined) {
  29629. mesh.isBlocker = parsedMesh.isBlocker;
  29630. }
  29631. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29632. // freezeWorldMatrix
  29633. if (parsedMesh.freezeWorldMatrix) {
  29634. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29635. }
  29636. // Parent
  29637. if (parsedMesh.parentId) {
  29638. mesh._waitingParentId = parsedMesh.parentId;
  29639. }
  29640. // Actions
  29641. if (parsedMesh.actions !== undefined) {
  29642. mesh._waitingActions = parsedMesh.actions;
  29643. }
  29644. // Overlay
  29645. if (parsedMesh.overlayAlpha !== undefined) {
  29646. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29647. }
  29648. if (parsedMesh.overlayColor !== undefined) {
  29649. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29650. }
  29651. if (parsedMesh.renderOverlay !== undefined) {
  29652. mesh.renderOverlay = parsedMesh.renderOverlay;
  29653. }
  29654. // Geometry
  29655. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29656. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29657. if (parsedMesh.delayLoadingFile) {
  29658. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29659. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29660. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29661. if (parsedMesh._binaryInfo) {
  29662. mesh._binaryInfo = parsedMesh._binaryInfo;
  29663. }
  29664. mesh._delayInfo = [];
  29665. if (parsedMesh.hasUVs) {
  29666. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29667. }
  29668. if (parsedMesh.hasUVs2) {
  29669. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29670. }
  29671. if (parsedMesh.hasUVs3) {
  29672. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29673. }
  29674. if (parsedMesh.hasUVs4) {
  29675. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29676. }
  29677. if (parsedMesh.hasUVs5) {
  29678. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29679. }
  29680. if (parsedMesh.hasUVs6) {
  29681. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29682. }
  29683. if (parsedMesh.hasColors) {
  29684. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29685. }
  29686. if (parsedMesh.hasMatricesIndices) {
  29687. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29688. }
  29689. if (parsedMesh.hasMatricesWeights) {
  29690. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29691. }
  29692. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29693. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29694. mesh._checkDelayState();
  29695. }
  29696. }
  29697. else {
  29698. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29699. }
  29700. // Material
  29701. if (parsedMesh.materialId) {
  29702. mesh.setMaterialByID(parsedMesh.materialId);
  29703. }
  29704. else {
  29705. mesh.material = null;
  29706. }
  29707. // Morph targets
  29708. if (parsedMesh.morphTargetManagerId > -1) {
  29709. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29710. }
  29711. // Skeleton
  29712. if (parsedMesh.skeletonId > -1) {
  29713. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29714. if (parsedMesh.numBoneInfluencers) {
  29715. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29716. }
  29717. }
  29718. // Animations
  29719. if (parsedMesh.animations) {
  29720. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29721. var parsedAnimation = parsedMesh.animations[animationIndex];
  29722. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29723. }
  29724. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29725. }
  29726. if (parsedMesh.autoAnimate) {
  29727. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29728. }
  29729. // Layer Mask
  29730. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29731. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29732. }
  29733. else {
  29734. mesh.layerMask = 0x0FFFFFFF;
  29735. }
  29736. // Physics
  29737. if (parsedMesh.physicsImpostor) {
  29738. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29739. mass: parsedMesh.physicsMass,
  29740. friction: parsedMesh.physicsFriction,
  29741. restitution: parsedMesh.physicsRestitution
  29742. }, scene);
  29743. }
  29744. // Instances
  29745. if (parsedMesh.instances) {
  29746. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29747. var parsedInstance = parsedMesh.instances[index];
  29748. var instance = mesh.createInstance(parsedInstance.name);
  29749. if (parsedInstance.id) {
  29750. instance.id = parsedInstance.id;
  29751. }
  29752. if (BABYLON.Tags) {
  29753. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29754. }
  29755. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29756. if (parsedInstance.parentId) {
  29757. instance._waitingParentId = parsedInstance.parentId;
  29758. }
  29759. if (parsedInstance.rotationQuaternion) {
  29760. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29761. }
  29762. else if (parsedInstance.rotation) {
  29763. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29764. }
  29765. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29766. instance.checkCollisions = mesh.checkCollisions;
  29767. if (parsedMesh.animations) {
  29768. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29769. parsedAnimation = parsedMesh.animations[animationIndex];
  29770. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29771. }
  29772. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29773. }
  29774. }
  29775. }
  29776. return mesh;
  29777. };
  29778. /**
  29779. * Creates a ribbon mesh.
  29780. * Please consider using the same method from the MeshBuilder class instead.
  29781. * 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.
  29782. *
  29783. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29784. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29785. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29786. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29787. * 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.
  29788. * 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.
  29789. * 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
  29790. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29791. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29792. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29793. */
  29794. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29795. if (closeArray === void 0) { closeArray = false; }
  29796. if (updatable === void 0) { updatable = false; }
  29797. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29798. pathArray: pathArray,
  29799. closeArray: closeArray,
  29800. closePath: closePath,
  29801. offset: offset,
  29802. updatable: updatable,
  29803. sideOrientation: sideOrientation,
  29804. instance: instance
  29805. }, scene);
  29806. };
  29807. /**
  29808. * Creates a plane polygonal mesh. By default, this is a disc.
  29809. * Please consider using the same method from the MeshBuilder class instead.
  29810. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29811. * 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.
  29812. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29813. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29814. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29815. */
  29816. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29817. if (scene === void 0) { scene = null; }
  29818. var options = {
  29819. radius: radius,
  29820. tessellation: tessellation,
  29821. sideOrientation: sideOrientation,
  29822. updatable: updatable
  29823. };
  29824. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29825. };
  29826. /**
  29827. * Creates a box mesh.
  29828. * Please consider using the same method from the MeshBuilder class instead.
  29829. * The parameter `size` sets the size (float) of each box side (default 1).
  29830. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29831. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29832. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29833. */
  29834. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29835. if (scene === void 0) { scene = null; }
  29836. var options = {
  29837. size: size,
  29838. sideOrientation: sideOrientation,
  29839. updatable: updatable
  29840. };
  29841. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29842. };
  29843. /**
  29844. * Creates a sphere mesh.
  29845. * Please consider using the same method from the MeshBuilder class instead.
  29846. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29847. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29848. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29849. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29850. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29851. */
  29852. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29853. var options = {
  29854. segments: segments,
  29855. diameterX: diameter,
  29856. diameterY: diameter,
  29857. diameterZ: diameter,
  29858. sideOrientation: sideOrientation,
  29859. updatable: updatable
  29860. };
  29861. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29862. };
  29863. /**
  29864. * Creates a cylinder or a cone mesh.
  29865. * Please consider using the same method from the MeshBuilder class instead.
  29866. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29867. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29868. * 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.
  29869. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29870. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29871. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29872. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29873. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29874. */
  29875. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29876. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29877. if (scene !== undefined) {
  29878. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29879. updatable = scene;
  29880. }
  29881. scene = subdivisions;
  29882. subdivisions = 1;
  29883. }
  29884. var options = {
  29885. height: height,
  29886. diameterTop: diameterTop,
  29887. diameterBottom: diameterBottom,
  29888. tessellation: tessellation,
  29889. subdivisions: subdivisions,
  29890. sideOrientation: sideOrientation,
  29891. updatable: updatable
  29892. };
  29893. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29894. };
  29895. // Torus (Code from SharpDX.org)
  29896. /**
  29897. * Creates a torus mesh.
  29898. * Please consider using the same method from the MeshBuilder class instead.
  29899. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29900. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29901. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29902. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29903. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29904. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29905. */
  29906. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29907. var options = {
  29908. diameter: diameter,
  29909. thickness: thickness,
  29910. tessellation: tessellation,
  29911. sideOrientation: sideOrientation,
  29912. updatable: updatable
  29913. };
  29914. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29915. };
  29916. /**
  29917. * Creates a torus knot mesh.
  29918. * Please consider using the same method from the MeshBuilder class instead.
  29919. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29920. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29921. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29922. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29923. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29924. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29925. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29926. */
  29927. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29928. var options = {
  29929. radius: radius,
  29930. tube: tube,
  29931. radialSegments: radialSegments,
  29932. tubularSegments: tubularSegments,
  29933. p: p,
  29934. q: q,
  29935. sideOrientation: sideOrientation,
  29936. updatable: updatable
  29937. };
  29938. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29939. };
  29940. /**
  29941. * Creates a line mesh.
  29942. * Please consider using the same method from the MeshBuilder class instead.
  29943. * 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.
  29944. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29945. * The parameter `points` is an array successive Vector3.
  29946. * 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
  29947. * When updating an instance, remember that only point positions can change, not the number of points.
  29948. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29949. */
  29950. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29951. if (scene === void 0) { scene = null; }
  29952. if (updatable === void 0) { updatable = false; }
  29953. if (instance === void 0) { instance = null; }
  29954. var options = {
  29955. points: points,
  29956. updatable: updatable,
  29957. instance: instance
  29958. };
  29959. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29960. };
  29961. /**
  29962. * Creates a dashed line mesh.
  29963. * Please consider using the same method from the MeshBuilder class instead.
  29964. * 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.
  29965. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29966. * The parameter `points` is an array successive Vector3.
  29967. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29968. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29969. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29970. * 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
  29971. * When updating an instance, remember that only point positions can change, not the number of points.
  29972. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29973. */
  29974. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29975. if (scene === void 0) { scene = null; }
  29976. var options = {
  29977. points: points,
  29978. dashSize: dashSize,
  29979. gapSize: gapSize,
  29980. dashNb: dashNb,
  29981. updatable: updatable,
  29982. instance: instance
  29983. };
  29984. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29985. };
  29986. /**
  29987. * Creates a polygon mesh.
  29988. * Please consider using the same method from the MeshBuilder class instead.
  29989. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29990. * 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.
  29991. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29992. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29993. * Remember you can only change the shape positions, not their number when updating a polygon.
  29994. */
  29995. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29996. var options = {
  29997. shape: shape,
  29998. holes: holes,
  29999. updatable: updatable,
  30000. sideOrientation: sideOrientation
  30001. };
  30002. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  30003. };
  30004. /**
  30005. * Creates an extruded polygon mesh, with depth in the Y direction.
  30006. * Please consider using the same method from the MeshBuilder class instead.
  30007. */
  30008. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  30009. var options = {
  30010. shape: shape,
  30011. holes: holes,
  30012. depth: depth,
  30013. updatable: updatable,
  30014. sideOrientation: sideOrientation
  30015. };
  30016. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  30017. };
  30018. /**
  30019. * Creates an extruded shape mesh.
  30020. * 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.
  30021. * Please consider using the same method from the MeshBuilder class instead.
  30022. *
  30023. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30024. * 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
  30025. * extruded along the Z axis.
  30026. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30027. * 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.
  30028. * The parameter `scale` (float, default 1) is the value to scale the shape.
  30029. * 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
  30030. * 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
  30031. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30032. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30033. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30034. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30035. */
  30036. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  30037. if (scene === void 0) { scene = null; }
  30038. var options = {
  30039. shape: shape,
  30040. path: path,
  30041. scale: scale,
  30042. rotation: rotation,
  30043. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30044. sideOrientation: sideOrientation,
  30045. instance: instance,
  30046. updatable: updatable
  30047. };
  30048. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  30049. };
  30050. /**
  30051. * Creates an custom extruded shape mesh.
  30052. * 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.
  30053. * Please consider using the same method from the MeshBuilder class instead.
  30054. *
  30055. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30056. * 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
  30057. * extruded along the Z axis.
  30058. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30059. * 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
  30060. * and the distance of this point from the begining of the path :
  30061. * ```javascript
  30062. * var rotationFunction = function(i, distance) {
  30063. * // do things
  30064. * return rotationValue; }
  30065. * ```
  30066. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  30067. * 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
  30068. * and the distance of this point from the begining of the path :
  30069. * ```javascript
  30070. * var scaleFunction = function(i, distance) {
  30071. * // do things
  30072. * return scaleValue;}
  30073. * ```
  30074. * It must returns a float value that will be the scale value applied to the shape on each path point.
  30075. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  30076. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  30077. * 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
  30078. * 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
  30079. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30080. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30081. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30082. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30083. */
  30084. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  30085. var options = {
  30086. shape: shape,
  30087. path: path,
  30088. scaleFunction: scaleFunction,
  30089. rotationFunction: rotationFunction,
  30090. ribbonCloseArray: ribbonCloseArray,
  30091. ribbonClosePath: ribbonClosePath,
  30092. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30093. sideOrientation: sideOrientation,
  30094. instance: instance,
  30095. updatable: updatable
  30096. };
  30097. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  30098. };
  30099. /**
  30100. * Creates lathe mesh.
  30101. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  30102. * Please consider using the same method from the MeshBuilder class instead.
  30103. * 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
  30104. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  30105. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  30106. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  30107. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30108. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30109. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30110. */
  30111. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  30112. var options = {
  30113. shape: shape,
  30114. radius: radius,
  30115. tessellation: tessellation,
  30116. sideOrientation: sideOrientation,
  30117. updatable: updatable
  30118. };
  30119. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  30120. };
  30121. /**
  30122. * Creates a plane mesh.
  30123. * Please consider using the same method from the MeshBuilder class instead.
  30124. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  30125. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30126. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30127. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30128. */
  30129. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  30130. var options = {
  30131. size: size,
  30132. width: size,
  30133. height: size,
  30134. sideOrientation: sideOrientation,
  30135. updatable: updatable
  30136. };
  30137. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  30138. };
  30139. /**
  30140. * Creates a ground mesh.
  30141. * Please consider using the same method from the MeshBuilder class instead.
  30142. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  30143. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  30144. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30145. */
  30146. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  30147. var options = {
  30148. width: width,
  30149. height: height,
  30150. subdivisions: subdivisions,
  30151. updatable: updatable
  30152. };
  30153. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  30154. };
  30155. /**
  30156. * Creates a tiled ground mesh.
  30157. * Please consider using the same method from the MeshBuilder class instead.
  30158. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30159. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30160. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30161. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30162. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30163. * numbers of subdivisions on the ground width and height of each tile.
  30164. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30165. */
  30166. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30167. var options = {
  30168. xmin: xmin,
  30169. zmin: zmin,
  30170. xmax: xmax,
  30171. zmax: zmax,
  30172. subdivisions: subdivisions,
  30173. precision: precision,
  30174. updatable: updatable
  30175. };
  30176. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30177. };
  30178. /**
  30179. * Creates a ground mesh from a height map.
  30180. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30181. * Please consider using the same method from the MeshBuilder class instead.
  30182. * The parameter `url` sets the URL of the height map image resource.
  30183. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30184. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30185. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30186. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30187. * 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).
  30188. * This function is passed the newly built mesh :
  30189. * ```javascript
  30190. * function(mesh) { // do things
  30191. * return; }
  30192. * ```
  30193. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30194. */
  30195. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30196. var options = {
  30197. width: width,
  30198. height: height,
  30199. subdivisions: subdivisions,
  30200. minHeight: minHeight,
  30201. maxHeight: maxHeight,
  30202. updatable: updatable,
  30203. onReady: onReady
  30204. };
  30205. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30206. };
  30207. /**
  30208. * Creates a tube mesh.
  30209. * 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.
  30210. * Please consider using the same method from the MeshBuilder class instead.
  30211. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30212. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30213. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30214. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30215. * 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.
  30216. * It must return a radius value (positive float) :
  30217. * ```javascript
  30218. * var radiusFunction = function(i, distance) {
  30219. * // do things
  30220. * return radius; }
  30221. * ```
  30222. * 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
  30223. * 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
  30224. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30225. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30226. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30227. */
  30228. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30229. var options = {
  30230. path: path,
  30231. radius: radius,
  30232. tessellation: tessellation,
  30233. radiusFunction: radiusFunction,
  30234. arc: 1,
  30235. cap: cap,
  30236. updatable: updatable,
  30237. sideOrientation: sideOrientation,
  30238. instance: instance
  30239. };
  30240. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30241. };
  30242. /**
  30243. * Creates a polyhedron mesh.
  30244. * Please consider using the same method from the MeshBuilder class instead.
  30245. * 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
  30246. * to choose the wanted type.
  30247. * The parameter `size` (positive float, default 1) sets the polygon size.
  30248. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30249. * 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`.
  30250. * 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
  30251. * 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)`).
  30252. * 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
  30253. * 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.
  30254. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30255. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30256. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30257. */
  30258. Mesh.CreatePolyhedron = function (name, options, scene) {
  30259. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30260. };
  30261. /**
  30262. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30263. * Please consider using the same method from the MeshBuilder class instead.
  30264. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30265. * 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`).
  30266. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30267. * 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.
  30268. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30269. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30270. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30271. */
  30272. Mesh.CreateIcoSphere = function (name, options, scene) {
  30273. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30274. };
  30275. /**
  30276. * Creates a decal mesh.
  30277. * Please consider using the same method from the MeshBuilder class instead.
  30278. * 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.
  30279. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30280. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30281. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30282. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30283. */
  30284. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30285. var options = {
  30286. position: position,
  30287. normal: normal,
  30288. size: size,
  30289. angle: angle
  30290. };
  30291. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30292. };
  30293. // Skeletons
  30294. /**
  30295. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30296. */
  30297. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30298. if (!this._sourcePositions) {
  30299. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30300. if (!source) {
  30301. return this._sourcePositions;
  30302. }
  30303. this._sourcePositions = new Float32Array(source);
  30304. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30305. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30306. }
  30307. }
  30308. return this._sourcePositions;
  30309. };
  30310. /**
  30311. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30312. */
  30313. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30314. if (!this._sourceNormals) {
  30315. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30316. if (!source) {
  30317. return this._sourceNormals;
  30318. }
  30319. this._sourceNormals = new Float32Array(source);
  30320. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30321. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30322. }
  30323. }
  30324. return this._sourceNormals;
  30325. };
  30326. /**
  30327. * Updates the vertex buffer by applying transformation from the bones.
  30328. * Returns the Mesh.
  30329. *
  30330. * @param {skeleton} skeleton to apply
  30331. */
  30332. Mesh.prototype.applySkeleton = function (skeleton) {
  30333. if (!this.geometry) {
  30334. return this;
  30335. }
  30336. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30337. return this;
  30338. }
  30339. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30340. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30341. return this;
  30342. }
  30343. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30344. return this;
  30345. }
  30346. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30347. return this;
  30348. }
  30349. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30350. return this;
  30351. }
  30352. if (!this._sourcePositions) {
  30353. var submeshes = this.subMeshes.slice();
  30354. this.setPositionsForCPUSkinning();
  30355. this.subMeshes = submeshes;
  30356. }
  30357. if (!this._sourceNormals) {
  30358. this.setNormalsForCPUSkinning();
  30359. }
  30360. // positionsData checks for not being Float32Array will only pass at most once
  30361. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30362. if (!positionsData) {
  30363. return this;
  30364. }
  30365. if (!(positionsData instanceof Float32Array)) {
  30366. positionsData = new Float32Array(positionsData);
  30367. }
  30368. // normalsData checks for not being Float32Array will only pass at most once
  30369. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30370. if (!normalsData) {
  30371. return this;
  30372. }
  30373. if (!(normalsData instanceof Float32Array)) {
  30374. normalsData = new Float32Array(normalsData);
  30375. }
  30376. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30377. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30378. if (!matricesWeightsData || !matricesIndicesData) {
  30379. return this;
  30380. }
  30381. var needExtras = this.numBoneInfluencers > 4;
  30382. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30383. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30384. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30385. var tempVector3 = BABYLON.Vector3.Zero();
  30386. var finalMatrix = new BABYLON.Matrix();
  30387. var tempMatrix = new BABYLON.Matrix();
  30388. var matWeightIdx = 0;
  30389. var inf;
  30390. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30391. var weight;
  30392. for (inf = 0; inf < 4; inf++) {
  30393. weight = matricesWeightsData[matWeightIdx + inf];
  30394. if (weight > 0) {
  30395. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30396. finalMatrix.addToSelf(tempMatrix);
  30397. }
  30398. else
  30399. break;
  30400. }
  30401. if (needExtras) {
  30402. for (inf = 0; inf < 4; inf++) {
  30403. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30404. if (weight > 0) {
  30405. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30406. finalMatrix.addToSelf(tempMatrix);
  30407. }
  30408. else
  30409. break;
  30410. }
  30411. }
  30412. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30413. tempVector3.toArray(positionsData, index);
  30414. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30415. tempVector3.toArray(normalsData, index);
  30416. finalMatrix.reset();
  30417. }
  30418. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30419. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30420. return this;
  30421. };
  30422. // Tools
  30423. /**
  30424. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30425. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30426. */
  30427. Mesh.MinMax = function (meshes) {
  30428. var minVector = null;
  30429. var maxVector = null;
  30430. meshes.forEach(function (mesh, index, array) {
  30431. var boundingInfo = mesh.getBoundingInfo();
  30432. var boundingBox = boundingInfo.boundingBox;
  30433. if (!minVector || !maxVector) {
  30434. minVector = boundingBox.minimumWorld;
  30435. maxVector = boundingBox.maximumWorld;
  30436. }
  30437. else {
  30438. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30439. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30440. }
  30441. });
  30442. if (!minVector || !maxVector) {
  30443. return {
  30444. min: BABYLON.Vector3.Zero(),
  30445. max: BABYLON.Vector3.Zero()
  30446. };
  30447. }
  30448. return {
  30449. min: minVector,
  30450. max: maxVector
  30451. };
  30452. };
  30453. /**
  30454. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30455. */
  30456. Mesh.Center = function (meshesOrMinMaxVector) {
  30457. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30458. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30459. };
  30460. /**
  30461. * Merge the array of meshes into a single mesh for performance reasons.
  30462. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30463. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30464. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30465. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30466. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30467. */
  30468. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30469. if (disposeSource === void 0) { disposeSource = true; }
  30470. var index;
  30471. if (!allow32BitsIndices) {
  30472. var totalVertices = 0;
  30473. // Counting vertices
  30474. for (index = 0; index < meshes.length; index++) {
  30475. if (meshes[index]) {
  30476. totalVertices += meshes[index].getTotalVertices();
  30477. if (totalVertices > 65536) {
  30478. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30479. return null;
  30480. }
  30481. }
  30482. }
  30483. }
  30484. // Merge
  30485. var vertexData = null;
  30486. var otherVertexData;
  30487. var indiceArray = new Array();
  30488. var source = null;
  30489. for (index = 0; index < meshes.length; index++) {
  30490. if (meshes[index]) {
  30491. meshes[index].computeWorldMatrix(true);
  30492. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30493. otherVertexData.transform(meshes[index].getWorldMatrix());
  30494. if (vertexData) {
  30495. vertexData.merge(otherVertexData);
  30496. }
  30497. else {
  30498. vertexData = otherVertexData;
  30499. source = meshes[index];
  30500. }
  30501. if (subdivideWithSubMeshes) {
  30502. indiceArray.push(meshes[index].getTotalIndices());
  30503. }
  30504. }
  30505. }
  30506. source = source;
  30507. if (!meshSubclass) {
  30508. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30509. }
  30510. vertexData.applyToMesh(meshSubclass);
  30511. // Setting properties
  30512. meshSubclass.material = source.material;
  30513. meshSubclass.checkCollisions = source.checkCollisions;
  30514. // Cleaning
  30515. if (disposeSource) {
  30516. for (index = 0; index < meshes.length; index++) {
  30517. if (meshes[index]) {
  30518. meshes[index].dispose();
  30519. }
  30520. }
  30521. }
  30522. // Subdivide
  30523. if (subdivideWithSubMeshes) {
  30524. //-- Suppresions du submesh global
  30525. meshSubclass.releaseSubMeshes();
  30526. index = 0;
  30527. var offset = 0;
  30528. //-- aplique la subdivision en fonction du tableau d'indices
  30529. while (index < indiceArray.length) {
  30530. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30531. offset += indiceArray[index];
  30532. index++;
  30533. }
  30534. }
  30535. return meshSubclass;
  30536. };
  30537. // Consts
  30538. Mesh._FRONTSIDE = 0;
  30539. Mesh._BACKSIDE = 1;
  30540. Mesh._DOUBLESIDE = 2;
  30541. Mesh._DEFAULTSIDE = 0;
  30542. Mesh._NO_CAP = 0;
  30543. Mesh._CAP_START = 1;
  30544. Mesh._CAP_END = 2;
  30545. Mesh._CAP_ALL = 3;
  30546. return Mesh;
  30547. }(BABYLON.AbstractMesh));
  30548. BABYLON.Mesh = Mesh;
  30549. })(BABYLON || (BABYLON = {}));
  30550. //# sourceMappingURL=babylon.mesh.js.map
  30551. var BABYLON;
  30552. (function (BABYLON) {
  30553. var BaseSubMesh = /** @class */ (function () {
  30554. function BaseSubMesh() {
  30555. }
  30556. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30557. get: function () {
  30558. return this._materialEffect;
  30559. },
  30560. enumerable: true,
  30561. configurable: true
  30562. });
  30563. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30564. if (defines === void 0) { defines = null; }
  30565. if (this._materialEffect === effect) {
  30566. if (!effect) {
  30567. this._materialDefines = null;
  30568. }
  30569. return;
  30570. }
  30571. this._materialDefines = defines;
  30572. this._materialEffect = effect;
  30573. };
  30574. return BaseSubMesh;
  30575. }());
  30576. BABYLON.BaseSubMesh = BaseSubMesh;
  30577. var SubMesh = /** @class */ (function (_super) {
  30578. __extends(SubMesh, _super);
  30579. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30580. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30581. var _this = _super.call(this) || this;
  30582. _this.materialIndex = materialIndex;
  30583. _this.verticesStart = verticesStart;
  30584. _this.verticesCount = verticesCount;
  30585. _this.indexStart = indexStart;
  30586. _this.indexCount = indexCount;
  30587. _this._renderId = 0;
  30588. _this._mesh = mesh;
  30589. _this._renderingMesh = renderingMesh || mesh;
  30590. mesh.subMeshes.push(_this);
  30591. _this._trianglePlanes = [];
  30592. _this._id = mesh.subMeshes.length - 1;
  30593. if (createBoundingBox) {
  30594. _this.refreshBoundingInfo();
  30595. mesh.computeWorldMatrix(true);
  30596. }
  30597. return _this;
  30598. }
  30599. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30600. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30601. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30602. };
  30603. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30604. get: function () {
  30605. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30606. },
  30607. enumerable: true,
  30608. configurable: true
  30609. });
  30610. /**
  30611. * Returns the submesh BoudingInfo object.
  30612. */
  30613. SubMesh.prototype.getBoundingInfo = function () {
  30614. if (this.IsGlobal) {
  30615. return this._mesh.getBoundingInfo();
  30616. }
  30617. return this._boundingInfo;
  30618. };
  30619. /**
  30620. * Sets the submesh BoundingInfo.
  30621. * Return the SubMesh.
  30622. */
  30623. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30624. this._boundingInfo = boundingInfo;
  30625. return this;
  30626. };
  30627. /**
  30628. * Returns the mesh of the current submesh.
  30629. */
  30630. SubMesh.prototype.getMesh = function () {
  30631. return this._mesh;
  30632. };
  30633. /**
  30634. * Returns the rendering mesh of the submesh.
  30635. */
  30636. SubMesh.prototype.getRenderingMesh = function () {
  30637. return this._renderingMesh;
  30638. };
  30639. /**
  30640. * Returns the submesh material.
  30641. */
  30642. SubMesh.prototype.getMaterial = function () {
  30643. var rootMaterial = this._renderingMesh.material;
  30644. if (rootMaterial === null || rootMaterial === undefined) {
  30645. return this._mesh.getScene().defaultMaterial;
  30646. }
  30647. else if (rootMaterial.getSubMaterial) {
  30648. var multiMaterial = rootMaterial;
  30649. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30650. if (this._currentMaterial !== effectiveMaterial) {
  30651. this._currentMaterial = effectiveMaterial;
  30652. this._materialDefines = null;
  30653. }
  30654. return effectiveMaterial;
  30655. }
  30656. return rootMaterial;
  30657. };
  30658. // Methods
  30659. /**
  30660. * Sets a new updated BoundingInfo object to the submesh.
  30661. * Returns the SubMesh.
  30662. */
  30663. SubMesh.prototype.refreshBoundingInfo = function () {
  30664. this._lastColliderWorldVertices = null;
  30665. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30666. return this;
  30667. }
  30668. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30669. if (!data) {
  30670. this._boundingInfo = this._mesh.getBoundingInfo();
  30671. return this;
  30672. }
  30673. var indices = this._renderingMesh.getIndices();
  30674. var extend;
  30675. //is this the only submesh?
  30676. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30677. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30678. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30679. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30680. }
  30681. else {
  30682. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30683. }
  30684. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30685. return this;
  30686. };
  30687. SubMesh.prototype._checkCollision = function (collider) {
  30688. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30689. return boundingInfo._checkCollision(collider);
  30690. };
  30691. /**
  30692. * Updates the submesh BoundingInfo.
  30693. * Returns the Submesh.
  30694. */
  30695. SubMesh.prototype.updateBoundingInfo = function (world) {
  30696. var boundingInfo = this.getBoundingInfo();
  30697. if (!boundingInfo) {
  30698. this.refreshBoundingInfo();
  30699. boundingInfo = this.getBoundingInfo();
  30700. }
  30701. boundingInfo.update(world);
  30702. return this;
  30703. };
  30704. /**
  30705. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30706. * Boolean returned.
  30707. */
  30708. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30709. var boundingInfo = this.getBoundingInfo();
  30710. if (!boundingInfo) {
  30711. return false;
  30712. }
  30713. return boundingInfo.isInFrustum(frustumPlanes);
  30714. };
  30715. /**
  30716. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30717. * Boolean returned.
  30718. */
  30719. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30720. var boundingInfo = this.getBoundingInfo();
  30721. if (!boundingInfo) {
  30722. return false;
  30723. }
  30724. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30725. };
  30726. /**
  30727. * Renders the submesh.
  30728. * Returns it.
  30729. */
  30730. SubMesh.prototype.render = function (enableAlphaMode) {
  30731. this._renderingMesh.render(this, enableAlphaMode);
  30732. return this;
  30733. };
  30734. /**
  30735. * Returns a new Index Buffer.
  30736. * Type returned : WebGLBuffer.
  30737. */
  30738. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30739. if (!this._linesIndexBuffer) {
  30740. var linesIndices = [];
  30741. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30742. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30743. }
  30744. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30745. this.linesIndexCount = linesIndices.length;
  30746. }
  30747. return this._linesIndexBuffer;
  30748. };
  30749. /**
  30750. * True is the passed Ray intersects the submesh bounding box.
  30751. * Boolean returned.
  30752. */
  30753. SubMesh.prototype.canIntersects = function (ray) {
  30754. var boundingInfo = this.getBoundingInfo();
  30755. if (!boundingInfo) {
  30756. return false;
  30757. }
  30758. return ray.intersectsBox(boundingInfo.boundingBox);
  30759. };
  30760. /**
  30761. * Returns an object IntersectionInfo.
  30762. */
  30763. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30764. var intersectInfo = null;
  30765. // LineMesh first as it's also a Mesh...
  30766. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30767. var lineMesh = this._mesh;
  30768. // Line test
  30769. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30770. var p0 = positions[indices[index]];
  30771. var p1 = positions[indices[index + 1]];
  30772. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30773. if (length < 0) {
  30774. continue;
  30775. }
  30776. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30777. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30778. if (fastCheck) {
  30779. break;
  30780. }
  30781. }
  30782. }
  30783. }
  30784. else {
  30785. // Triangles test
  30786. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30787. var p0 = positions[indices[index]];
  30788. var p1 = positions[indices[index + 1]];
  30789. var p2 = positions[indices[index + 2]];
  30790. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30791. if (currentIntersectInfo) {
  30792. if (currentIntersectInfo.distance < 0) {
  30793. continue;
  30794. }
  30795. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30796. intersectInfo = currentIntersectInfo;
  30797. intersectInfo.faceId = index / 3;
  30798. if (fastCheck) {
  30799. break;
  30800. }
  30801. }
  30802. }
  30803. }
  30804. }
  30805. return intersectInfo;
  30806. };
  30807. SubMesh.prototype._rebuild = function () {
  30808. if (this._linesIndexBuffer) {
  30809. this._linesIndexBuffer = null;
  30810. }
  30811. };
  30812. // Clone
  30813. /**
  30814. * Creates a new Submesh from the passed Mesh.
  30815. */
  30816. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30817. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30818. if (!this.IsGlobal) {
  30819. var boundingInfo = this.getBoundingInfo();
  30820. if (!boundingInfo) {
  30821. return result;
  30822. }
  30823. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30824. }
  30825. return result;
  30826. };
  30827. // Dispose
  30828. /**
  30829. * Disposes the Submesh.
  30830. * Returns nothing.
  30831. */
  30832. SubMesh.prototype.dispose = function () {
  30833. if (this._linesIndexBuffer) {
  30834. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30835. this._linesIndexBuffer = null;
  30836. }
  30837. // Remove from mesh
  30838. var index = this._mesh.subMeshes.indexOf(this);
  30839. this._mesh.subMeshes.splice(index, 1);
  30840. };
  30841. // Statics
  30842. /**
  30843. * Creates a new Submesh from the passed parameters :
  30844. * - materialIndex (integer) : the index of the main mesh material.
  30845. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30846. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30847. * - mesh (Mesh) : the main mesh to create the submesh from.
  30848. * - renderingMesh (optional Mesh) : rendering mesh.
  30849. */
  30850. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30851. var minVertexIndex = Number.MAX_VALUE;
  30852. var maxVertexIndex = -Number.MAX_VALUE;
  30853. renderingMesh = (renderingMesh || mesh);
  30854. var indices = renderingMesh.getIndices();
  30855. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30856. var vertexIndex = indices[index];
  30857. if (vertexIndex < minVertexIndex)
  30858. minVertexIndex = vertexIndex;
  30859. if (vertexIndex > maxVertexIndex)
  30860. maxVertexIndex = vertexIndex;
  30861. }
  30862. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30863. };
  30864. return SubMesh;
  30865. }(BaseSubMesh));
  30866. BABYLON.SubMesh = SubMesh;
  30867. })(BABYLON || (BABYLON = {}));
  30868. //# sourceMappingURL=babylon.subMesh.js.map
  30869. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30870. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30871. s = arguments[i];
  30872. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30873. t[p] = s[p];
  30874. }
  30875. return t;
  30876. };
  30877. var BABYLON;
  30878. (function (BABYLON) {
  30879. /**
  30880. * Manages the defines for the Material.
  30881. */
  30882. var MaterialDefines = /** @class */ (function () {
  30883. function MaterialDefines() {
  30884. this._isDirty = true;
  30885. this._areLightsDirty = true;
  30886. this._areAttributesDirty = true;
  30887. this._areTexturesDirty = true;
  30888. this._areFresnelDirty = true;
  30889. this._areMiscDirty = true;
  30890. this._areImageProcessingDirty = true;
  30891. this._normals = false;
  30892. this._uvs = false;
  30893. this._needNormals = false;
  30894. this._needUVs = false;
  30895. }
  30896. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30897. /**
  30898. * Specifies if the material needs to be re-calculated.
  30899. */
  30900. get: function () {
  30901. return this._isDirty;
  30902. },
  30903. enumerable: true,
  30904. configurable: true
  30905. });
  30906. /**
  30907. * Marks the material to indicate that it has been re-calculated.
  30908. */
  30909. MaterialDefines.prototype.markAsProcessed = function () {
  30910. this._isDirty = false;
  30911. this._areAttributesDirty = false;
  30912. this._areTexturesDirty = false;
  30913. this._areFresnelDirty = false;
  30914. this._areLightsDirty = false;
  30915. this._areMiscDirty = false;
  30916. this._areImageProcessingDirty = false;
  30917. };
  30918. /**
  30919. * Marks the material to indicate that it needs to be re-calculated.
  30920. */
  30921. MaterialDefines.prototype.markAsUnprocessed = function () {
  30922. this._isDirty = true;
  30923. };
  30924. /**
  30925. * Marks the material to indicate all of its defines need to be re-calculated.
  30926. */
  30927. MaterialDefines.prototype.markAllAsDirty = function () {
  30928. this._areTexturesDirty = true;
  30929. this._areAttributesDirty = true;
  30930. this._areLightsDirty = true;
  30931. this._areFresnelDirty = true;
  30932. this._areMiscDirty = true;
  30933. this._areImageProcessingDirty = true;
  30934. this._isDirty = true;
  30935. };
  30936. /**
  30937. * Marks the material to indicate that image processing needs to be re-calculated.
  30938. */
  30939. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30940. this._areImageProcessingDirty = true;
  30941. this._isDirty = true;
  30942. };
  30943. /**
  30944. * Marks the material to indicate the lights need to be re-calculated.
  30945. */
  30946. MaterialDefines.prototype.markAsLightDirty = function () {
  30947. this._areLightsDirty = true;
  30948. this._isDirty = true;
  30949. };
  30950. /**
  30951. * Marks the attribute state as changed.
  30952. */
  30953. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30954. this._areAttributesDirty = true;
  30955. this._isDirty = true;
  30956. };
  30957. /**
  30958. * Marks the texture state as changed.
  30959. */
  30960. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30961. this._areTexturesDirty = true;
  30962. this._isDirty = true;
  30963. };
  30964. /**
  30965. * Marks the fresnel state as changed.
  30966. */
  30967. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30968. this._areFresnelDirty = true;
  30969. this._isDirty = true;
  30970. };
  30971. /**
  30972. * Marks the misc state as changed.
  30973. */
  30974. MaterialDefines.prototype.markAsMiscDirty = function () {
  30975. this._areMiscDirty = true;
  30976. this._isDirty = true;
  30977. };
  30978. /**
  30979. * Rebuilds the material defines.
  30980. */
  30981. MaterialDefines.prototype.rebuild = function () {
  30982. if (this._keys) {
  30983. delete this._keys;
  30984. }
  30985. this._keys = [];
  30986. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30987. var key = _a[_i];
  30988. if (key[0] === "_") {
  30989. continue;
  30990. }
  30991. this._keys.push(key);
  30992. }
  30993. };
  30994. /**
  30995. * Specifies if two material defines are equal.
  30996. * @param other - A material define instance to compare to.
  30997. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30998. */
  30999. MaterialDefines.prototype.isEqual = function (other) {
  31000. if (this._keys.length !== other._keys.length) {
  31001. return false;
  31002. }
  31003. for (var index = 0; index < this._keys.length; index++) {
  31004. var prop = this._keys[index];
  31005. if (this[prop] !== other[prop]) {
  31006. return false;
  31007. }
  31008. }
  31009. return true;
  31010. };
  31011. /**
  31012. * Clones this instance's defines to another instance.
  31013. * @param other - material defines to clone values to.
  31014. */
  31015. MaterialDefines.prototype.cloneTo = function (other) {
  31016. if (this._keys.length !== other._keys.length) {
  31017. other._keys = this._keys.slice(0);
  31018. }
  31019. for (var index = 0; index < this._keys.length; index++) {
  31020. var prop = this._keys[index];
  31021. other[prop] = this[prop];
  31022. }
  31023. };
  31024. /**
  31025. * Resets the material define values.
  31026. */
  31027. MaterialDefines.prototype.reset = function () {
  31028. for (var index = 0; index < this._keys.length; index++) {
  31029. var prop = this._keys[index];
  31030. if (typeof (this[prop]) === "number") {
  31031. this[prop] = 0;
  31032. }
  31033. else {
  31034. this[prop] = false;
  31035. }
  31036. }
  31037. };
  31038. /**
  31039. * Converts the material define values to a string.
  31040. * @returns - String of material define information.
  31041. */
  31042. MaterialDefines.prototype.toString = function () {
  31043. var result = "";
  31044. for (var index = 0; index < this._keys.length; index++) {
  31045. var prop = this._keys[index];
  31046. var value = this[prop];
  31047. if (typeof (value) === "number") {
  31048. result += "#define " + prop + " " + this[prop] + "\n";
  31049. }
  31050. else if (value) {
  31051. result += "#define " + prop + "\n";
  31052. }
  31053. }
  31054. return result;
  31055. };
  31056. return MaterialDefines;
  31057. }());
  31058. BABYLON.MaterialDefines = MaterialDefines;
  31059. /**
  31060. * This offers the main features of a material in BJS.
  31061. */
  31062. var Material = /** @class */ (function () {
  31063. /**
  31064. * Creates a material instance.
  31065. * @param name - The name of the material.
  31066. * @param scene - The BJS scene to reference.
  31067. * @param doNotAdd - Specifies if the material should be added to the scene.
  31068. */
  31069. function Material(name, scene, doNotAdd) {
  31070. /**
  31071. * Specifies if the ready state should be checked on each call.
  31072. */
  31073. this.checkReadyOnEveryCall = false;
  31074. /**
  31075. * Specifies if the ready state should be checked once.
  31076. */
  31077. this.checkReadyOnlyOnce = false;
  31078. /**
  31079. * The state of the material.
  31080. */
  31081. this.state = "";
  31082. /**
  31083. * The alpha value of the material.
  31084. */
  31085. this._alpha = 1.0;
  31086. /**
  31087. * Specifies if back face culling is enabled.
  31088. */
  31089. this._backFaceCulling = true;
  31090. /**
  31091. * Specifies if the material should be serialized.
  31092. */
  31093. this.doNotSerialize = false;
  31094. /**
  31095. * Specifies if the effect should be stored on sub meshes.
  31096. */
  31097. this.storeEffectOnSubMeshes = false;
  31098. /**
  31099. * An event triggered when the material is disposed.
  31100. * @type {BABYLON.Observable}
  31101. */
  31102. this.onDisposeObservable = new BABYLON.Observable();
  31103. /**
  31104. * An event triggered when the material is bound.
  31105. * @type {BABYLON.Observable}
  31106. */
  31107. this.onBindObservable = new BABYLON.Observable();
  31108. /**
  31109. * An event triggered when the material is unbound.
  31110. * @type {BABYLON.Observable}
  31111. */
  31112. this.onUnBindObservable = new BABYLON.Observable();
  31113. /**
  31114. * Stores the value of the alpha mode.
  31115. */
  31116. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  31117. /**
  31118. * Stores the state of the need depth pre-pass value.
  31119. */
  31120. this._needDepthPrePass = false;
  31121. /**
  31122. * Specifies if depth writing should be disabled.
  31123. */
  31124. this.disableDepthWrite = false;
  31125. /**
  31126. * Specifies if depth writing should be forced.
  31127. */
  31128. this.forceDepthWrite = false;
  31129. /**
  31130. * Specifies if there should be a separate pass for culling.
  31131. */
  31132. this.separateCullingPass = false;
  31133. /**
  31134. * Stores the state specifing if fog should be enabled.
  31135. */
  31136. this._fogEnabled = true;
  31137. /**
  31138. * Stores the size of points.
  31139. */
  31140. this.pointSize = 1.0;
  31141. /**
  31142. * Stores the z offset value.
  31143. */
  31144. this.zOffset = 0;
  31145. /**
  31146. * Specifies if the material was previously ready.
  31147. */
  31148. this._wasPreviouslyReady = false;
  31149. /**
  31150. * Stores the fill mode state.
  31151. */
  31152. this._fillMode = Material.TriangleFillMode;
  31153. this.name = name;
  31154. this.id = name || BABYLON.Tools.RandomId();
  31155. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31156. if (this._scene.useRightHandedSystem) {
  31157. this.sideOrientation = Material.ClockWiseSideOrientation;
  31158. }
  31159. else {
  31160. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31161. }
  31162. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31163. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31164. if (!doNotAdd) {
  31165. this._scene.materials.push(this);
  31166. }
  31167. }
  31168. Object.defineProperty(Material, "TriangleFillMode", {
  31169. /**
  31170. * Returns the triangle fill mode.
  31171. */
  31172. get: function () {
  31173. return Material._TriangleFillMode;
  31174. },
  31175. enumerable: true,
  31176. configurable: true
  31177. });
  31178. Object.defineProperty(Material, "WireFrameFillMode", {
  31179. /**
  31180. * Returns the wireframe mode.
  31181. */
  31182. get: function () {
  31183. return Material._WireFrameFillMode;
  31184. },
  31185. enumerable: true,
  31186. configurable: true
  31187. });
  31188. Object.defineProperty(Material, "PointFillMode", {
  31189. /**
  31190. * Returns the point fill mode.
  31191. */
  31192. get: function () {
  31193. return Material._PointFillMode;
  31194. },
  31195. enumerable: true,
  31196. configurable: true
  31197. });
  31198. Object.defineProperty(Material, "PointListDrawMode", {
  31199. /**
  31200. * Returns the point list draw mode.
  31201. */
  31202. get: function () {
  31203. return Material._PointListDrawMode;
  31204. },
  31205. enumerable: true,
  31206. configurable: true
  31207. });
  31208. Object.defineProperty(Material, "LineListDrawMode", {
  31209. /**
  31210. * Returns the line list draw mode.
  31211. */
  31212. get: function () {
  31213. return Material._LineListDrawMode;
  31214. },
  31215. enumerable: true,
  31216. configurable: true
  31217. });
  31218. Object.defineProperty(Material, "LineLoopDrawMode", {
  31219. /**
  31220. * Returns the line loop draw mode.
  31221. */
  31222. get: function () {
  31223. return Material._LineLoopDrawMode;
  31224. },
  31225. enumerable: true,
  31226. configurable: true
  31227. });
  31228. Object.defineProperty(Material, "LineStripDrawMode", {
  31229. /**
  31230. * Returns the line strip draw mode.
  31231. */
  31232. get: function () {
  31233. return Material._LineStripDrawMode;
  31234. },
  31235. enumerable: true,
  31236. configurable: true
  31237. });
  31238. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31239. /**
  31240. * Returns the triangle strip draw mode.
  31241. */
  31242. get: function () {
  31243. return Material._TriangleStripDrawMode;
  31244. },
  31245. enumerable: true,
  31246. configurable: true
  31247. });
  31248. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31249. /**
  31250. * Returns the triangle fan draw mode.
  31251. */
  31252. get: function () {
  31253. return Material._TriangleFanDrawMode;
  31254. },
  31255. enumerable: true,
  31256. configurable: true
  31257. });
  31258. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31259. /**
  31260. * Returns the clock-wise side orientation.
  31261. */
  31262. get: function () {
  31263. return Material._ClockWiseSideOrientation;
  31264. },
  31265. enumerable: true,
  31266. configurable: true
  31267. });
  31268. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31269. /**
  31270. * Returns the counter clock-wise side orientation.
  31271. */
  31272. get: function () {
  31273. return Material._CounterClockWiseSideOrientation;
  31274. },
  31275. enumerable: true,
  31276. configurable: true
  31277. });
  31278. Object.defineProperty(Material, "TextureDirtyFlag", {
  31279. /**
  31280. * Returns the dirty texture flag value.
  31281. */
  31282. get: function () {
  31283. return Material._TextureDirtyFlag;
  31284. },
  31285. enumerable: true,
  31286. configurable: true
  31287. });
  31288. Object.defineProperty(Material, "LightDirtyFlag", {
  31289. /**
  31290. * Returns the dirty light flag value.
  31291. */
  31292. get: function () {
  31293. return Material._LightDirtyFlag;
  31294. },
  31295. enumerable: true,
  31296. configurable: true
  31297. });
  31298. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31299. /**
  31300. * Returns the dirty fresnel flag value.
  31301. */
  31302. get: function () {
  31303. return Material._FresnelDirtyFlag;
  31304. },
  31305. enumerable: true,
  31306. configurable: true
  31307. });
  31308. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31309. /**
  31310. * Returns the dirty attributes flag value.
  31311. */
  31312. get: function () {
  31313. return Material._AttributesDirtyFlag;
  31314. },
  31315. enumerable: true,
  31316. configurable: true
  31317. });
  31318. Object.defineProperty(Material, "MiscDirtyFlag", {
  31319. /**
  31320. * Returns the dirty misc flag value.
  31321. */
  31322. get: function () {
  31323. return Material._MiscDirtyFlag;
  31324. },
  31325. enumerable: true,
  31326. configurable: true
  31327. });
  31328. Object.defineProperty(Material.prototype, "alpha", {
  31329. /**
  31330. * Gets the alpha value of the material.
  31331. */
  31332. get: function () {
  31333. return this._alpha;
  31334. },
  31335. /**
  31336. * Sets the alpha value of the material.
  31337. */
  31338. set: function (value) {
  31339. if (this._alpha === value) {
  31340. return;
  31341. }
  31342. this._alpha = value;
  31343. this.markAsDirty(Material.MiscDirtyFlag);
  31344. },
  31345. enumerable: true,
  31346. configurable: true
  31347. });
  31348. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31349. /**
  31350. * Gets the back-face culling state.
  31351. */
  31352. get: function () {
  31353. return this._backFaceCulling;
  31354. },
  31355. /**
  31356. * Sets the back-face culling state.
  31357. */
  31358. set: function (value) {
  31359. if (this._backFaceCulling === value) {
  31360. return;
  31361. }
  31362. this._backFaceCulling = value;
  31363. this.markAsDirty(Material.TextureDirtyFlag);
  31364. },
  31365. enumerable: true,
  31366. configurable: true
  31367. });
  31368. Object.defineProperty(Material.prototype, "onDispose", {
  31369. /**
  31370. * Called during a dispose event.
  31371. */
  31372. set: function (callback) {
  31373. if (this._onDisposeObserver) {
  31374. this.onDisposeObservable.remove(this._onDisposeObserver);
  31375. }
  31376. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31377. },
  31378. enumerable: true,
  31379. configurable: true
  31380. });
  31381. Object.defineProperty(Material.prototype, "onBind", {
  31382. /**
  31383. * Called during a bind event.
  31384. */
  31385. set: function (callback) {
  31386. if (this._onBindObserver) {
  31387. this.onBindObservable.remove(this._onBindObserver);
  31388. }
  31389. this._onBindObserver = this.onBindObservable.add(callback);
  31390. },
  31391. enumerable: true,
  31392. configurable: true
  31393. });
  31394. Object.defineProperty(Material.prototype, "alphaMode", {
  31395. /**
  31396. * Gets the value of the alpha mode.
  31397. */
  31398. get: function () {
  31399. return this._alphaMode;
  31400. },
  31401. /**
  31402. * Sets the value of the alpha mode.
  31403. */
  31404. set: function (value) {
  31405. if (this._alphaMode === value) {
  31406. return;
  31407. }
  31408. this._alphaMode = value;
  31409. this.markAsDirty(Material.TextureDirtyFlag);
  31410. },
  31411. enumerable: true,
  31412. configurable: true
  31413. });
  31414. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31415. /**
  31416. * Gets the depth pre-pass value.
  31417. */
  31418. get: function () {
  31419. return this._needDepthPrePass;
  31420. },
  31421. /**
  31422. * Sets the need depth pre-pass value.
  31423. */
  31424. set: function (value) {
  31425. if (this._needDepthPrePass === value) {
  31426. return;
  31427. }
  31428. this._needDepthPrePass = value;
  31429. if (this._needDepthPrePass) {
  31430. this.checkReadyOnEveryCall = true;
  31431. }
  31432. },
  31433. enumerable: true,
  31434. configurable: true
  31435. });
  31436. Object.defineProperty(Material.prototype, "fogEnabled", {
  31437. /**
  31438. * Gets the value of the fog enabled state.
  31439. */
  31440. get: function () {
  31441. return this._fogEnabled;
  31442. },
  31443. /**
  31444. * Sets the state for enabling fog.
  31445. */
  31446. set: function (value) {
  31447. if (this._fogEnabled === value) {
  31448. return;
  31449. }
  31450. this._fogEnabled = value;
  31451. this.markAsDirty(Material.MiscDirtyFlag);
  31452. },
  31453. enumerable: true,
  31454. configurable: true
  31455. });
  31456. Object.defineProperty(Material.prototype, "wireframe", {
  31457. /**
  31458. * Gets a value specifying if wireframe mode is enabled.
  31459. */
  31460. get: function () {
  31461. return this._fillMode === Material.WireFrameFillMode;
  31462. },
  31463. /**
  31464. * Sets the state of wireframe mode.
  31465. */
  31466. set: function (value) {
  31467. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31468. },
  31469. enumerable: true,
  31470. configurable: true
  31471. });
  31472. Object.defineProperty(Material.prototype, "pointsCloud", {
  31473. /**
  31474. * Gets the value specifying if point clouds are enabled.
  31475. */
  31476. get: function () {
  31477. return this._fillMode === Material.PointFillMode;
  31478. },
  31479. /**
  31480. * Sets the state of point cloud mode.
  31481. */
  31482. set: function (value) {
  31483. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31484. },
  31485. enumerable: true,
  31486. configurable: true
  31487. });
  31488. Object.defineProperty(Material.prototype, "fillMode", {
  31489. /**
  31490. * Gets the material fill mode.
  31491. */
  31492. get: function () {
  31493. return this._fillMode;
  31494. },
  31495. /**
  31496. * Sets the material fill mode.
  31497. */
  31498. set: function (value) {
  31499. if (this._fillMode === value) {
  31500. return;
  31501. }
  31502. this._fillMode = value;
  31503. this.markAsDirty(Material.MiscDirtyFlag);
  31504. },
  31505. enumerable: true,
  31506. configurable: true
  31507. });
  31508. /**
  31509. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31510. * subclasses should override adding information pertainent to themselves.
  31511. * @returns - String with material information.
  31512. */
  31513. Material.prototype.toString = function (fullDetails) {
  31514. var ret = "Name: " + this.name;
  31515. if (fullDetails) {
  31516. }
  31517. return ret;
  31518. };
  31519. /**
  31520. * Gets the class name of the material.
  31521. * @returns - String with the class name of the material.
  31522. */
  31523. Material.prototype.getClassName = function () {
  31524. return "Material";
  31525. };
  31526. Object.defineProperty(Material.prototype, "isFrozen", {
  31527. /**
  31528. * Specifies if updates for the material been locked.
  31529. */
  31530. get: function () {
  31531. return this.checkReadyOnlyOnce;
  31532. },
  31533. enumerable: true,
  31534. configurable: true
  31535. });
  31536. /**
  31537. * Locks updates for the material.
  31538. */
  31539. Material.prototype.freeze = function () {
  31540. this.checkReadyOnlyOnce = true;
  31541. };
  31542. /**
  31543. * Unlocks updates for the material.
  31544. */
  31545. Material.prototype.unfreeze = function () {
  31546. this.checkReadyOnlyOnce = false;
  31547. };
  31548. /**
  31549. * Specifies if the material is ready to be used.
  31550. * @param mesh - BJS mesh.
  31551. * @param useInstances - Specifies if instances should be used.
  31552. * @returns - Boolean indicating if the material is ready to be used.
  31553. */
  31554. Material.prototype.isReady = function (mesh, useInstances) {
  31555. return true;
  31556. };
  31557. /**
  31558. * Specifies that the submesh is ready to be used.
  31559. * @param mesh - BJS mesh.
  31560. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31561. * @param useInstances - Specifies that instances should be used.
  31562. * @returns - boolean indicating that the submesh is ready or not.
  31563. */
  31564. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31565. return false;
  31566. };
  31567. /**
  31568. * Returns the material effect.
  31569. * @returns - Nullable material effect.
  31570. */
  31571. Material.prototype.getEffect = function () {
  31572. return this._effect;
  31573. };
  31574. /**
  31575. * Returns the BJS scene.
  31576. * @returns - BJS Scene.
  31577. */
  31578. Material.prototype.getScene = function () {
  31579. return this._scene;
  31580. };
  31581. /**
  31582. * Specifies if the material will require alpha blending
  31583. * @returns - Boolean specifying if alpha blending is needed.
  31584. */
  31585. Material.prototype.needAlphaBlending = function () {
  31586. return (this.alpha < 1.0);
  31587. };
  31588. /**
  31589. * Specifies if the mesh will require alpha blending.
  31590. * @param mesh - BJS mesh.
  31591. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31592. */
  31593. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31594. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31595. };
  31596. /**
  31597. * Specifies if this material should be rendered in alpha test mode.
  31598. * @returns - Boolean specifying if an alpha test is needed.
  31599. */
  31600. Material.prototype.needAlphaTesting = function () {
  31601. return false;
  31602. };
  31603. /**
  31604. * Gets the texture used for the alpha test.
  31605. * @returns - Nullable alpha test texture.
  31606. */
  31607. Material.prototype.getAlphaTestTexture = function () {
  31608. return null;
  31609. };
  31610. /**
  31611. * Marks the material to indicate that it needs to be re-calculated.
  31612. */
  31613. Material.prototype.markDirty = function () {
  31614. this._wasPreviouslyReady = false;
  31615. };
  31616. Material.prototype._preBind = function (effect, overrideOrientation) {
  31617. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31618. var engine = this._scene.getEngine();
  31619. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31620. var reverse = orientation === Material.ClockWiseSideOrientation;
  31621. engine.enableEffect(effect ? effect : this._effect);
  31622. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31623. return reverse;
  31624. };
  31625. /**
  31626. * Binds the material to the mesh.
  31627. * @param world - World transformation matrix.
  31628. * @param mesh - Mesh to bind the material to.
  31629. */
  31630. Material.prototype.bind = function (world, mesh) {
  31631. };
  31632. /**
  31633. * Binds the submesh to the material.
  31634. * @param world - World transformation matrix.
  31635. * @param mesh - Mesh containing the submesh.
  31636. * @param subMesh - Submesh to bind the material to.
  31637. */
  31638. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31639. };
  31640. /**
  31641. * Binds the world matrix to the material.
  31642. * @param world - World transformation matrix.
  31643. */
  31644. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31645. };
  31646. /**
  31647. * Binds the scene's uniform buffer to the effect.
  31648. * @param effect - Effect to bind to the scene uniform buffer.
  31649. * @param sceneUbo - Scene uniform buffer.
  31650. */
  31651. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31652. sceneUbo.bindToEffect(effect, "Scene");
  31653. };
  31654. /**
  31655. * Binds the view matrix to the effect.
  31656. * @param effect - Effect to bind the view matrix to.
  31657. */
  31658. Material.prototype.bindView = function (effect) {
  31659. if (!this._useUBO) {
  31660. effect.setMatrix("view", this.getScene().getViewMatrix());
  31661. }
  31662. else {
  31663. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31664. }
  31665. };
  31666. /**
  31667. * Binds the view projection matrix to the effect.
  31668. * @param effect - Effect to bind the view projection matrix to.
  31669. */
  31670. Material.prototype.bindViewProjection = function (effect) {
  31671. if (!this._useUBO) {
  31672. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31673. }
  31674. else {
  31675. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31676. }
  31677. };
  31678. /**
  31679. * Specifies if material alpha testing should be turned on for the mesh.
  31680. * @param mesh - BJS mesh.
  31681. */
  31682. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31683. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31684. };
  31685. /**
  31686. * Processes to execute after binding the material to a mesh.
  31687. * @param mesh - BJS mesh.
  31688. */
  31689. Material.prototype._afterBind = function (mesh) {
  31690. this._scene._cachedMaterial = this;
  31691. if (mesh) {
  31692. this._scene._cachedVisibility = mesh.visibility;
  31693. }
  31694. else {
  31695. this._scene._cachedVisibility = 1;
  31696. }
  31697. if (mesh) {
  31698. this.onBindObservable.notifyObservers(mesh);
  31699. }
  31700. if (this.disableDepthWrite) {
  31701. var engine = this._scene.getEngine();
  31702. this._cachedDepthWriteState = engine.getDepthWrite();
  31703. engine.setDepthWrite(false);
  31704. }
  31705. };
  31706. /**
  31707. * Unbinds the material from the mesh.
  31708. */
  31709. Material.prototype.unbind = function () {
  31710. this.onUnBindObservable.notifyObservers(this);
  31711. if (this.disableDepthWrite) {
  31712. var engine = this._scene.getEngine();
  31713. engine.setDepthWrite(this._cachedDepthWriteState);
  31714. }
  31715. };
  31716. /**
  31717. * Gets the active textures from the material.
  31718. * @returns - Array of textures.
  31719. */
  31720. Material.prototype.getActiveTextures = function () {
  31721. return [];
  31722. };
  31723. /**
  31724. * Specifies if the material uses a texture.
  31725. * @param texture - Texture to check against the material.
  31726. * @returns - Boolean specifying if the material uses the texture.
  31727. */
  31728. Material.prototype.hasTexture = function (texture) {
  31729. return false;
  31730. };
  31731. /**
  31732. * Makes a duplicate of the material, and gives it a new name.
  31733. * @param name - Name to call the duplicated material.
  31734. * @returns - Nullable cloned material
  31735. */
  31736. Material.prototype.clone = function (name) {
  31737. return null;
  31738. };
  31739. /**
  31740. * Gets the meshes bound to the material.
  31741. * @returns - Array of meshes bound to the material.
  31742. */
  31743. Material.prototype.getBindedMeshes = function () {
  31744. var result = new Array();
  31745. for (var index = 0; index < this._scene.meshes.length; index++) {
  31746. var mesh = this._scene.meshes[index];
  31747. if (mesh.material === this) {
  31748. result.push(mesh);
  31749. }
  31750. }
  31751. return result;
  31752. };
  31753. /**
  31754. * Force shader compilation
  31755. * @param mesh - BJS mesh.
  31756. * @param onCompiled - function to execute once the material is compiled.
  31757. * @param options - options to pass to this function.
  31758. */
  31759. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31760. var _this = this;
  31761. var localOptions = __assign({ clipPlane: false }, options);
  31762. var subMesh = new BABYLON.BaseSubMesh();
  31763. var scene = this.getScene();
  31764. var checkReady = function () {
  31765. if (!_this._scene || !_this._scene.getEngine()) {
  31766. return;
  31767. }
  31768. if (subMesh._materialDefines) {
  31769. subMesh._materialDefines._renderId = -1;
  31770. }
  31771. var clipPlaneState = scene.clipPlane;
  31772. if (localOptions.clipPlane) {
  31773. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31774. }
  31775. if (_this.storeEffectOnSubMeshes) {
  31776. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31777. if (onCompiled) {
  31778. onCompiled(_this);
  31779. }
  31780. }
  31781. else {
  31782. setTimeout(checkReady, 16);
  31783. }
  31784. }
  31785. else {
  31786. if (_this.isReady(mesh)) {
  31787. if (onCompiled) {
  31788. onCompiled(_this);
  31789. }
  31790. }
  31791. else {
  31792. setTimeout(checkReady, 16);
  31793. }
  31794. }
  31795. if (localOptions.clipPlane) {
  31796. scene.clipPlane = clipPlaneState;
  31797. }
  31798. };
  31799. checkReady();
  31800. };
  31801. /**
  31802. * Force shader compilation.
  31803. * @param mesh The mesh that will use this material
  31804. * @param options Additional options for compiling the shaders
  31805. * @returns A promise that resolves when the compilation completes
  31806. */
  31807. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31808. var _this = this;
  31809. return new Promise(function (resolve) {
  31810. _this.forceCompilation(mesh, function () {
  31811. resolve();
  31812. }, options);
  31813. });
  31814. };
  31815. /**
  31816. * Marks a define in the material to indicate that it needs to be re-computed.
  31817. * @param flag - Material define flag.
  31818. */
  31819. Material.prototype.markAsDirty = function (flag) {
  31820. if (flag & Material.TextureDirtyFlag) {
  31821. this._markAllSubMeshesAsTexturesDirty();
  31822. }
  31823. if (flag & Material.LightDirtyFlag) {
  31824. this._markAllSubMeshesAsLightsDirty();
  31825. }
  31826. if (flag & Material.FresnelDirtyFlag) {
  31827. this._markAllSubMeshesAsFresnelDirty();
  31828. }
  31829. if (flag & Material.AttributesDirtyFlag) {
  31830. this._markAllSubMeshesAsAttributesDirty();
  31831. }
  31832. if (flag & Material.MiscDirtyFlag) {
  31833. this._markAllSubMeshesAsMiscDirty();
  31834. }
  31835. this.getScene().resetCachedMaterial();
  31836. };
  31837. /**
  31838. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31839. * @param func - function which checks material defines against the submeshes.
  31840. */
  31841. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31842. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31843. var mesh = _a[_i];
  31844. if (!mesh.subMeshes) {
  31845. continue;
  31846. }
  31847. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31848. var subMesh = _c[_b];
  31849. if (subMesh.getMaterial() !== this) {
  31850. continue;
  31851. }
  31852. if (!subMesh._materialDefines) {
  31853. continue;
  31854. }
  31855. func(subMesh._materialDefines);
  31856. }
  31857. }
  31858. };
  31859. /**
  31860. * Indicates that image processing needs to be re-calculated for all submeshes.
  31861. */
  31862. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31863. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31864. };
  31865. /**
  31866. * Indicates that textures need to be re-calculated for all submeshes.
  31867. */
  31868. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31869. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31870. };
  31871. /**
  31872. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31873. */
  31874. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31875. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31876. };
  31877. /**
  31878. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31879. */
  31880. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31881. this._markAllSubMeshesAsDirty(function (defines) {
  31882. defines.markAsFresnelDirty();
  31883. defines.markAsMiscDirty();
  31884. });
  31885. };
  31886. /**
  31887. * Indicates that lights need to be re-calculated for all submeshes.
  31888. */
  31889. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31890. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31891. };
  31892. /**
  31893. * Indicates that attributes need to be re-calculated for all submeshes.
  31894. */
  31895. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31896. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31897. };
  31898. /**
  31899. * Indicates that misc needs to be re-calculated for all submeshes.
  31900. */
  31901. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31902. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31903. };
  31904. /**
  31905. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31906. */
  31907. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31908. this._markAllSubMeshesAsDirty(function (defines) {
  31909. defines.markAsTexturesDirty();
  31910. defines.markAsMiscDirty();
  31911. });
  31912. };
  31913. /**
  31914. * Disposes the material.
  31915. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31916. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31917. */
  31918. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31919. // Animations
  31920. this.getScene().stopAnimation(this);
  31921. this.getScene().freeProcessedMaterials();
  31922. // Remove from scene
  31923. var index = this._scene.materials.indexOf(this);
  31924. if (index >= 0) {
  31925. this._scene.materials.splice(index, 1);
  31926. }
  31927. // Remove from meshes
  31928. for (index = 0; index < this._scene.meshes.length; index++) {
  31929. var mesh = this._scene.meshes[index];
  31930. if (mesh.material === this) {
  31931. mesh.material = null;
  31932. if (mesh.geometry) {
  31933. var geometry = (mesh.geometry);
  31934. if (this.storeEffectOnSubMeshes) {
  31935. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31936. var subMesh = _a[_i];
  31937. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31938. if (forceDisposeEffect && subMesh._materialEffect) {
  31939. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31940. }
  31941. }
  31942. }
  31943. else {
  31944. geometry._releaseVertexArrayObject(this._effect);
  31945. }
  31946. }
  31947. }
  31948. }
  31949. this._uniformBuffer.dispose();
  31950. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31951. if (forceDisposeEffect && this._effect) {
  31952. if (!this.storeEffectOnSubMeshes) {
  31953. this._scene.getEngine()._releaseEffect(this._effect);
  31954. }
  31955. this._effect = null;
  31956. }
  31957. // Callback
  31958. this.onDisposeObservable.notifyObservers(this);
  31959. this.onDisposeObservable.clear();
  31960. this.onBindObservable.clear();
  31961. this.onUnBindObservable.clear();
  31962. };
  31963. /**
  31964. * Serializes this material.
  31965. * @returns - serialized material object.
  31966. */
  31967. Material.prototype.serialize = function () {
  31968. return BABYLON.SerializationHelper.Serialize(this);
  31969. };
  31970. /**
  31971. * Creates a MultiMaterial from parse MultiMaterial data.
  31972. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31973. * @param scene - BJS scene.
  31974. * @returns - MultiMaterial.
  31975. */
  31976. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31977. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31978. multiMaterial.id = parsedMultiMaterial.id;
  31979. if (BABYLON.Tags) {
  31980. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31981. }
  31982. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31983. var subMatId = parsedMultiMaterial.materials[matIndex];
  31984. if (subMatId) {
  31985. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31986. }
  31987. else {
  31988. multiMaterial.subMaterials.push(null);
  31989. }
  31990. }
  31991. return multiMaterial;
  31992. };
  31993. /**
  31994. * Creates a material from parsed material data.
  31995. * @param parsedMaterial - Parsed material data.
  31996. * @param scene - BJS scene.
  31997. * @param rootUrl - Root URL containing the material information.
  31998. * @returns - Parsed material.
  31999. */
  32000. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  32001. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  32002. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  32003. }
  32004. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  32005. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  32006. if (!BABYLON.LegacyPBRMaterial) {
  32007. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  32008. return;
  32009. }
  32010. }
  32011. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  32012. return materialType.Parse(parsedMaterial, scene, rootUrl);
  32013. ;
  32014. };
  32015. // Triangle views
  32016. Material._TriangleFillMode = 0;
  32017. Material._WireFrameFillMode = 1;
  32018. Material._PointFillMode = 2;
  32019. // Draw modes
  32020. Material._PointListDrawMode = 3;
  32021. Material._LineListDrawMode = 4;
  32022. Material._LineLoopDrawMode = 5;
  32023. Material._LineStripDrawMode = 6;
  32024. Material._TriangleStripDrawMode = 7;
  32025. Material._TriangleFanDrawMode = 8;
  32026. /**
  32027. * Stores the clock-wise side orientation.
  32028. */
  32029. Material._ClockWiseSideOrientation = 0;
  32030. /**
  32031. * Stores the counter clock-wise side orientation.
  32032. */
  32033. Material._CounterClockWiseSideOrientation = 1;
  32034. /**
  32035. * The dirty texture flag value.
  32036. */
  32037. Material._TextureDirtyFlag = 1;
  32038. /**
  32039. * The dirty light flag value.
  32040. */
  32041. Material._LightDirtyFlag = 2;
  32042. /**
  32043. * The dirty fresnel flag value.
  32044. */
  32045. Material._FresnelDirtyFlag = 4;
  32046. /**
  32047. * The dirty attribute flag value.
  32048. */
  32049. Material._AttributesDirtyFlag = 8;
  32050. /**
  32051. * The dirty misc flag value.
  32052. */
  32053. Material._MiscDirtyFlag = 16;
  32054. __decorate([
  32055. BABYLON.serialize()
  32056. ], Material.prototype, "id", void 0);
  32057. __decorate([
  32058. BABYLON.serialize()
  32059. ], Material.prototype, "name", void 0);
  32060. __decorate([
  32061. BABYLON.serialize()
  32062. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  32063. __decorate([
  32064. BABYLON.serialize()
  32065. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  32066. __decorate([
  32067. BABYLON.serialize()
  32068. ], Material.prototype, "state", void 0);
  32069. __decorate([
  32070. BABYLON.serialize("alpha")
  32071. ], Material.prototype, "_alpha", void 0);
  32072. __decorate([
  32073. BABYLON.serialize("backFaceCulling")
  32074. ], Material.prototype, "_backFaceCulling", void 0);
  32075. __decorate([
  32076. BABYLON.serialize()
  32077. ], Material.prototype, "sideOrientation", void 0);
  32078. __decorate([
  32079. BABYLON.serialize("alphaMode")
  32080. ], Material.prototype, "_alphaMode", void 0);
  32081. __decorate([
  32082. BABYLON.serialize()
  32083. ], Material.prototype, "_needDepthPrePass", void 0);
  32084. __decorate([
  32085. BABYLON.serialize()
  32086. ], Material.prototype, "disableDepthWrite", void 0);
  32087. __decorate([
  32088. BABYLON.serialize()
  32089. ], Material.prototype, "forceDepthWrite", void 0);
  32090. __decorate([
  32091. BABYLON.serialize()
  32092. ], Material.prototype, "separateCullingPass", void 0);
  32093. __decorate([
  32094. BABYLON.serialize("fogEnabled")
  32095. ], Material.prototype, "_fogEnabled", void 0);
  32096. __decorate([
  32097. BABYLON.serialize()
  32098. ], Material.prototype, "pointSize", void 0);
  32099. __decorate([
  32100. BABYLON.serialize()
  32101. ], Material.prototype, "zOffset", void 0);
  32102. __decorate([
  32103. BABYLON.serialize()
  32104. ], Material.prototype, "wireframe", null);
  32105. __decorate([
  32106. BABYLON.serialize()
  32107. ], Material.prototype, "pointsCloud", null);
  32108. __decorate([
  32109. BABYLON.serialize()
  32110. ], Material.prototype, "fillMode", null);
  32111. return Material;
  32112. }());
  32113. BABYLON.Material = Material;
  32114. })(BABYLON || (BABYLON = {}));
  32115. //# sourceMappingURL=babylon.material.js.map
  32116. var BABYLON;
  32117. (function (BABYLON) {
  32118. var UniformBuffer = /** @class */ (function () {
  32119. /**
  32120. * Uniform buffer objects.
  32121. *
  32122. * Handles blocks of uniform on the GPU.
  32123. *
  32124. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  32125. *
  32126. * For more information, please refer to :
  32127. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  32128. */
  32129. function UniformBuffer(engine, data, dynamic) {
  32130. this._engine = engine;
  32131. this._noUBO = !engine.supportsUniformBuffers;
  32132. this._dynamic = dynamic;
  32133. this._data = data || [];
  32134. this._uniformLocations = {};
  32135. this._uniformSizes = {};
  32136. this._uniformLocationPointer = 0;
  32137. this._needSync = false;
  32138. if (this._noUBO) {
  32139. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  32140. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  32141. this.updateFloat = this._updateFloatForEffect;
  32142. this.updateFloat2 = this._updateFloat2ForEffect;
  32143. this.updateFloat3 = this._updateFloat3ForEffect;
  32144. this.updateFloat4 = this._updateFloat4ForEffect;
  32145. this.updateMatrix = this._updateMatrixForEffect;
  32146. this.updateVector3 = this._updateVector3ForEffect;
  32147. this.updateVector4 = this._updateVector4ForEffect;
  32148. this.updateColor3 = this._updateColor3ForEffect;
  32149. this.updateColor4 = this._updateColor4ForEffect;
  32150. }
  32151. else {
  32152. this._engine._uniformBuffers.push(this);
  32153. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  32154. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  32155. this.updateFloat = this._updateFloatForUniform;
  32156. this.updateFloat2 = this._updateFloat2ForUniform;
  32157. this.updateFloat3 = this._updateFloat3ForUniform;
  32158. this.updateFloat4 = this._updateFloat4ForUniform;
  32159. this.updateMatrix = this._updateMatrixForUniform;
  32160. this.updateVector3 = this._updateVector3ForUniform;
  32161. this.updateVector4 = this._updateVector4ForUniform;
  32162. this.updateColor3 = this._updateColor3ForUniform;
  32163. this.updateColor4 = this._updateColor4ForUniform;
  32164. }
  32165. }
  32166. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32167. // Properties
  32168. /**
  32169. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32170. * or just falling back on setUniformXXX calls.
  32171. */
  32172. get: function () {
  32173. return !this._noUBO;
  32174. },
  32175. enumerable: true,
  32176. configurable: true
  32177. });
  32178. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32179. /**
  32180. * Indicates if the WebGL underlying uniform buffer is in sync
  32181. * with the javascript cache data.
  32182. */
  32183. get: function () {
  32184. return !this._needSync;
  32185. },
  32186. enumerable: true,
  32187. configurable: true
  32188. });
  32189. /**
  32190. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32191. * Also, a dynamic UniformBuffer will disable cache verification and always
  32192. * update the underlying WebGL uniform buffer to the GPU.
  32193. */
  32194. UniformBuffer.prototype.isDynamic = function () {
  32195. return this._dynamic !== undefined;
  32196. };
  32197. /**
  32198. * The data cache on JS side.
  32199. */
  32200. UniformBuffer.prototype.getData = function () {
  32201. return this._bufferData;
  32202. };
  32203. /**
  32204. * The underlying WebGL Uniform buffer.
  32205. */
  32206. UniformBuffer.prototype.getBuffer = function () {
  32207. return this._buffer;
  32208. };
  32209. /**
  32210. * std140 layout specifies how to align data within an UBO structure.
  32211. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32212. * for specs.
  32213. */
  32214. UniformBuffer.prototype._fillAlignment = function (size) {
  32215. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32216. // and 4x4 matrices
  32217. // TODO : change if other types are used
  32218. var alignment;
  32219. if (size <= 2) {
  32220. alignment = size;
  32221. }
  32222. else {
  32223. alignment = 4;
  32224. }
  32225. if ((this._uniformLocationPointer % alignment) !== 0) {
  32226. var oldPointer = this._uniformLocationPointer;
  32227. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32228. var diff = this._uniformLocationPointer - oldPointer;
  32229. for (var i = 0; i < diff; i++) {
  32230. this._data.push(0);
  32231. }
  32232. }
  32233. };
  32234. /**
  32235. * Adds an uniform in the buffer.
  32236. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32237. * for the layout to be correct !
  32238. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32239. * @param {number|number[]} size Data size, or data directly.
  32240. */
  32241. UniformBuffer.prototype.addUniform = function (name, size) {
  32242. if (this._noUBO) {
  32243. return;
  32244. }
  32245. if (this._uniformLocations[name] !== undefined) {
  32246. // Already existing uniform
  32247. return;
  32248. }
  32249. // This function must be called in the order of the shader layout !
  32250. // size can be the size of the uniform, or data directly
  32251. var data;
  32252. if (size instanceof Array) {
  32253. data = size;
  32254. size = data.length;
  32255. }
  32256. else {
  32257. size = size;
  32258. data = [];
  32259. // Fill with zeros
  32260. for (var i = 0; i < size; i++) {
  32261. data.push(0);
  32262. }
  32263. }
  32264. this._fillAlignment(size);
  32265. this._uniformSizes[name] = size;
  32266. this._uniformLocations[name] = this._uniformLocationPointer;
  32267. this._uniformLocationPointer += size;
  32268. for (var i = 0; i < size; i++) {
  32269. this._data.push(data[i]);
  32270. }
  32271. this._needSync = true;
  32272. };
  32273. /**
  32274. * Wrapper for addUniform.
  32275. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32276. * @param {Matrix} mat A 4x4 matrix.
  32277. */
  32278. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32279. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32280. };
  32281. /**
  32282. * Wrapper for addUniform.
  32283. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32284. * @param {number} x
  32285. * @param {number} y
  32286. */
  32287. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32288. var temp = [x, y];
  32289. this.addUniform(name, temp);
  32290. };
  32291. /**
  32292. * Wrapper for addUniform.
  32293. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32294. * @param {number} x
  32295. * @param {number} y
  32296. * @param {number} z
  32297. */
  32298. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32299. var temp = [x, y, z];
  32300. this.addUniform(name, temp);
  32301. };
  32302. /**
  32303. * Wrapper for addUniform.
  32304. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32305. * @param {Color3} color
  32306. */
  32307. UniformBuffer.prototype.addColor3 = function (name, color) {
  32308. var temp = new Array();
  32309. color.toArray(temp);
  32310. this.addUniform(name, temp);
  32311. };
  32312. /**
  32313. * Wrapper for addUniform.
  32314. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32315. * @param {Color3} color
  32316. * @param {number} alpha
  32317. */
  32318. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32319. var temp = new Array();
  32320. color.toArray(temp);
  32321. temp.push(alpha);
  32322. this.addUniform(name, temp);
  32323. };
  32324. /**
  32325. * Wrapper for addUniform.
  32326. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32327. * @param {Vector3} vector
  32328. */
  32329. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32330. var temp = new Array();
  32331. vector.toArray(temp);
  32332. this.addUniform(name, temp);
  32333. };
  32334. /**
  32335. * Wrapper for addUniform.
  32336. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32337. */
  32338. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32339. this.addUniform(name, 12);
  32340. };
  32341. /**
  32342. * Wrapper for addUniform.
  32343. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32344. */
  32345. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32346. this.addUniform(name, 8);
  32347. };
  32348. /**
  32349. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32350. */
  32351. UniformBuffer.prototype.create = function () {
  32352. if (this._noUBO) {
  32353. return;
  32354. }
  32355. if (this._buffer) {
  32356. return; // nothing to do
  32357. }
  32358. // See spec, alignment must be filled as a vec4
  32359. this._fillAlignment(4);
  32360. this._bufferData = new Float32Array(this._data);
  32361. this._rebuild();
  32362. this._needSync = true;
  32363. };
  32364. UniformBuffer.prototype._rebuild = function () {
  32365. if (this._noUBO) {
  32366. return;
  32367. }
  32368. if (this._dynamic) {
  32369. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32370. }
  32371. else {
  32372. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32373. }
  32374. };
  32375. /**
  32376. * Updates the WebGL Uniform Buffer on the GPU.
  32377. * If the `dynamic` flag is set to true, no cache comparison is done.
  32378. * Otherwise, the buffer will be updated only if the cache differs.
  32379. */
  32380. UniformBuffer.prototype.update = function () {
  32381. if (!this._buffer) {
  32382. this.create();
  32383. return;
  32384. }
  32385. if (!this._dynamic && !this._needSync) {
  32386. return;
  32387. }
  32388. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32389. this._needSync = false;
  32390. };
  32391. /**
  32392. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32393. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32394. * @param {number[]|Float32Array} data Flattened data
  32395. * @param {number} size Size of the data.
  32396. */
  32397. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32398. var location = this._uniformLocations[uniformName];
  32399. if (location === undefined) {
  32400. if (this._buffer) {
  32401. // Cannot add an uniform if the buffer is already created
  32402. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32403. return;
  32404. }
  32405. this.addUniform(uniformName, size);
  32406. location = this._uniformLocations[uniformName];
  32407. }
  32408. if (!this._buffer) {
  32409. this.create();
  32410. }
  32411. if (!this._dynamic) {
  32412. // Cache for static uniform buffers
  32413. var changed = false;
  32414. for (var i = 0; i < size; i++) {
  32415. if (this._bufferData[location + i] !== data[i]) {
  32416. changed = true;
  32417. this._bufferData[location + i] = data[i];
  32418. }
  32419. }
  32420. this._needSync = this._needSync || changed;
  32421. }
  32422. else {
  32423. // No cache for dynamic
  32424. for (var i = 0; i < size; i++) {
  32425. this._bufferData[location + i] = data[i];
  32426. }
  32427. }
  32428. };
  32429. // Update methods
  32430. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32431. // To match std140, matrix must be realigned
  32432. for (var i = 0; i < 3; i++) {
  32433. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32434. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32435. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32436. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32437. }
  32438. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32439. };
  32440. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32441. this._currentEffect.setMatrix3x3(name, matrix);
  32442. };
  32443. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32444. this._currentEffect.setMatrix2x2(name, matrix);
  32445. };
  32446. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32447. // To match std140, matrix must be realigned
  32448. for (var i = 0; i < 2; i++) {
  32449. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32450. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32451. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32452. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32453. }
  32454. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32455. };
  32456. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32457. this._currentEffect.setFloat(name, x);
  32458. };
  32459. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32460. UniformBuffer._tempBuffer[0] = x;
  32461. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32462. };
  32463. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32464. if (suffix === void 0) { suffix = ""; }
  32465. this._currentEffect.setFloat2(name + suffix, x, y);
  32466. };
  32467. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32468. if (suffix === void 0) { suffix = ""; }
  32469. UniformBuffer._tempBuffer[0] = x;
  32470. UniformBuffer._tempBuffer[1] = y;
  32471. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32472. };
  32473. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32474. if (suffix === void 0) { suffix = ""; }
  32475. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32476. };
  32477. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32478. if (suffix === void 0) { suffix = ""; }
  32479. UniformBuffer._tempBuffer[0] = x;
  32480. UniformBuffer._tempBuffer[1] = y;
  32481. UniformBuffer._tempBuffer[2] = z;
  32482. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32483. };
  32484. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32485. if (suffix === void 0) { suffix = ""; }
  32486. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32487. };
  32488. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32489. if (suffix === void 0) { suffix = ""; }
  32490. UniformBuffer._tempBuffer[0] = x;
  32491. UniformBuffer._tempBuffer[1] = y;
  32492. UniformBuffer._tempBuffer[2] = z;
  32493. UniformBuffer._tempBuffer[3] = w;
  32494. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32495. };
  32496. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32497. this._currentEffect.setMatrix(name, mat);
  32498. };
  32499. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32500. this.updateUniform(name, mat.toArray(), 16);
  32501. };
  32502. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32503. this._currentEffect.setVector3(name, vector);
  32504. };
  32505. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32506. vector.toArray(UniformBuffer._tempBuffer);
  32507. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32508. };
  32509. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32510. this._currentEffect.setVector4(name, vector);
  32511. };
  32512. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32513. vector.toArray(UniformBuffer._tempBuffer);
  32514. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32515. };
  32516. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32517. if (suffix === void 0) { suffix = ""; }
  32518. this._currentEffect.setColor3(name + suffix, color);
  32519. };
  32520. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32521. if (suffix === void 0) { suffix = ""; }
  32522. color.toArray(UniformBuffer._tempBuffer);
  32523. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32524. };
  32525. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32526. if (suffix === void 0) { suffix = ""; }
  32527. this._currentEffect.setColor4(name + suffix, color, alpha);
  32528. };
  32529. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32530. if (suffix === void 0) { suffix = ""; }
  32531. color.toArray(UniformBuffer._tempBuffer);
  32532. UniformBuffer._tempBuffer[3] = alpha;
  32533. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32534. };
  32535. /**
  32536. * Sets a sampler uniform on the effect.
  32537. * @param {string} name Name of the sampler.
  32538. * @param {Texture} texture
  32539. */
  32540. UniformBuffer.prototype.setTexture = function (name, texture) {
  32541. this._currentEffect.setTexture(name, texture);
  32542. };
  32543. /**
  32544. * Directly updates the value of the uniform in the cache AND on the GPU.
  32545. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32546. * @param {number[]|Float32Array} data Flattened data
  32547. */
  32548. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32549. this.updateUniform(uniformName, data, data.length);
  32550. this.update();
  32551. };
  32552. /**
  32553. * Binds this uniform buffer to an effect.
  32554. * @param {Effect} effect
  32555. * @param {string} name Name of the uniform block in the shader.
  32556. */
  32557. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32558. this._currentEffect = effect;
  32559. if (this._noUBO || !this._buffer) {
  32560. return;
  32561. }
  32562. effect.bindUniformBuffer(this._buffer, name);
  32563. };
  32564. /**
  32565. * Disposes the uniform buffer.
  32566. */
  32567. UniformBuffer.prototype.dispose = function () {
  32568. if (this._noUBO) {
  32569. return;
  32570. }
  32571. var index = this._engine._uniformBuffers.indexOf(this);
  32572. if (index !== -1) {
  32573. this._engine._uniformBuffers.splice(index, 1);
  32574. }
  32575. if (!this._buffer) {
  32576. return;
  32577. }
  32578. if (this._engine._releaseBuffer(this._buffer)) {
  32579. this._buffer = null;
  32580. }
  32581. };
  32582. // Pool for avoiding memory leaks
  32583. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32584. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32585. return UniformBuffer;
  32586. }());
  32587. BABYLON.UniformBuffer = UniformBuffer;
  32588. })(BABYLON || (BABYLON = {}));
  32589. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32590. var BABYLON;
  32591. (function (BABYLON) {
  32592. var VertexData = /** @class */ (function () {
  32593. function VertexData() {
  32594. }
  32595. VertexData.prototype.set = function (data, kind) {
  32596. switch (kind) {
  32597. case BABYLON.VertexBuffer.PositionKind:
  32598. this.positions = data;
  32599. break;
  32600. case BABYLON.VertexBuffer.NormalKind:
  32601. this.normals = data;
  32602. break;
  32603. case BABYLON.VertexBuffer.TangentKind:
  32604. this.tangents = data;
  32605. break;
  32606. case BABYLON.VertexBuffer.UVKind:
  32607. this.uvs = data;
  32608. break;
  32609. case BABYLON.VertexBuffer.UV2Kind:
  32610. this.uvs2 = data;
  32611. break;
  32612. case BABYLON.VertexBuffer.UV3Kind:
  32613. this.uvs3 = data;
  32614. break;
  32615. case BABYLON.VertexBuffer.UV4Kind:
  32616. this.uvs4 = data;
  32617. break;
  32618. case BABYLON.VertexBuffer.UV5Kind:
  32619. this.uvs5 = data;
  32620. break;
  32621. case BABYLON.VertexBuffer.UV6Kind:
  32622. this.uvs6 = data;
  32623. break;
  32624. case BABYLON.VertexBuffer.ColorKind:
  32625. this.colors = data;
  32626. break;
  32627. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32628. this.matricesIndices = data;
  32629. break;
  32630. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32631. this.matricesWeights = data;
  32632. break;
  32633. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32634. this.matricesIndicesExtra = data;
  32635. break;
  32636. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32637. this.matricesWeightsExtra = data;
  32638. break;
  32639. }
  32640. };
  32641. /**
  32642. * Associates the vertexData to the passed Mesh.
  32643. * Sets it as updatable or not (default `false`).
  32644. * Returns the VertexData.
  32645. */
  32646. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32647. this._applyTo(mesh, updatable);
  32648. return this;
  32649. };
  32650. /**
  32651. * Associates the vertexData to the passed Geometry.
  32652. * Sets it as updatable or not (default `false`).
  32653. * Returns the VertexData.
  32654. */
  32655. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32656. this._applyTo(geometry, updatable);
  32657. return this;
  32658. };
  32659. /**
  32660. * Updates the associated mesh.
  32661. * Returns the VertexData.
  32662. */
  32663. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32664. this._update(mesh);
  32665. return this;
  32666. };
  32667. /**
  32668. * Updates the associated geometry.
  32669. * Returns the VertexData.
  32670. */
  32671. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32672. this._update(geometry);
  32673. return this;
  32674. };
  32675. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32676. if (updatable === void 0) { updatable = false; }
  32677. if (this.positions) {
  32678. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32679. }
  32680. if (this.normals) {
  32681. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32682. }
  32683. if (this.tangents) {
  32684. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32685. }
  32686. if (this.uvs) {
  32687. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32688. }
  32689. if (this.uvs2) {
  32690. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32691. }
  32692. if (this.uvs3) {
  32693. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32694. }
  32695. if (this.uvs4) {
  32696. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32697. }
  32698. if (this.uvs5) {
  32699. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32700. }
  32701. if (this.uvs6) {
  32702. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32703. }
  32704. if (this.colors) {
  32705. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32706. }
  32707. if (this.matricesIndices) {
  32708. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32709. }
  32710. if (this.matricesWeights) {
  32711. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32712. }
  32713. if (this.matricesIndicesExtra) {
  32714. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32715. }
  32716. if (this.matricesWeightsExtra) {
  32717. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32718. }
  32719. if (this.indices) {
  32720. meshOrGeometry.setIndices(this.indices, null, updatable);
  32721. }
  32722. return this;
  32723. };
  32724. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32725. if (this.positions) {
  32726. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32727. }
  32728. if (this.normals) {
  32729. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32730. }
  32731. if (this.tangents) {
  32732. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32733. }
  32734. if (this.uvs) {
  32735. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32736. }
  32737. if (this.uvs2) {
  32738. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32739. }
  32740. if (this.uvs3) {
  32741. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32742. }
  32743. if (this.uvs4) {
  32744. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32745. }
  32746. if (this.uvs5) {
  32747. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32748. }
  32749. if (this.uvs6) {
  32750. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32751. }
  32752. if (this.colors) {
  32753. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32754. }
  32755. if (this.matricesIndices) {
  32756. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32757. }
  32758. if (this.matricesWeights) {
  32759. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32760. }
  32761. if (this.matricesIndicesExtra) {
  32762. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32763. }
  32764. if (this.matricesWeightsExtra) {
  32765. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32766. }
  32767. if (this.indices) {
  32768. meshOrGeometry.setIndices(this.indices, null);
  32769. }
  32770. return this;
  32771. };
  32772. /**
  32773. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32774. * Returns the VertexData.
  32775. */
  32776. VertexData.prototype.transform = function (matrix) {
  32777. var transformed = BABYLON.Vector3.Zero();
  32778. var index;
  32779. if (this.positions) {
  32780. var position = BABYLON.Vector3.Zero();
  32781. for (index = 0; index < this.positions.length; index += 3) {
  32782. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32783. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32784. this.positions[index] = transformed.x;
  32785. this.positions[index + 1] = transformed.y;
  32786. this.positions[index + 2] = transformed.z;
  32787. }
  32788. }
  32789. if (this.normals) {
  32790. var normal = BABYLON.Vector3.Zero();
  32791. for (index = 0; index < this.normals.length; index += 3) {
  32792. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32793. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32794. this.normals[index] = transformed.x;
  32795. this.normals[index + 1] = transformed.y;
  32796. this.normals[index + 2] = transformed.z;
  32797. }
  32798. }
  32799. if (this.tangents) {
  32800. var tangent = BABYLON.Vector4.Zero();
  32801. var tangentTransformed = BABYLON.Vector4.Zero();
  32802. for (index = 0; index < this.tangents.length; index += 4) {
  32803. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32804. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32805. this.tangents[index] = tangentTransformed.x;
  32806. this.tangents[index + 1] = tangentTransformed.y;
  32807. this.tangents[index + 2] = tangentTransformed.z;
  32808. this.tangents[index + 3] = tangentTransformed.w;
  32809. }
  32810. }
  32811. return this;
  32812. };
  32813. /**
  32814. * Merges the passed VertexData into the current one.
  32815. * Returns the modified VertexData.
  32816. */
  32817. VertexData.prototype.merge = function (other) {
  32818. this._validate();
  32819. other._validate();
  32820. if (!this.normals !== !other.normals ||
  32821. !this.tangents !== !other.tangents ||
  32822. !this.uvs !== !other.uvs ||
  32823. !this.uvs2 !== !other.uvs2 ||
  32824. !this.uvs3 !== !other.uvs3 ||
  32825. !this.uvs4 !== !other.uvs4 ||
  32826. !this.uvs5 !== !other.uvs5 ||
  32827. !this.uvs6 !== !other.uvs6 ||
  32828. !this.colors !== !other.colors ||
  32829. !this.matricesIndices !== !other.matricesIndices ||
  32830. !this.matricesWeights !== !other.matricesWeights ||
  32831. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32832. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32833. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32834. }
  32835. if (other.indices) {
  32836. if (!this.indices) {
  32837. this.indices = [];
  32838. }
  32839. var offset = this.positions ? this.positions.length / 3 : 0;
  32840. for (var index = 0; index < other.indices.length; index++) {
  32841. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32842. this.indices.push(other.indices[index] + offset);
  32843. }
  32844. }
  32845. this.positions = this._mergeElement(this.positions, other.positions);
  32846. this.normals = this._mergeElement(this.normals, other.normals);
  32847. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32848. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32849. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32850. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32851. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32852. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32853. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32854. this.colors = this._mergeElement(this.colors, other.colors);
  32855. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32856. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32857. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32858. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32859. return this;
  32860. };
  32861. VertexData.prototype._mergeElement = function (source, other) {
  32862. if (!source) {
  32863. return other;
  32864. }
  32865. if (!other) {
  32866. return source;
  32867. }
  32868. var len = other.length + source.length;
  32869. var isSrcTypedArray = source instanceof Float32Array;
  32870. var isOthTypedArray = other instanceof Float32Array;
  32871. // use non-loop method when the source is Float32Array
  32872. if (isSrcTypedArray) {
  32873. var ret32 = new Float32Array(len);
  32874. ret32.set(source);
  32875. ret32.set(other, source.length);
  32876. return ret32;
  32877. // source is number[], when other is also use concat
  32878. }
  32879. else if (!isOthTypedArray) {
  32880. return source.concat(other);
  32881. // source is a number[], but other is a Float32Array, loop required
  32882. }
  32883. else {
  32884. var ret = source.slice(0); // copy source to a separate array
  32885. for (var i = 0, len = other.length; i < len; i++) {
  32886. ret.push(other[i]);
  32887. }
  32888. return ret;
  32889. }
  32890. };
  32891. VertexData.prototype._validate = function () {
  32892. if (!this.positions) {
  32893. throw new Error("Positions are required");
  32894. }
  32895. var getElementCount = function (kind, values) {
  32896. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32897. if ((values.length % stride) !== 0) {
  32898. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32899. }
  32900. return values.length / stride;
  32901. };
  32902. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32903. var validateElementCount = function (kind, values) {
  32904. var elementCount = getElementCount(kind, values);
  32905. if (elementCount !== positionsElementCount) {
  32906. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32907. }
  32908. };
  32909. if (this.normals)
  32910. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32911. if (this.tangents)
  32912. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32913. if (this.uvs)
  32914. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32915. if (this.uvs2)
  32916. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32917. if (this.uvs3)
  32918. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32919. if (this.uvs4)
  32920. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32921. if (this.uvs5)
  32922. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32923. if (this.uvs6)
  32924. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32925. if (this.colors)
  32926. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32927. if (this.matricesIndices)
  32928. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32929. if (this.matricesWeights)
  32930. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32931. if (this.matricesIndicesExtra)
  32932. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32933. if (this.matricesWeightsExtra)
  32934. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32935. };
  32936. /**
  32937. * Serializes the VertexData.
  32938. * Returns a serialized object.
  32939. */
  32940. VertexData.prototype.serialize = function () {
  32941. var serializationObject = this.serialize();
  32942. if (this.positions) {
  32943. serializationObject.positions = this.positions;
  32944. }
  32945. if (this.normals) {
  32946. serializationObject.normals = this.normals;
  32947. }
  32948. if (this.tangents) {
  32949. serializationObject.tangents = this.tangents;
  32950. }
  32951. if (this.uvs) {
  32952. serializationObject.uvs = this.uvs;
  32953. }
  32954. if (this.uvs2) {
  32955. serializationObject.uvs2 = this.uvs2;
  32956. }
  32957. if (this.uvs3) {
  32958. serializationObject.uvs3 = this.uvs3;
  32959. }
  32960. if (this.uvs4) {
  32961. serializationObject.uvs4 = this.uvs4;
  32962. }
  32963. if (this.uvs5) {
  32964. serializationObject.uvs5 = this.uvs5;
  32965. }
  32966. if (this.uvs6) {
  32967. serializationObject.uvs6 = this.uvs6;
  32968. }
  32969. if (this.colors) {
  32970. serializationObject.colors = this.colors;
  32971. }
  32972. if (this.matricesIndices) {
  32973. serializationObject.matricesIndices = this.matricesIndices;
  32974. serializationObject.matricesIndices._isExpanded = true;
  32975. }
  32976. if (this.matricesWeights) {
  32977. serializationObject.matricesWeights = this.matricesWeights;
  32978. }
  32979. if (this.matricesIndicesExtra) {
  32980. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32981. serializationObject.matricesIndicesExtra._isExpanded = true;
  32982. }
  32983. if (this.matricesWeightsExtra) {
  32984. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32985. }
  32986. serializationObject.indices = this.indices;
  32987. return serializationObject;
  32988. };
  32989. // Statics
  32990. /**
  32991. * Returns the object VertexData associated to the passed mesh.
  32992. */
  32993. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32994. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32995. };
  32996. /**
  32997. * Returns the object VertexData associated to the passed geometry.
  32998. */
  32999. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  33000. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  33001. };
  33002. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  33003. var result = new VertexData();
  33004. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33005. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  33006. }
  33007. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33008. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  33009. }
  33010. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33011. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  33012. }
  33013. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33014. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  33015. }
  33016. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33017. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  33018. }
  33019. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33020. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  33021. }
  33022. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33023. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  33024. }
  33025. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33026. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  33027. }
  33028. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33029. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  33030. }
  33031. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33032. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  33033. }
  33034. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33035. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  33036. }
  33037. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33038. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  33039. }
  33040. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  33041. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  33042. }
  33043. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33044. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  33045. }
  33046. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  33047. return result;
  33048. };
  33049. /**
  33050. * Creates the vertexData of the Ribbon.
  33051. */
  33052. VertexData.CreateRibbon = function (options) {
  33053. var pathArray = options.pathArray;
  33054. var closeArray = options.closeArray || false;
  33055. var closePath = options.closePath || false;
  33056. var invertUV = options.invertUV || false;
  33057. var defaultOffset = Math.floor(pathArray[0].length / 2);
  33058. var offset = options.offset || defaultOffset;
  33059. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  33060. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33061. var customUV = options.uvs;
  33062. var customColors = options.colors;
  33063. var positions = [];
  33064. var indices = [];
  33065. var normals = [];
  33066. var uvs = [];
  33067. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  33068. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  33069. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  33070. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  33071. var minlg; // minimal length among all paths from pathArray
  33072. var lg = []; // array of path lengths : nb of vertex per path
  33073. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  33074. var p; // path iterator
  33075. var i; // point iterator
  33076. var j; // point iterator
  33077. // if single path in pathArray
  33078. if (pathArray.length < 2) {
  33079. var ar1 = [];
  33080. var ar2 = [];
  33081. for (i = 0; i < pathArray[0].length - offset; i++) {
  33082. ar1.push(pathArray[0][i]);
  33083. ar2.push(pathArray[0][i + offset]);
  33084. }
  33085. pathArray = [ar1, ar2];
  33086. }
  33087. // positions and horizontal distances (u)
  33088. var idc = 0;
  33089. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  33090. var path;
  33091. var l;
  33092. minlg = pathArray[0].length;
  33093. var vectlg;
  33094. var dist;
  33095. for (p = 0; p < pathArray.length; p++) {
  33096. uTotalDistance[p] = 0;
  33097. us[p] = [0];
  33098. path = pathArray[p];
  33099. l = path.length;
  33100. minlg = (minlg < l) ? minlg : l;
  33101. j = 0;
  33102. while (j < l) {
  33103. positions.push(path[j].x, path[j].y, path[j].z);
  33104. if (j > 0) {
  33105. vectlg = path[j].subtract(path[j - 1]).length();
  33106. dist = vectlg + uTotalDistance[p];
  33107. us[p].push(dist);
  33108. uTotalDistance[p] = dist;
  33109. }
  33110. j++;
  33111. }
  33112. if (closePath) {
  33113. j--;
  33114. positions.push(path[0].x, path[0].y, path[0].z);
  33115. vectlg = path[j].subtract(path[0]).length();
  33116. dist = vectlg + uTotalDistance[p];
  33117. us[p].push(dist);
  33118. uTotalDistance[p] = dist;
  33119. }
  33120. lg[p] = l + closePathCorr;
  33121. idx[p] = idc;
  33122. idc += (l + closePathCorr);
  33123. }
  33124. // vertical distances (v)
  33125. var path1;
  33126. var path2;
  33127. var vertex1 = null;
  33128. var vertex2 = null;
  33129. for (i = 0; i < minlg + closePathCorr; i++) {
  33130. vTotalDistance[i] = 0;
  33131. vs[i] = [0];
  33132. for (p = 0; p < pathArray.length - 1; p++) {
  33133. path1 = pathArray[p];
  33134. path2 = pathArray[p + 1];
  33135. if (i === minlg) {
  33136. vertex1 = path1[0];
  33137. vertex2 = path2[0];
  33138. }
  33139. else {
  33140. vertex1 = path1[i];
  33141. vertex2 = path2[i];
  33142. }
  33143. vectlg = vertex2.subtract(vertex1).length();
  33144. dist = vectlg + vTotalDistance[i];
  33145. vs[i].push(dist);
  33146. vTotalDistance[i] = dist;
  33147. }
  33148. if (closeArray && vertex2 && vertex1) {
  33149. path1 = pathArray[p];
  33150. path2 = pathArray[0];
  33151. if (i === minlg) {
  33152. vertex2 = path2[0];
  33153. }
  33154. vectlg = vertex2.subtract(vertex1).length();
  33155. dist = vectlg + vTotalDistance[i];
  33156. vTotalDistance[i] = dist;
  33157. }
  33158. }
  33159. // uvs
  33160. var u;
  33161. var v;
  33162. if (customUV) {
  33163. for (p = 0; p < customUV.length; p++) {
  33164. uvs.push(customUV[p].x, customUV[p].y);
  33165. }
  33166. }
  33167. else {
  33168. for (p = 0; p < pathArray.length; p++) {
  33169. for (i = 0; i < minlg + closePathCorr; i++) {
  33170. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33171. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33172. if (invertUV) {
  33173. uvs.push(v, u);
  33174. }
  33175. else {
  33176. uvs.push(u, v);
  33177. }
  33178. }
  33179. }
  33180. }
  33181. // indices
  33182. p = 0; // path index
  33183. var pi = 0; // positions array index
  33184. var l1 = lg[p] - 1; // path1 length
  33185. var l2 = lg[p + 1] - 1; // path2 length
  33186. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33187. var shft = idx[1] - idx[0]; // shift
  33188. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33189. while (pi <= min && p < path1nb) {
  33190. // 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
  33191. indices.push(pi, pi + shft, pi + 1);
  33192. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33193. pi += 1;
  33194. if (pi === min) {
  33195. p++;
  33196. if (p === lg.length - 1) {
  33197. shft = idx[0] - idx[p];
  33198. l1 = lg[p] - 1;
  33199. l2 = lg[0] - 1;
  33200. }
  33201. else {
  33202. shft = idx[p + 1] - idx[p];
  33203. l1 = lg[p] - 1;
  33204. l2 = lg[p + 1] - 1;
  33205. }
  33206. pi = idx[p];
  33207. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33208. }
  33209. }
  33210. // normals
  33211. VertexData.ComputeNormals(positions, indices, normals);
  33212. if (closePath) {
  33213. var indexFirst = 0;
  33214. var indexLast = 0;
  33215. for (p = 0; p < pathArray.length; p++) {
  33216. indexFirst = idx[p] * 3;
  33217. if (p + 1 < pathArray.length) {
  33218. indexLast = (idx[p + 1] - 1) * 3;
  33219. }
  33220. else {
  33221. indexLast = normals.length - 3;
  33222. }
  33223. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33224. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33225. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33226. normals[indexLast] = normals[indexFirst];
  33227. normals[indexLast + 1] = normals[indexFirst + 1];
  33228. normals[indexLast + 2] = normals[indexFirst + 2];
  33229. }
  33230. }
  33231. // sides
  33232. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33233. // Colors
  33234. var colors = null;
  33235. if (customColors) {
  33236. colors = new Float32Array(customColors.length * 4);
  33237. for (var c = 0; c < customColors.length; c++) {
  33238. colors[c * 4] = customColors[c].r;
  33239. colors[c * 4 + 1] = customColors[c].g;
  33240. colors[c * 4 + 2] = customColors[c].b;
  33241. colors[c * 4 + 3] = customColors[c].a;
  33242. }
  33243. }
  33244. // Result
  33245. var vertexData = new VertexData();
  33246. var positions32 = new Float32Array(positions);
  33247. var normals32 = new Float32Array(normals);
  33248. var uvs32 = new Float32Array(uvs);
  33249. vertexData.indices = indices;
  33250. vertexData.positions = positions32;
  33251. vertexData.normals = normals32;
  33252. vertexData.uvs = uvs32;
  33253. if (colors) {
  33254. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33255. }
  33256. if (closePath) {
  33257. vertexData._idx = idx;
  33258. }
  33259. return vertexData;
  33260. };
  33261. /**
  33262. * Creates the VertexData of the Box.
  33263. */
  33264. VertexData.CreateBox = function (options) {
  33265. var normalsSource = [
  33266. new BABYLON.Vector3(0, 0, 1),
  33267. new BABYLON.Vector3(0, 0, -1),
  33268. new BABYLON.Vector3(1, 0, 0),
  33269. new BABYLON.Vector3(-1, 0, 0),
  33270. new BABYLON.Vector3(0, 1, 0),
  33271. new BABYLON.Vector3(0, -1, 0)
  33272. ];
  33273. var indices = [];
  33274. var positions = [];
  33275. var normals = [];
  33276. var uvs = [];
  33277. var width = options.width || options.size || 1;
  33278. var height = options.height || options.size || 1;
  33279. var depth = options.depth || options.size || 1;
  33280. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33281. var faceUV = options.faceUV || new Array(6);
  33282. var faceColors = options.faceColors;
  33283. var colors = [];
  33284. // default face colors and UV if undefined
  33285. for (var f = 0; f < 6; f++) {
  33286. if (faceUV[f] === undefined) {
  33287. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33288. }
  33289. if (faceColors && faceColors[f] === undefined) {
  33290. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33291. }
  33292. }
  33293. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33294. // Create each face in turn.
  33295. for (var index = 0; index < normalsSource.length; index++) {
  33296. var normal = normalsSource[index];
  33297. // Get two vectors perpendicular to the face normal and to each other.
  33298. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33299. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33300. // Six indices (two triangles) per face.
  33301. var verticesLength = positions.length / 3;
  33302. indices.push(verticesLength);
  33303. indices.push(verticesLength + 1);
  33304. indices.push(verticesLength + 2);
  33305. indices.push(verticesLength);
  33306. indices.push(verticesLength + 2);
  33307. indices.push(verticesLength + 3);
  33308. // Four vertices per face.
  33309. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33310. positions.push(vertex.x, vertex.y, vertex.z);
  33311. normals.push(normal.x, normal.y, normal.z);
  33312. uvs.push(faceUV[index].z, faceUV[index].w);
  33313. if (faceColors) {
  33314. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33315. }
  33316. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33317. positions.push(vertex.x, vertex.y, vertex.z);
  33318. normals.push(normal.x, normal.y, normal.z);
  33319. uvs.push(faceUV[index].x, faceUV[index].w);
  33320. if (faceColors) {
  33321. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33322. }
  33323. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33324. positions.push(vertex.x, vertex.y, vertex.z);
  33325. normals.push(normal.x, normal.y, normal.z);
  33326. uvs.push(faceUV[index].x, faceUV[index].y);
  33327. if (faceColors) {
  33328. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33329. }
  33330. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33331. positions.push(vertex.x, vertex.y, vertex.z);
  33332. normals.push(normal.x, normal.y, normal.z);
  33333. uvs.push(faceUV[index].z, faceUV[index].y);
  33334. if (faceColors) {
  33335. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33336. }
  33337. }
  33338. // sides
  33339. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33340. // Result
  33341. var vertexData = new VertexData();
  33342. vertexData.indices = indices;
  33343. vertexData.positions = positions;
  33344. vertexData.normals = normals;
  33345. vertexData.uvs = uvs;
  33346. if (faceColors) {
  33347. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33348. vertexData.colors = totalColors;
  33349. }
  33350. return vertexData;
  33351. };
  33352. /**
  33353. * Creates the VertexData of the Sphere.
  33354. */
  33355. VertexData.CreateSphere = function (options) {
  33356. var segments = options.segments || 32;
  33357. var diameterX = options.diameterX || options.diameter || 1;
  33358. var diameterY = options.diameterY || options.diameter || 1;
  33359. var diameterZ = options.diameterZ || options.diameter || 1;
  33360. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33361. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33362. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33363. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33364. var totalZRotationSteps = 2 + segments;
  33365. var totalYRotationSteps = 2 * totalZRotationSteps;
  33366. var indices = [];
  33367. var positions = [];
  33368. var normals = [];
  33369. var uvs = [];
  33370. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33371. var normalizedZ = zRotationStep / totalZRotationSteps;
  33372. var angleZ = normalizedZ * Math.PI * slice;
  33373. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33374. var normalizedY = yRotationStep / totalYRotationSteps;
  33375. var angleY = normalizedY * Math.PI * 2 * arc;
  33376. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33377. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33378. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33379. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33380. var vertex = complete.multiply(radius);
  33381. var normal = complete.divide(radius).normalize();
  33382. positions.push(vertex.x, vertex.y, vertex.z);
  33383. normals.push(normal.x, normal.y, normal.z);
  33384. uvs.push(normalizedY, normalizedZ);
  33385. }
  33386. if (zRotationStep > 0) {
  33387. var verticesCount = positions.length / 3;
  33388. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33389. indices.push((firstIndex));
  33390. indices.push((firstIndex + 1));
  33391. indices.push(firstIndex + totalYRotationSteps + 1);
  33392. indices.push((firstIndex + totalYRotationSteps + 1));
  33393. indices.push((firstIndex + 1));
  33394. indices.push((firstIndex + totalYRotationSteps + 2));
  33395. }
  33396. }
  33397. }
  33398. // Sides
  33399. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33400. // Result
  33401. var vertexData = new VertexData();
  33402. vertexData.indices = indices;
  33403. vertexData.positions = positions;
  33404. vertexData.normals = normals;
  33405. vertexData.uvs = uvs;
  33406. return vertexData;
  33407. };
  33408. /**
  33409. * Creates the VertexData of the Cylinder or Cone.
  33410. */
  33411. VertexData.CreateCylinder = function (options) {
  33412. var height = options.height || 2;
  33413. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33414. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33415. var tessellation = options.tessellation || 24;
  33416. var subdivisions = options.subdivisions || 1;
  33417. var hasRings = options.hasRings ? true : false;
  33418. var enclose = options.enclose ? true : false;
  33419. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33420. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33421. var faceUV = options.faceUV || new Array(3);
  33422. var faceColors = options.faceColors;
  33423. // default face colors and UV if undefined
  33424. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33425. var ringNb = (hasRings) ? subdivisions : 1;
  33426. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33427. var f;
  33428. for (f = 0; f < surfaceNb; f++) {
  33429. if (faceColors && faceColors[f] === undefined) {
  33430. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33431. }
  33432. }
  33433. for (f = 0; f < surfaceNb; f++) {
  33434. if (faceUV && faceUV[f] === undefined) {
  33435. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33436. }
  33437. }
  33438. var indices = new Array();
  33439. var positions = new Array();
  33440. var normals = new Array();
  33441. var uvs = new Array();
  33442. var colors = new Array();
  33443. var angle_step = Math.PI * 2 * arc / tessellation;
  33444. var angle;
  33445. var h;
  33446. var radius;
  33447. var tan = (diameterBottom - diameterTop) / 2 / height;
  33448. var ringVertex = BABYLON.Vector3.Zero();
  33449. var ringNormal = BABYLON.Vector3.Zero();
  33450. var ringFirstVertex = BABYLON.Vector3.Zero();
  33451. var ringFirstNormal = BABYLON.Vector3.Zero();
  33452. var quadNormal = BABYLON.Vector3.Zero();
  33453. var Y = BABYLON.Axis.Y;
  33454. // positions, normals, uvs
  33455. var i;
  33456. var j;
  33457. var r;
  33458. var ringIdx = 1;
  33459. var s = 1; // surface index
  33460. var cs = 0;
  33461. var v = 0;
  33462. for (i = 0; i <= subdivisions; i++) {
  33463. h = i / subdivisions;
  33464. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33465. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33466. for (r = 0; r < ringIdx; r++) {
  33467. if (hasRings) {
  33468. s += r;
  33469. }
  33470. if (enclose) {
  33471. s += 2 * r;
  33472. }
  33473. for (j = 0; j <= tessellation; j++) {
  33474. angle = j * angle_step;
  33475. // position
  33476. ringVertex.x = Math.cos(-angle) * radius;
  33477. ringVertex.y = -height / 2 + h * height;
  33478. ringVertex.z = Math.sin(-angle) * radius;
  33479. // normal
  33480. if (diameterTop === 0 && i === subdivisions) {
  33481. // if no top cap, reuse former normals
  33482. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33483. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33484. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33485. }
  33486. else {
  33487. ringNormal.x = ringVertex.x;
  33488. ringNormal.z = ringVertex.z;
  33489. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33490. ringNormal.normalize();
  33491. }
  33492. // keep first ring vertex values for enclose
  33493. if (j === 0) {
  33494. ringFirstVertex.copyFrom(ringVertex);
  33495. ringFirstNormal.copyFrom(ringNormal);
  33496. }
  33497. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33498. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33499. if (hasRings) {
  33500. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33501. }
  33502. else {
  33503. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33504. }
  33505. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33506. if (faceColors) {
  33507. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33508. }
  33509. }
  33510. // if enclose, add four vertices and their dedicated normals
  33511. if (arc !== 1 && enclose) {
  33512. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33513. positions.push(0, ringVertex.y, 0);
  33514. positions.push(0, ringVertex.y, 0);
  33515. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33516. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33517. quadNormal.normalize();
  33518. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33519. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33520. quadNormal.normalize();
  33521. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33522. if (hasRings) {
  33523. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33524. }
  33525. else {
  33526. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33527. }
  33528. uvs.push(faceUV[s + 1].x, v);
  33529. uvs.push(faceUV[s + 1].z, v);
  33530. if (hasRings) {
  33531. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33532. }
  33533. else {
  33534. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33535. }
  33536. uvs.push(faceUV[s + 2].x, v);
  33537. uvs.push(faceUV[s + 2].z, v);
  33538. if (faceColors) {
  33539. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33540. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33541. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33542. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33543. }
  33544. }
  33545. if (cs !== s) {
  33546. cs = s;
  33547. }
  33548. }
  33549. }
  33550. // indices
  33551. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33552. var s;
  33553. i = 0;
  33554. for (s = 0; s < subdivisions; s++) {
  33555. var i0 = 0;
  33556. var i1 = 0;
  33557. var i2 = 0;
  33558. var i3 = 0;
  33559. for (j = 0; j < tessellation; j++) {
  33560. i0 = i * (e + 1) + j;
  33561. i1 = (i + 1) * (e + 1) + j;
  33562. i2 = i * (e + 1) + (j + 1);
  33563. i3 = (i + 1) * (e + 1) + (j + 1);
  33564. indices.push(i0, i1, i2);
  33565. indices.push(i3, i2, i1);
  33566. }
  33567. if (arc !== 1 && enclose) {
  33568. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33569. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33570. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33571. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33572. }
  33573. i = (hasRings) ? (i + 2) : (i + 1);
  33574. }
  33575. // Caps
  33576. var createCylinderCap = function (isTop) {
  33577. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33578. if (radius === 0) {
  33579. return;
  33580. }
  33581. // Cap positions, normals & uvs
  33582. var angle;
  33583. var circleVector;
  33584. var i;
  33585. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33586. var c = null;
  33587. if (faceColors) {
  33588. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33589. }
  33590. // cap center
  33591. var vbase = positions.length / 3;
  33592. var offset = isTop ? height / 2 : -height / 2;
  33593. var center = new BABYLON.Vector3(0, offset, 0);
  33594. positions.push(center.x, center.y, center.z);
  33595. normals.push(0, isTop ? 1 : -1, 0);
  33596. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33597. if (c) {
  33598. colors.push(c.r, c.g, c.b, c.a);
  33599. }
  33600. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33601. for (i = 0; i <= tessellation; i++) {
  33602. angle = Math.PI * 2 * i * arc / tessellation;
  33603. var cos = Math.cos(-angle);
  33604. var sin = Math.sin(-angle);
  33605. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33606. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33607. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33608. normals.push(0, isTop ? 1 : -1, 0);
  33609. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33610. if (c) {
  33611. colors.push(c.r, c.g, c.b, c.a);
  33612. }
  33613. }
  33614. // Cap indices
  33615. for (i = 0; i < tessellation; i++) {
  33616. if (!isTop) {
  33617. indices.push(vbase);
  33618. indices.push(vbase + (i + 1));
  33619. indices.push(vbase + (i + 2));
  33620. }
  33621. else {
  33622. indices.push(vbase);
  33623. indices.push(vbase + (i + 2));
  33624. indices.push(vbase + (i + 1));
  33625. }
  33626. }
  33627. };
  33628. // add caps to geometry
  33629. createCylinderCap(false);
  33630. createCylinderCap(true);
  33631. // Sides
  33632. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33633. var vertexData = new VertexData();
  33634. vertexData.indices = indices;
  33635. vertexData.positions = positions;
  33636. vertexData.normals = normals;
  33637. vertexData.uvs = uvs;
  33638. if (faceColors) {
  33639. vertexData.colors = colors;
  33640. }
  33641. return vertexData;
  33642. };
  33643. /**
  33644. * Creates the VertexData of the Torus.
  33645. */
  33646. VertexData.CreateTorus = function (options) {
  33647. var indices = [];
  33648. var positions = [];
  33649. var normals = [];
  33650. var uvs = [];
  33651. var diameter = options.diameter || 1;
  33652. var thickness = options.thickness || 0.5;
  33653. var tessellation = options.tessellation || 16;
  33654. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33655. var stride = tessellation + 1;
  33656. for (var i = 0; i <= tessellation; i++) {
  33657. var u = i / tessellation;
  33658. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33659. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33660. for (var j = 0; j <= tessellation; j++) {
  33661. var v = 1 - j / tessellation;
  33662. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33663. var dx = Math.cos(innerAngle);
  33664. var dy = Math.sin(innerAngle);
  33665. // Create a vertex.
  33666. var normal = new BABYLON.Vector3(dx, dy, 0);
  33667. var position = normal.scale(thickness / 2);
  33668. var textureCoordinate = new BABYLON.Vector2(u, v);
  33669. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33670. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33671. positions.push(position.x, position.y, position.z);
  33672. normals.push(normal.x, normal.y, normal.z);
  33673. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33674. // And create indices for two triangles.
  33675. var nextI = (i + 1) % stride;
  33676. var nextJ = (j + 1) % stride;
  33677. indices.push(i * stride + j);
  33678. indices.push(i * stride + nextJ);
  33679. indices.push(nextI * stride + j);
  33680. indices.push(i * stride + nextJ);
  33681. indices.push(nextI * stride + nextJ);
  33682. indices.push(nextI * stride + j);
  33683. }
  33684. }
  33685. // Sides
  33686. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33687. // Result
  33688. var vertexData = new VertexData();
  33689. vertexData.indices = indices;
  33690. vertexData.positions = positions;
  33691. vertexData.normals = normals;
  33692. vertexData.uvs = uvs;
  33693. return vertexData;
  33694. };
  33695. /**
  33696. * Creates the VertexData of the LineSystem.
  33697. */
  33698. VertexData.CreateLineSystem = function (options) {
  33699. var indices = [];
  33700. var positions = [];
  33701. var lines = options.lines;
  33702. var colors = options.colors;
  33703. var vertexColors = [];
  33704. var idx = 0;
  33705. for (var l = 0; l < lines.length; l++) {
  33706. var points = lines[l];
  33707. for (var index = 0; index < points.length; index++) {
  33708. positions.push(points[index].x, points[index].y, points[index].z);
  33709. if (colors) {
  33710. var color = colors[l];
  33711. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33712. }
  33713. if (index > 0) {
  33714. indices.push(idx - 1);
  33715. indices.push(idx);
  33716. }
  33717. idx++;
  33718. }
  33719. }
  33720. var vertexData = new VertexData();
  33721. vertexData.indices = indices;
  33722. vertexData.positions = positions;
  33723. if (colors) {
  33724. vertexData.colors = vertexColors;
  33725. }
  33726. return vertexData;
  33727. };
  33728. /**
  33729. * Create the VertexData of the DashedLines.
  33730. */
  33731. VertexData.CreateDashedLines = function (options) {
  33732. var dashSize = options.dashSize || 3;
  33733. var gapSize = options.gapSize || 1;
  33734. var dashNb = options.dashNb || 200;
  33735. var points = options.points;
  33736. var positions = new Array();
  33737. var indices = new Array();
  33738. var curvect = BABYLON.Vector3.Zero();
  33739. var lg = 0;
  33740. var nb = 0;
  33741. var shft = 0;
  33742. var dashshft = 0;
  33743. var curshft = 0;
  33744. var idx = 0;
  33745. var i = 0;
  33746. for (i = 0; i < points.length - 1; i++) {
  33747. points[i + 1].subtractToRef(points[i], curvect);
  33748. lg += curvect.length();
  33749. }
  33750. shft = lg / dashNb;
  33751. dashshft = dashSize * shft / (dashSize + gapSize);
  33752. for (i = 0; i < points.length - 1; i++) {
  33753. points[i + 1].subtractToRef(points[i], curvect);
  33754. nb = Math.floor(curvect.length() / shft);
  33755. curvect.normalize();
  33756. for (var j = 0; j < nb; j++) {
  33757. curshft = shft * j;
  33758. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33759. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33760. indices.push(idx, idx + 1);
  33761. idx += 2;
  33762. }
  33763. }
  33764. // Result
  33765. var vertexData = new VertexData();
  33766. vertexData.positions = positions;
  33767. vertexData.indices = indices;
  33768. return vertexData;
  33769. };
  33770. /**
  33771. * Creates the VertexData of the Ground.
  33772. */
  33773. VertexData.CreateGround = function (options) {
  33774. var indices = [];
  33775. var positions = [];
  33776. var normals = [];
  33777. var uvs = [];
  33778. var row, col;
  33779. var width = options.width || 1;
  33780. var height = options.height || 1;
  33781. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33782. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33783. for (row = 0; row <= subdivisionsY; row++) {
  33784. for (col = 0; col <= subdivisionsX; col++) {
  33785. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33786. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33787. positions.push(position.x, position.y, position.z);
  33788. normals.push(normal.x, normal.y, normal.z);
  33789. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33790. }
  33791. }
  33792. for (row = 0; row < subdivisionsY; row++) {
  33793. for (col = 0; col < subdivisionsX; col++) {
  33794. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33795. indices.push(col + 1 + row * (subdivisionsX + 1));
  33796. indices.push(col + row * (subdivisionsX + 1));
  33797. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33798. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33799. indices.push(col + row * (subdivisionsX + 1));
  33800. }
  33801. }
  33802. // Result
  33803. var vertexData = new VertexData();
  33804. vertexData.indices = indices;
  33805. vertexData.positions = positions;
  33806. vertexData.normals = normals;
  33807. vertexData.uvs = uvs;
  33808. return vertexData;
  33809. };
  33810. /**
  33811. * Creates the VertexData of the TiledGround.
  33812. */
  33813. VertexData.CreateTiledGround = function (options) {
  33814. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33815. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33816. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33817. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33818. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33819. var precision = options.precision || { w: 1, h: 1 };
  33820. var indices = new Array();
  33821. var positions = new Array();
  33822. var normals = new Array();
  33823. var uvs = new Array();
  33824. var row, col, tileRow, tileCol;
  33825. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33826. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33827. precision.w = (precision.w < 1) ? 1 : precision.w;
  33828. precision.h = (precision.h < 1) ? 1 : precision.h;
  33829. var tileSize = {
  33830. 'w': (xmax - xmin) / subdivisions.w,
  33831. 'h': (zmax - zmin) / subdivisions.h
  33832. };
  33833. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33834. // Indices
  33835. var base = positions.length / 3;
  33836. var rowLength = precision.w + 1;
  33837. for (row = 0; row < precision.h; row++) {
  33838. for (col = 0; col < precision.w; col++) {
  33839. var square = [
  33840. base + col + row * rowLength,
  33841. base + (col + 1) + row * rowLength,
  33842. base + (col + 1) + (row + 1) * rowLength,
  33843. base + col + (row + 1) * rowLength
  33844. ];
  33845. indices.push(square[1]);
  33846. indices.push(square[2]);
  33847. indices.push(square[3]);
  33848. indices.push(square[0]);
  33849. indices.push(square[1]);
  33850. indices.push(square[3]);
  33851. }
  33852. }
  33853. // Position, normals and uvs
  33854. var position = BABYLON.Vector3.Zero();
  33855. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33856. for (row = 0; row <= precision.h; row++) {
  33857. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33858. for (col = 0; col <= precision.w; col++) {
  33859. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33860. position.y = 0;
  33861. positions.push(position.x, position.y, position.z);
  33862. normals.push(normal.x, normal.y, normal.z);
  33863. uvs.push(col / precision.w, row / precision.h);
  33864. }
  33865. }
  33866. }
  33867. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33868. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33869. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33870. }
  33871. }
  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 Ground designed from a heightmap.
  33882. */
  33883. VertexData.CreateGroundFromHeightMap = function (options) {
  33884. var indices = [];
  33885. var positions = [];
  33886. var normals = [];
  33887. var uvs = [];
  33888. var row, col;
  33889. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33890. // Vertices
  33891. for (row = 0; row <= options.subdivisions; row++) {
  33892. for (col = 0; col <= options.subdivisions; col++) {
  33893. 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));
  33894. // Compute height
  33895. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33896. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33897. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33898. var r = options.buffer[pos] / 255.0;
  33899. var g = options.buffer[pos + 1] / 255.0;
  33900. var b = options.buffer[pos + 2] / 255.0;
  33901. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33902. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33903. // Add vertex
  33904. positions.push(position.x, position.y, position.z);
  33905. normals.push(0, 0, 0);
  33906. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33907. }
  33908. }
  33909. // Indices
  33910. for (row = 0; row < options.subdivisions; row++) {
  33911. for (col = 0; col < options.subdivisions; col++) {
  33912. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33913. indices.push(col + 1 + row * (options.subdivisions + 1));
  33914. indices.push(col + row * (options.subdivisions + 1));
  33915. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33916. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33917. indices.push(col + row * (options.subdivisions + 1));
  33918. }
  33919. }
  33920. // Normals
  33921. VertexData.ComputeNormals(positions, indices, normals);
  33922. // Result
  33923. var vertexData = new VertexData();
  33924. vertexData.indices = indices;
  33925. vertexData.positions = positions;
  33926. vertexData.normals = normals;
  33927. vertexData.uvs = uvs;
  33928. return vertexData;
  33929. };
  33930. /**
  33931. * Creates the VertexData of the Plane.
  33932. */
  33933. VertexData.CreatePlane = function (options) {
  33934. var indices = [];
  33935. var positions = [];
  33936. var normals = [];
  33937. var uvs = [];
  33938. var width = options.width || options.size || 1;
  33939. var height = options.height || options.size || 1;
  33940. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33941. // Vertices
  33942. var halfWidth = width / 2.0;
  33943. var halfHeight = height / 2.0;
  33944. positions.push(-halfWidth, -halfHeight, 0);
  33945. normals.push(0, 0, -1.0);
  33946. uvs.push(0.0, 0.0);
  33947. positions.push(halfWidth, -halfHeight, 0);
  33948. normals.push(0, 0, -1.0);
  33949. uvs.push(1.0, 0.0);
  33950. positions.push(halfWidth, halfHeight, 0);
  33951. normals.push(0, 0, -1.0);
  33952. uvs.push(1.0, 1.0);
  33953. positions.push(-halfWidth, halfHeight, 0);
  33954. normals.push(0, 0, -1.0);
  33955. uvs.push(0.0, 1.0);
  33956. // Indices
  33957. indices.push(0);
  33958. indices.push(1);
  33959. indices.push(2);
  33960. indices.push(0);
  33961. indices.push(2);
  33962. indices.push(3);
  33963. // Sides
  33964. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33965. // Result
  33966. var vertexData = new VertexData();
  33967. vertexData.indices = indices;
  33968. vertexData.positions = positions;
  33969. vertexData.normals = normals;
  33970. vertexData.uvs = uvs;
  33971. return vertexData;
  33972. };
  33973. /**
  33974. * Creates the VertexData of the Disc or regular Polygon.
  33975. */
  33976. VertexData.CreateDisc = function (options) {
  33977. var positions = new Array();
  33978. var indices = new Array();
  33979. var normals = new Array();
  33980. var uvs = new Array();
  33981. var radius = options.radius || 0.5;
  33982. var tessellation = options.tessellation || 64;
  33983. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33984. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33985. // positions and uvs
  33986. positions.push(0, 0, 0); // disc center first
  33987. uvs.push(0.5, 0.5);
  33988. var theta = Math.PI * 2 * arc;
  33989. var step = theta / tessellation;
  33990. for (var a = 0; a < theta; a += step) {
  33991. var x = Math.cos(a);
  33992. var y = Math.sin(a);
  33993. var u = (x + 1) / 2;
  33994. var v = (1 - y) / 2;
  33995. positions.push(radius * x, radius * y, 0);
  33996. uvs.push(u, v);
  33997. }
  33998. if (arc === 1) {
  33999. positions.push(positions[3], positions[4], positions[5]); // close the circle
  34000. uvs.push(uvs[2], uvs[3]);
  34001. }
  34002. //indices
  34003. var vertexNb = positions.length / 3;
  34004. for (var i = 1; i < vertexNb - 1; i++) {
  34005. indices.push(i + 1, 0, i);
  34006. }
  34007. // result
  34008. VertexData.ComputeNormals(positions, indices, normals);
  34009. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34010. var vertexData = new VertexData();
  34011. vertexData.indices = indices;
  34012. vertexData.positions = positions;
  34013. vertexData.normals = normals;
  34014. vertexData.uvs = uvs;
  34015. return vertexData;
  34016. };
  34017. /**
  34018. * Re-creates the VertexData of the Polygon for sideOrientation.
  34019. */
  34020. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  34021. var faceUV = fUV || new Array(3);
  34022. var faceColors = fColors;
  34023. var colors = [];
  34024. // default face colors and UV if undefined
  34025. for (var f = 0; f < 3; f++) {
  34026. if (faceUV[f] === undefined) {
  34027. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34028. }
  34029. if (faceColors && faceColors[f] === undefined) {
  34030. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34031. }
  34032. }
  34033. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34034. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34035. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34036. var indices = polygon.getIndices();
  34037. // set face colours and textures
  34038. var idx = 0;
  34039. var face = 0;
  34040. for (var index = 0; index < normals.length; index += 3) {
  34041. //Edge Face no. 1
  34042. if (Math.abs(normals[index + 1]) < 0.001) {
  34043. face = 1;
  34044. }
  34045. //Top Face no. 0
  34046. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  34047. face = 0;
  34048. }
  34049. //Bottom Face no. 2
  34050. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  34051. face = 2;
  34052. }
  34053. idx = index / 3;
  34054. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  34055. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  34056. if (faceColors) {
  34057. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  34058. }
  34059. }
  34060. // sides
  34061. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  34062. // Result
  34063. var vertexData = new VertexData();
  34064. vertexData.indices = indices;
  34065. vertexData.positions = positions;
  34066. vertexData.normals = normals;
  34067. vertexData.uvs = uvs;
  34068. if (faceColors) {
  34069. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  34070. vertexData.colors = totalColors;
  34071. }
  34072. return vertexData;
  34073. };
  34074. /**
  34075. * Creates the VertexData of the IcoSphere.
  34076. */
  34077. VertexData.CreateIcoSphere = function (options) {
  34078. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34079. var radius = options.radius || 1;
  34080. var flat = (options.flat === undefined) ? true : options.flat;
  34081. var subdivisions = options.subdivisions || 4;
  34082. var radiusX = options.radiusX || radius;
  34083. var radiusY = options.radiusY || radius;
  34084. var radiusZ = options.radiusZ || radius;
  34085. var t = (1 + Math.sqrt(5)) / 2;
  34086. // 12 vertex x,y,z
  34087. var ico_vertices = [
  34088. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34089. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34090. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34091. ];
  34092. // index of 3 vertex makes a face of icopshere
  34093. var ico_indices = [
  34094. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34095. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34096. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34097. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34098. ];
  34099. // vertex for uv have aliased position, not for UV
  34100. var vertices_unalias_id = [
  34101. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34102. // vertex alias
  34103. 0,
  34104. 2,
  34105. 3,
  34106. 3,
  34107. 3,
  34108. 4,
  34109. 7,
  34110. 8,
  34111. 9,
  34112. 9,
  34113. 10,
  34114. 11 // 23: B + 12
  34115. ];
  34116. // uv as integer step (not pixels !)
  34117. var ico_vertexuv = [
  34118. 5, 1, 3, 1, 6, 4, 0, 0,
  34119. 5, 3, 4, 2, 2, 2, 4, 0,
  34120. 2, 0, 1, 1, 6, 0, 6, 2,
  34121. // vertex alias (for same vertex on different faces)
  34122. 0, 4,
  34123. 3, 3,
  34124. 4, 4,
  34125. 3, 1,
  34126. 4, 2,
  34127. 4, 4,
  34128. 0, 2,
  34129. 1, 1,
  34130. 2, 2,
  34131. 3, 3,
  34132. 1, 3,
  34133. 2, 4 // 23: B + 12
  34134. ];
  34135. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34136. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34137. // First island of uv mapping
  34138. // v = 4h 3+ 2
  34139. // v = 3h 9+ 4
  34140. // v = 2h 9+ 5 B
  34141. // v = 1h 9 1 0
  34142. // v = 0h 3 8 7 A
  34143. // u = 0 1 2 3 4 5 6 *a
  34144. // Second island of uv mapping
  34145. // v = 4h 0+ B+ 4+
  34146. // v = 3h A+ 2+
  34147. // v = 2h 7+ 6 3+
  34148. // v = 1h 8+ 3+
  34149. // v = 0h
  34150. // u = 0 1 2 3 4 5 6 *a
  34151. // Face layout on texture UV mapping
  34152. // ============
  34153. // \ 4 /\ 16 / ======
  34154. // \ / \ / /\ 11 /
  34155. // \/ 7 \/ / \ /
  34156. // ======= / 10 \/
  34157. // /\ 17 /\ =======
  34158. // / \ / \ \ 15 /\
  34159. // / 8 \/ 12 \ \ / \
  34160. // ============ \/ 6 \
  34161. // \ 18 /\ ============
  34162. // \ / \ \ 5 /\ 0 /
  34163. // \/ 13 \ \ / \ /
  34164. // ======= \/ 1 \/
  34165. // =============
  34166. // /\ 19 /\ 2 /\
  34167. // / \ / \ / \
  34168. // / 14 \/ 9 \/ 3 \
  34169. // ===================
  34170. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34171. var ustep = 138 / 1024;
  34172. var vstep = 239 / 1024;
  34173. var uoffset = 60 / 1024;
  34174. var voffset = 26 / 1024;
  34175. // Second island should have margin, not to touch the first island
  34176. // avoid any borderline artefact in pixel rounding
  34177. var island_u_offset = -40 / 1024;
  34178. var island_v_offset = +20 / 1024;
  34179. // face is either island 0 or 1 :
  34180. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34181. var island = [
  34182. 0, 0, 0, 0, 1,
  34183. 0, 0, 1, 1, 0,
  34184. 0, 0, 1, 1, 0,
  34185. 0, 1, 1, 1, 0 // 15 - 19
  34186. ];
  34187. var indices = new Array();
  34188. var positions = new Array();
  34189. var normals = new Array();
  34190. var uvs = new Array();
  34191. var current_indice = 0;
  34192. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34193. var face_vertex_pos = new Array(3);
  34194. var face_vertex_uv = new Array(3);
  34195. var v012;
  34196. for (v012 = 0; v012 < 3; v012++) {
  34197. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34198. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34199. }
  34200. // create all with normals
  34201. for (var face = 0; face < 20; face++) {
  34202. // 3 vertex per face
  34203. for (v012 = 0; v012 < 3; v012++) {
  34204. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34205. var v_id = ico_indices[3 * face + v012];
  34206. // vertex have 3D position (x,y,z)
  34207. 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]);
  34208. // Normalize to get normal, then scale to radius
  34209. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34210. // uv Coordinates from vertex ID
  34211. 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);
  34212. }
  34213. // Subdivide the face (interpolate pos, norm, uv)
  34214. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34215. // - norm is linear interpolation of vertex corner normal
  34216. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34217. // - uv is linear interpolation
  34218. //
  34219. // Topology is as below for sub-divide by 2
  34220. // vertex shown as v0,v1,v2
  34221. // interp index is i1 to progress in range [v0,v1[
  34222. // interp index is i2 to progress in range [v0,v2[
  34223. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34224. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34225. //
  34226. //
  34227. // i2 v2
  34228. // ^ ^
  34229. // / / \
  34230. // / / \
  34231. // / / \
  34232. // / / (0,1) \
  34233. // / #---------\
  34234. // / / \ (0,0)'/ \
  34235. // / / \ / \
  34236. // / / \ / \
  34237. // / / (0,0) \ / (1,0) \
  34238. // / #---------#---------\
  34239. // v0 v1
  34240. //
  34241. // --------------------> i1
  34242. //
  34243. // interp of (i1,i2):
  34244. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34245. // along i1 : lerp(x0,x1, i1/(S-i2))
  34246. //
  34247. // centroid of triangle is needed to get help normal computation
  34248. // (c1,c2) are used for centroid location
  34249. var interp_vertex = function (i1, i2, c1, c2) {
  34250. // vertex is interpolated from
  34251. // - face_vertex_pos[0..2]
  34252. // - face_vertex_uv[0..2]
  34253. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34254. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34255. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34256. pos_interp.normalize();
  34257. var vertex_normal;
  34258. if (flat) {
  34259. // in flat mode, recalculate normal as face centroid normal
  34260. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34261. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34262. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34263. }
  34264. else {
  34265. // in smooth mode, recalculate normal from each single vertex position
  34266. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34267. }
  34268. // Vertex normal need correction due to X,Y,Z radius scaling
  34269. vertex_normal.x /= radiusX;
  34270. vertex_normal.y /= radiusY;
  34271. vertex_normal.z /= radiusZ;
  34272. vertex_normal.normalize();
  34273. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34274. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34275. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34276. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34277. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34278. uvs.push(uv_interp.x, uv_interp.y);
  34279. // push each vertex has member of a face
  34280. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34281. indices.push(current_indice);
  34282. current_indice++;
  34283. };
  34284. for (var i2 = 0; i2 < subdivisions; i2++) {
  34285. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34286. // face : (i1,i2) for /\ :
  34287. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34288. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34289. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34290. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34291. if (i1 + i2 + 1 < subdivisions) {
  34292. // face : (i1,i2)' for \/ :
  34293. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34294. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34295. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34296. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34297. }
  34298. }
  34299. }
  34300. }
  34301. // Sides
  34302. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34303. // Result
  34304. var vertexData = new VertexData();
  34305. vertexData.indices = indices;
  34306. vertexData.positions = positions;
  34307. vertexData.normals = normals;
  34308. vertexData.uvs = uvs;
  34309. return vertexData;
  34310. };
  34311. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34312. /**
  34313. * Creates the VertexData of the Polyhedron.
  34314. */
  34315. VertexData.CreatePolyhedron = function (options) {
  34316. // provided polyhedron types :
  34317. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34318. // 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)
  34319. var polyhedra = [];
  34320. 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]] };
  34321. 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]] };
  34322. polyhedra[2] = {
  34323. 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]],
  34324. 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]]
  34325. };
  34326. polyhedra[3] = {
  34327. 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]],
  34328. 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]]
  34329. };
  34330. polyhedra[4] = {
  34331. 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]],
  34332. 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]]
  34333. };
  34334. 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]] };
  34335. 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]] };
  34336. 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]] };
  34337. 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]] };
  34338. 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]] };
  34339. 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]] };
  34340. 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]] };
  34341. 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]] };
  34342. 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]] };
  34343. polyhedra[14] = {
  34344. 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]],
  34345. 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]]
  34346. };
  34347. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34348. var size = options.size;
  34349. var sizeX = options.sizeX || size || 1;
  34350. var sizeY = options.sizeY || size || 1;
  34351. var sizeZ = options.sizeZ || size || 1;
  34352. var data = options.custom || polyhedra[type];
  34353. var nbfaces = data.face.length;
  34354. var faceUV = options.faceUV || new Array(nbfaces);
  34355. var faceColors = options.faceColors;
  34356. var flat = (options.flat === undefined) ? true : options.flat;
  34357. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34358. var positions = new Array();
  34359. var indices = new Array();
  34360. var normals = new Array();
  34361. var uvs = new Array();
  34362. var colors = new Array();
  34363. var index = 0;
  34364. var faceIdx = 0; // face cursor in the array "indexes"
  34365. var indexes = new Array();
  34366. var i = 0;
  34367. var f = 0;
  34368. var u, v, ang, x, y, tmp;
  34369. // default face colors and UV if undefined
  34370. if (flat) {
  34371. for (f = 0; f < nbfaces; f++) {
  34372. if (faceColors && faceColors[f] === undefined) {
  34373. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34374. }
  34375. if (faceUV && faceUV[f] === undefined) {
  34376. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34377. }
  34378. }
  34379. }
  34380. if (!flat) {
  34381. for (i = 0; i < data.vertex.length; i++) {
  34382. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34383. uvs.push(0, 0);
  34384. }
  34385. for (f = 0; f < nbfaces; f++) {
  34386. for (i = 0; i < data.face[f].length - 2; i++) {
  34387. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34388. }
  34389. }
  34390. }
  34391. else {
  34392. for (f = 0; f < nbfaces; f++) {
  34393. var fl = data.face[f].length; // number of vertices of the current face
  34394. ang = 2 * Math.PI / fl;
  34395. x = 0.5 * Math.tan(ang / 2);
  34396. y = 0.5;
  34397. // positions, uvs, colors
  34398. for (i = 0; i < fl; i++) {
  34399. // positions
  34400. 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);
  34401. indexes.push(index);
  34402. index++;
  34403. // uvs
  34404. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34405. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34406. uvs.push(u, v);
  34407. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34408. y = x * Math.sin(ang) + y * Math.cos(ang);
  34409. x = tmp;
  34410. // colors
  34411. if (faceColors) {
  34412. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34413. }
  34414. }
  34415. // indices from indexes
  34416. for (i = 0; i < fl - 2; i++) {
  34417. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34418. }
  34419. faceIdx += fl;
  34420. }
  34421. }
  34422. VertexData.ComputeNormals(positions, indices, normals);
  34423. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34424. var vertexData = new VertexData();
  34425. vertexData.positions = positions;
  34426. vertexData.indices = indices;
  34427. vertexData.normals = normals;
  34428. vertexData.uvs = uvs;
  34429. if (faceColors && flat) {
  34430. vertexData.colors = colors;
  34431. }
  34432. return vertexData;
  34433. };
  34434. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34435. /**
  34436. * Creates the VertexData of the Torus Knot.
  34437. */
  34438. VertexData.CreateTorusKnot = function (options) {
  34439. var indices = new Array();
  34440. var positions = new Array();
  34441. var normals = new Array();
  34442. var uvs = new Array();
  34443. var radius = options.radius || 2;
  34444. var tube = options.tube || 0.5;
  34445. var radialSegments = options.radialSegments || 32;
  34446. var tubularSegments = options.tubularSegments || 32;
  34447. var p = options.p || 2;
  34448. var q = options.q || 3;
  34449. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34450. // Helper
  34451. var getPos = function (angle) {
  34452. var cu = Math.cos(angle);
  34453. var su = Math.sin(angle);
  34454. var quOverP = q / p * angle;
  34455. var cs = Math.cos(quOverP);
  34456. var tx = radius * (2 + cs) * 0.5 * cu;
  34457. var ty = radius * (2 + cs) * su * 0.5;
  34458. var tz = radius * Math.sin(quOverP) * 0.5;
  34459. return new BABYLON.Vector3(tx, ty, tz);
  34460. };
  34461. // Vertices
  34462. var i;
  34463. var j;
  34464. for (i = 0; i <= radialSegments; i++) {
  34465. var modI = i % radialSegments;
  34466. var u = modI / radialSegments * 2 * p * Math.PI;
  34467. var p1 = getPos(u);
  34468. var p2 = getPos(u + 0.01);
  34469. var tang = p2.subtract(p1);
  34470. var n = p2.add(p1);
  34471. var bitan = BABYLON.Vector3.Cross(tang, n);
  34472. n = BABYLON.Vector3.Cross(bitan, tang);
  34473. bitan.normalize();
  34474. n.normalize();
  34475. for (j = 0; j < tubularSegments; j++) {
  34476. var modJ = j % tubularSegments;
  34477. var v = modJ / tubularSegments * 2 * Math.PI;
  34478. var cx = -tube * Math.cos(v);
  34479. var cy = tube * Math.sin(v);
  34480. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34481. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34482. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34483. uvs.push(i / radialSegments);
  34484. uvs.push(j / tubularSegments);
  34485. }
  34486. }
  34487. for (i = 0; i < radialSegments; i++) {
  34488. for (j = 0; j < tubularSegments; j++) {
  34489. var jNext = (j + 1) % tubularSegments;
  34490. var a = i * tubularSegments + j;
  34491. var b = (i + 1) * tubularSegments + j;
  34492. var c = (i + 1) * tubularSegments + jNext;
  34493. var d = i * tubularSegments + jNext;
  34494. indices.push(d);
  34495. indices.push(b);
  34496. indices.push(a);
  34497. indices.push(d);
  34498. indices.push(c);
  34499. indices.push(b);
  34500. }
  34501. }
  34502. // Normals
  34503. VertexData.ComputeNormals(positions, indices, normals);
  34504. // Sides
  34505. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34506. // Result
  34507. var vertexData = new VertexData();
  34508. vertexData.indices = indices;
  34509. vertexData.positions = positions;
  34510. vertexData.normals = normals;
  34511. vertexData.uvs = uvs;
  34512. return vertexData;
  34513. };
  34514. // Tools
  34515. /**
  34516. * @param {any} - positions (number[] or Float32Array)
  34517. * @param {any} - indices (number[] or Uint16Array)
  34518. * @param {any} - normals (number[] or Float32Array)
  34519. * options (optional) :
  34520. * facetPositions : optional array of facet positions (vector3)
  34521. * facetNormals : optional array of facet normals (vector3)
  34522. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34523. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34524. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34525. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34526. * bInfo : optional bounding info, required for facetPartitioning computation
  34527. * useRightHandedSystem: optional boolean to for right handed system computation
  34528. * depthSort : optional boolean to enable the facet depth sort computation
  34529. * distanceTo : optional Vector3 to compute the facet depth from this location
  34530. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34531. */
  34532. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34533. // temporary scalar variables
  34534. var index = 0; // facet index
  34535. var p1p2x = 0.0; // p1p2 vector x coordinate
  34536. var p1p2y = 0.0; // p1p2 vector y coordinate
  34537. var p1p2z = 0.0; // p1p2 vector z coordinate
  34538. var p3p2x = 0.0; // p3p2 vector x coordinate
  34539. var p3p2y = 0.0; // p3p2 vector y coordinate
  34540. var p3p2z = 0.0; // p3p2 vector z coordinate
  34541. var faceNormalx = 0.0; // facet normal x coordinate
  34542. var faceNormaly = 0.0; // facet normal y coordinate
  34543. var faceNormalz = 0.0; // facet normal z coordinate
  34544. var length = 0.0; // facet normal length before normalization
  34545. var v1x = 0; // vector1 x index in the positions array
  34546. var v1y = 0; // vector1 y index in the positions array
  34547. var v1z = 0; // vector1 z index in the positions array
  34548. var v2x = 0; // vector2 x index in the positions array
  34549. var v2y = 0; // vector2 y index in the positions array
  34550. var v2z = 0; // vector2 z index in the positions array
  34551. var v3x = 0; // vector3 x index in the positions array
  34552. var v3y = 0; // vector3 y index in the positions array
  34553. var v3z = 0; // vector3 z index in the positions array
  34554. var computeFacetNormals = false;
  34555. var computeFacetPositions = false;
  34556. var computeFacetPartitioning = false;
  34557. var computeDepthSort = false;
  34558. var faceNormalSign = 1;
  34559. var ratio = 0;
  34560. var distanceTo = null;
  34561. if (options) {
  34562. computeFacetNormals = (options.facetNormals) ? true : false;
  34563. computeFacetPositions = (options.facetPositions) ? true : false;
  34564. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34565. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34566. ratio = options.ratio || 0;
  34567. computeDepthSort = (options.depthSort) ? true : false;
  34568. distanceTo = (options.distanceTo);
  34569. if (computeDepthSort) {
  34570. if (distanceTo === undefined) {
  34571. distanceTo = BABYLON.Vector3.Zero();
  34572. }
  34573. var depthSortedFacets = options.depthSortedFacets;
  34574. }
  34575. }
  34576. // facetPartitioning reinit if needed
  34577. var xSubRatio = 0;
  34578. var ySubRatio = 0;
  34579. var zSubRatio = 0;
  34580. var subSq = 0;
  34581. if (computeFacetPartitioning && options && options.bbSize) {
  34582. var ox = 0; // X partitioning index for facet position
  34583. var oy = 0; // Y partinioning index for facet position
  34584. var oz = 0; // Z partinioning index for facet position
  34585. var b1x = 0; // X partitioning index for facet v1 vertex
  34586. var b1y = 0; // Y partitioning index for facet v1 vertex
  34587. var b1z = 0; // z partitioning index for facet v1 vertex
  34588. var b2x = 0; // X partitioning index for facet v2 vertex
  34589. var b2y = 0; // Y partitioning index for facet v2 vertex
  34590. var b2z = 0; // Z partitioning index for facet v2 vertex
  34591. var b3x = 0; // X partitioning index for facet v3 vertex
  34592. var b3y = 0; // Y partitioning index for facet v3 vertex
  34593. var b3z = 0; // Z partitioning index for facet v3 vertex
  34594. var block_idx_o = 0; // facet barycenter block index
  34595. var block_idx_v1 = 0; // v1 vertex block index
  34596. var block_idx_v2 = 0; // v2 vertex block index
  34597. var block_idx_v3 = 0; // v3 vertex block index
  34598. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34599. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34600. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34601. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34602. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34603. subSq = options.subDiv.max * options.subDiv.max;
  34604. options.facetPartitioning.length = 0;
  34605. }
  34606. // reset the normals
  34607. for (index = 0; index < positions.length; index++) {
  34608. normals[index] = 0.0;
  34609. }
  34610. // Loop : 1 indice triplet = 1 facet
  34611. var nbFaces = (indices.length / 3) | 0;
  34612. for (index = 0; index < nbFaces; index++) {
  34613. // get the indexes of the coordinates of each vertex of the facet
  34614. v1x = indices[index * 3] * 3;
  34615. v1y = v1x + 1;
  34616. v1z = v1x + 2;
  34617. v2x = indices[index * 3 + 1] * 3;
  34618. v2y = v2x + 1;
  34619. v2z = v2x + 2;
  34620. v3x = indices[index * 3 + 2] * 3;
  34621. v3y = v3x + 1;
  34622. v3z = v3x + 2;
  34623. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34624. p1p2y = positions[v1y] - positions[v2y];
  34625. p1p2z = positions[v1z] - positions[v2z];
  34626. p3p2x = positions[v3x] - positions[v2x];
  34627. p3p2y = positions[v3y] - positions[v2y];
  34628. p3p2z = positions[v3z] - positions[v2z];
  34629. // compute the face normal with the cross product
  34630. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34631. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34632. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34633. // normalize this normal and store it in the array facetData
  34634. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34635. length = (length === 0) ? 1.0 : length;
  34636. faceNormalx /= length;
  34637. faceNormaly /= length;
  34638. faceNormalz /= length;
  34639. if (computeFacetNormals && options) {
  34640. options.facetNormals[index].x = faceNormalx;
  34641. options.facetNormals[index].y = faceNormaly;
  34642. options.facetNormals[index].z = faceNormalz;
  34643. }
  34644. if (computeFacetPositions && options) {
  34645. // compute and the facet barycenter coordinates in the array facetPositions
  34646. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34647. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34648. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34649. }
  34650. if (computeFacetPartitioning && options) {
  34651. // store the facet indexes in arrays in the main facetPartitioning array :
  34652. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34653. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34654. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34655. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34656. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34657. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34658. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34659. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34660. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34661. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34662. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34663. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34664. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34665. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34666. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34667. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34668. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34669. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34670. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34671. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34672. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34673. // push each facet index in each block containing the vertex
  34674. options.facetPartitioning[block_idx_v1].push(index);
  34675. if (block_idx_v2 != block_idx_v1) {
  34676. options.facetPartitioning[block_idx_v2].push(index);
  34677. }
  34678. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34679. options.facetPartitioning[block_idx_v3].push(index);
  34680. }
  34681. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34682. options.facetPartitioning[block_idx_o].push(index);
  34683. }
  34684. }
  34685. if (computeDepthSort && options && options.facetPositions) {
  34686. var dsf = depthSortedFacets[index];
  34687. dsf.ind = index * 3;
  34688. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34689. }
  34690. // compute the normals anyway
  34691. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34692. normals[v1y] += faceNormaly;
  34693. normals[v1z] += faceNormalz;
  34694. normals[v2x] += faceNormalx;
  34695. normals[v2y] += faceNormaly;
  34696. normals[v2z] += faceNormalz;
  34697. normals[v3x] += faceNormalx;
  34698. normals[v3y] += faceNormaly;
  34699. normals[v3z] += faceNormalz;
  34700. }
  34701. // last normalization of each normal
  34702. for (index = 0; index < normals.length / 3; index++) {
  34703. faceNormalx = normals[index * 3];
  34704. faceNormaly = normals[index * 3 + 1];
  34705. faceNormalz = normals[index * 3 + 2];
  34706. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34707. length = (length === 0) ? 1.0 : length;
  34708. faceNormalx /= length;
  34709. faceNormaly /= length;
  34710. faceNormalz /= length;
  34711. normals[index * 3] = faceNormalx;
  34712. normals[index * 3 + 1] = faceNormaly;
  34713. normals[index * 3 + 2] = faceNormalz;
  34714. }
  34715. };
  34716. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34717. var li = indices.length;
  34718. var ln = normals.length;
  34719. var i;
  34720. var n;
  34721. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34722. switch (sideOrientation) {
  34723. case BABYLON.Mesh.FRONTSIDE:
  34724. // nothing changed
  34725. break;
  34726. case BABYLON.Mesh.BACKSIDE:
  34727. var tmp;
  34728. // indices
  34729. for (i = 0; i < li; i += 3) {
  34730. tmp = indices[i];
  34731. indices[i] = indices[i + 2];
  34732. indices[i + 2] = tmp;
  34733. }
  34734. // normals
  34735. for (n = 0; n < ln; n++) {
  34736. normals[n] = -normals[n];
  34737. }
  34738. break;
  34739. case BABYLON.Mesh.DOUBLESIDE:
  34740. // positions
  34741. var lp = positions.length;
  34742. var l = lp / 3;
  34743. for (var p = 0; p < lp; p++) {
  34744. positions[lp + p] = positions[p];
  34745. }
  34746. // indices
  34747. for (i = 0; i < li; i += 3) {
  34748. indices[i + li] = indices[i + 2] + l;
  34749. indices[i + 1 + li] = indices[i + 1] + l;
  34750. indices[i + 2 + li] = indices[i] + l;
  34751. }
  34752. // normals
  34753. for (n = 0; n < ln; n++) {
  34754. normals[ln + n] = -normals[n];
  34755. }
  34756. // uvs
  34757. var lu = uvs.length;
  34758. var u = 0;
  34759. for (u = 0; u < lu; u++) {
  34760. uvs[u + lu] = uvs[u];
  34761. }
  34762. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34763. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34764. u = 0;
  34765. for (i = 0; i < lu / 2; i++) {
  34766. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34767. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34768. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34769. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34770. u += 2;
  34771. }
  34772. break;
  34773. }
  34774. };
  34775. /**
  34776. * Creates a new VertexData from the imported parameters.
  34777. */
  34778. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34779. var vertexData = new VertexData();
  34780. // positions
  34781. var positions = parsedVertexData.positions;
  34782. if (positions) {
  34783. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34784. }
  34785. // normals
  34786. var normals = parsedVertexData.normals;
  34787. if (normals) {
  34788. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34789. }
  34790. // tangents
  34791. var tangents = parsedVertexData.tangents;
  34792. if (tangents) {
  34793. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34794. }
  34795. // uvs
  34796. var uvs = parsedVertexData.uvs;
  34797. if (uvs) {
  34798. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34799. }
  34800. // uv2s
  34801. var uv2s = parsedVertexData.uv2s;
  34802. if (uv2s) {
  34803. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34804. }
  34805. // uv3s
  34806. var uv3s = parsedVertexData.uv3s;
  34807. if (uv3s) {
  34808. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34809. }
  34810. // uv4s
  34811. var uv4s = parsedVertexData.uv4s;
  34812. if (uv4s) {
  34813. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34814. }
  34815. // uv5s
  34816. var uv5s = parsedVertexData.uv5s;
  34817. if (uv5s) {
  34818. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34819. }
  34820. // uv6s
  34821. var uv6s = parsedVertexData.uv6s;
  34822. if (uv6s) {
  34823. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34824. }
  34825. // colors
  34826. var colors = parsedVertexData.colors;
  34827. if (colors) {
  34828. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34829. }
  34830. // matricesIndices
  34831. var matricesIndices = parsedVertexData.matricesIndices;
  34832. if (matricesIndices) {
  34833. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34834. }
  34835. // matricesWeights
  34836. var matricesWeights = parsedVertexData.matricesWeights;
  34837. if (matricesWeights) {
  34838. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34839. }
  34840. // indices
  34841. var indices = parsedVertexData.indices;
  34842. if (indices) {
  34843. vertexData.indices = indices;
  34844. }
  34845. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34846. };
  34847. return VertexData;
  34848. }());
  34849. BABYLON.VertexData = VertexData;
  34850. })(BABYLON || (BABYLON = {}));
  34851. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34852. var BABYLON;
  34853. (function (BABYLON) {
  34854. /**
  34855. * Class used to store geometry data (vertex buffers + index buffer)
  34856. */
  34857. var Geometry = /** @class */ (function () {
  34858. /**
  34859. * Creates a new geometry
  34860. * @param id defines the unique ID
  34861. * @param scene defines the hosting scene
  34862. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34863. * @param updatable defines if geometry must be updatable (false by default)
  34864. * @param mesh defines the mesh that will be associated with the geometry
  34865. */
  34866. function Geometry(id, scene, vertexData, updatable, mesh) {
  34867. if (updatable === void 0) { updatable = false; }
  34868. if (mesh === void 0) { mesh = null; }
  34869. /**
  34870. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34871. */
  34872. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34873. this._totalVertices = 0;
  34874. this._isDisposed = false;
  34875. this._indexBufferIsUpdatable = false;
  34876. this.id = id;
  34877. this._engine = scene.getEngine();
  34878. this._meshes = [];
  34879. this._scene = scene;
  34880. //Init vertex buffer cache
  34881. this._vertexBuffers = {};
  34882. this._indices = [];
  34883. this._updatable = updatable;
  34884. // vertexData
  34885. if (vertexData) {
  34886. this.setAllVerticesData(vertexData, updatable);
  34887. }
  34888. else {
  34889. this._totalVertices = 0;
  34890. this._indices = [];
  34891. }
  34892. if (this._engine.getCaps().vertexArrayObject) {
  34893. this._vertexArrayObjects = {};
  34894. }
  34895. // applyToMesh
  34896. if (mesh) {
  34897. if (mesh.getClassName() === "LinesMesh") {
  34898. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34899. this.updateExtend();
  34900. }
  34901. this.applyToMesh(mesh);
  34902. mesh.computeWorldMatrix(true);
  34903. }
  34904. }
  34905. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34906. /**
  34907. * 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
  34908. */
  34909. get: function () {
  34910. return this._boundingBias;
  34911. },
  34912. /**
  34913. * 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
  34914. */
  34915. set: function (value) {
  34916. if (this._boundingBias && this._boundingBias.equals(value)) {
  34917. return;
  34918. }
  34919. this._boundingBias = value.clone();
  34920. this.updateBoundingInfo(true, null);
  34921. },
  34922. enumerable: true,
  34923. configurable: true
  34924. });
  34925. /**
  34926. * Static function used to attach a new empty geometry to a mesh
  34927. * @param mesh defines the mesh to attach the geometry to
  34928. * @returns the new {BABYLON.Geometry}
  34929. */
  34930. Geometry.CreateGeometryForMesh = function (mesh) {
  34931. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34932. geometry.applyToMesh(mesh);
  34933. return geometry;
  34934. };
  34935. Object.defineProperty(Geometry.prototype, "extend", {
  34936. /**
  34937. * Gets the current extend of the geometry
  34938. */
  34939. get: function () {
  34940. return this._extend;
  34941. },
  34942. enumerable: true,
  34943. configurable: true
  34944. });
  34945. /**
  34946. * Gets the hosting scene
  34947. * @returns the hosting {BABYLON.Scene}
  34948. */
  34949. Geometry.prototype.getScene = function () {
  34950. return this._scene;
  34951. };
  34952. /**
  34953. * Gets the hosting engine
  34954. * @returns the hosting {BABYLON.Engine}
  34955. */
  34956. Geometry.prototype.getEngine = function () {
  34957. return this._engine;
  34958. };
  34959. /**
  34960. * Defines if the geometry is ready to use
  34961. * @returns true if the geometry is ready to be used
  34962. */
  34963. Geometry.prototype.isReady = function () {
  34964. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34965. };
  34966. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34967. /**
  34968. * Gets a value indicating that the geometry should not be serialized
  34969. */
  34970. get: function () {
  34971. for (var index = 0; index < this._meshes.length; index++) {
  34972. if (!this._meshes[index].doNotSerialize) {
  34973. return false;
  34974. }
  34975. }
  34976. return true;
  34977. },
  34978. enumerable: true,
  34979. configurable: true
  34980. });
  34981. /** @ignore */
  34982. Geometry.prototype._rebuild = function () {
  34983. if (this._vertexArrayObjects) {
  34984. this._vertexArrayObjects = {};
  34985. }
  34986. // Index buffer
  34987. if (this._meshes.length !== 0 && this._indices) {
  34988. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34989. }
  34990. // Vertex buffers
  34991. for (var key in this._vertexBuffers) {
  34992. var vertexBuffer = this._vertexBuffers[key];
  34993. vertexBuffer._rebuild();
  34994. }
  34995. };
  34996. /**
  34997. * Affects all gemetry data in one call
  34998. * @param vertexData defines the geometry data
  34999. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  35000. */
  35001. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35002. vertexData.applyToGeometry(this, updatable);
  35003. this.notifyUpdate();
  35004. };
  35005. /**
  35006. * Set specific vertex data
  35007. * @param kind defines the data kind (Position, normal, etc...)
  35008. * @param data defines the vertex data to use
  35009. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  35010. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  35011. */
  35012. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  35013. if (updatable === void 0) { updatable = false; }
  35014. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  35015. this.setVerticesBuffer(buffer);
  35016. };
  35017. /**
  35018. * Removes a specific vertex data
  35019. * @param kind defines the data kind (Position, normal, etc...)
  35020. */
  35021. Geometry.prototype.removeVerticesData = function (kind) {
  35022. if (this._vertexBuffers[kind]) {
  35023. this._vertexBuffers[kind].dispose();
  35024. delete this._vertexBuffers[kind];
  35025. }
  35026. };
  35027. /**
  35028. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  35029. * @param buffer defines the vertex buffer to use
  35030. */
  35031. Geometry.prototype.setVerticesBuffer = function (buffer) {
  35032. var kind = buffer.getKind();
  35033. if (this._vertexBuffers[kind]) {
  35034. this._vertexBuffers[kind].dispose();
  35035. }
  35036. this._vertexBuffers[kind] = buffer;
  35037. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35038. var data = buffer.getData();
  35039. var stride = buffer.getStrideSize();
  35040. this._totalVertices = data.length / stride;
  35041. this.updateExtend(data, stride);
  35042. this._resetPointsArrayCache();
  35043. var meshes = this._meshes;
  35044. var numOfMeshes = meshes.length;
  35045. for (var index = 0; index < numOfMeshes; index++) {
  35046. var mesh = meshes[index];
  35047. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35048. mesh._createGlobalSubMesh(false);
  35049. mesh.computeWorldMatrix(true);
  35050. }
  35051. }
  35052. this.notifyUpdate(kind);
  35053. if (this._vertexArrayObjects) {
  35054. this._disposeVertexArrayObjects();
  35055. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  35056. }
  35057. };
  35058. /**
  35059. * Update a specific vertex buffer
  35060. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  35061. * It will do nothing if the buffer is not updatable
  35062. * @param kind defines the data kind (Position, normal, etc...)
  35063. * @param data defines the data to use
  35064. * @param offset defines the offset in the target buffer where to store the data
  35065. */
  35066. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  35067. var vertexBuffer = this.getVertexBuffer(kind);
  35068. if (!vertexBuffer) {
  35069. return;
  35070. }
  35071. vertexBuffer.updateDirectly(data, offset);
  35072. this.notifyUpdate(kind);
  35073. };
  35074. /**
  35075. * Update a specific vertex buffer
  35076. * This function will create a new buffer if the current one is not updatable
  35077. * @param kind defines the data kind (Position, normal, etc...)
  35078. * @param data defines the data to use
  35079. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  35080. */
  35081. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  35082. if (updateExtends === void 0) { updateExtends = false; }
  35083. var vertexBuffer = this.getVertexBuffer(kind);
  35084. if (!vertexBuffer) {
  35085. return;
  35086. }
  35087. vertexBuffer.update(data);
  35088. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35089. var stride = vertexBuffer.getStrideSize();
  35090. this._totalVertices = data.length / stride;
  35091. this.updateBoundingInfo(updateExtends, data);
  35092. }
  35093. this.notifyUpdate(kind);
  35094. };
  35095. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  35096. if (updateExtends) {
  35097. this.updateExtend(data);
  35098. }
  35099. var meshes = this._meshes;
  35100. var numOfMeshes = meshes.length;
  35101. this._resetPointsArrayCache();
  35102. for (var index = 0; index < numOfMeshes; index++) {
  35103. var mesh = meshes[index];
  35104. if (updateExtends) {
  35105. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35106. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35107. var subMesh = mesh.subMeshes[subIndex];
  35108. subMesh.refreshBoundingInfo();
  35109. }
  35110. }
  35111. }
  35112. };
  35113. /** @ignore */
  35114. Geometry.prototype._bind = function (effect, indexToBind) {
  35115. if (!effect) {
  35116. return;
  35117. }
  35118. if (indexToBind === undefined) {
  35119. indexToBind = this._indexBuffer;
  35120. }
  35121. var vbs = this.getVertexBuffers();
  35122. if (!vbs) {
  35123. return;
  35124. }
  35125. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  35126. this._engine.bindBuffers(vbs, indexToBind, effect);
  35127. return;
  35128. }
  35129. // Using VAO
  35130. if (!this._vertexArrayObjects[effect.key]) {
  35131. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  35132. }
  35133. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  35134. };
  35135. /**
  35136. * Gets total number of vertices
  35137. * @returns the total number of vertices
  35138. */
  35139. Geometry.prototype.getTotalVertices = function () {
  35140. if (!this.isReady()) {
  35141. return 0;
  35142. }
  35143. return this._totalVertices;
  35144. };
  35145. /**
  35146. * Gets a specific vertex data attached to this geometry
  35147. * @param kind defines the data kind (Position, normal, etc...)
  35148. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35149. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  35150. * @returns a float array containing vertex data
  35151. */
  35152. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  35153. var vertexBuffer = this.getVertexBuffer(kind);
  35154. if (!vertexBuffer) {
  35155. return null;
  35156. }
  35157. var orig = vertexBuffer.getData();
  35158. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35159. return orig;
  35160. }
  35161. else {
  35162. var len = orig.length;
  35163. var copy = [];
  35164. for (var i = 0; i < len; i++) {
  35165. copy.push(orig[i]);
  35166. }
  35167. return copy;
  35168. }
  35169. };
  35170. /**
  35171. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35172. * @param kind defines the data kind (Position, normal, etc...)
  35173. * @returns true if the vertex buffer with the specified kind is updatable
  35174. */
  35175. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35176. var vb = this._vertexBuffers[kind];
  35177. if (!vb) {
  35178. return false;
  35179. }
  35180. return vb.isUpdatable();
  35181. };
  35182. /**
  35183. * Gets a specific vertex buffer
  35184. * @param kind defines the data kind (Position, normal, etc...)
  35185. * @returns a {BABYLON.VertexBuffer}
  35186. */
  35187. Geometry.prototype.getVertexBuffer = function (kind) {
  35188. if (!this.isReady()) {
  35189. return null;
  35190. }
  35191. return this._vertexBuffers[kind];
  35192. };
  35193. /**
  35194. * Returns all vertex buffers
  35195. * @return an object holding all vertex buffers indexed by kind
  35196. */
  35197. Geometry.prototype.getVertexBuffers = function () {
  35198. if (!this.isReady()) {
  35199. return null;
  35200. }
  35201. return this._vertexBuffers;
  35202. };
  35203. /**
  35204. * Gets a boolean indicating if specific vertex buffer is present
  35205. * @param kind defines the data kind (Position, normal, etc...)
  35206. * @returns true if data is present
  35207. */
  35208. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35209. if (!this._vertexBuffers) {
  35210. if (this._delayInfo) {
  35211. return this._delayInfo.indexOf(kind) !== -1;
  35212. }
  35213. return false;
  35214. }
  35215. return this._vertexBuffers[kind] !== undefined;
  35216. };
  35217. /**
  35218. * Gets a list of all attached data kinds (Position, normal, etc...)
  35219. * @returns a list of string containing all kinds
  35220. */
  35221. Geometry.prototype.getVerticesDataKinds = function () {
  35222. var result = [];
  35223. var kind;
  35224. if (!this._vertexBuffers && this._delayInfo) {
  35225. for (kind in this._delayInfo) {
  35226. result.push(kind);
  35227. }
  35228. }
  35229. else {
  35230. for (kind in this._vertexBuffers) {
  35231. result.push(kind);
  35232. }
  35233. }
  35234. return result;
  35235. };
  35236. /**
  35237. * Update index buffer
  35238. * @param indices defines the indices to store in the index buffer
  35239. * @param offset defines the offset in the target buffer where to store the data
  35240. */
  35241. Geometry.prototype.updateIndices = function (indices, offset) {
  35242. if (!this._indexBuffer) {
  35243. return;
  35244. }
  35245. if (!this._indexBufferIsUpdatable) {
  35246. this.setIndices(indices, null, true);
  35247. }
  35248. else {
  35249. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35250. }
  35251. };
  35252. /**
  35253. * Creates a new index buffer
  35254. * @param indices defines the indices to store in the index buffer
  35255. * @param totalVertices defines the total number of vertices (could be null)
  35256. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35257. */
  35258. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35259. if (totalVertices === void 0) { totalVertices = null; }
  35260. if (updatable === void 0) { updatable = false; }
  35261. if (this._indexBuffer) {
  35262. this._engine._releaseBuffer(this._indexBuffer);
  35263. }
  35264. this._disposeVertexArrayObjects();
  35265. this._indices = indices;
  35266. this._indexBufferIsUpdatable = updatable;
  35267. if (this._meshes.length !== 0 && this._indices) {
  35268. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35269. }
  35270. if (totalVertices != undefined) {
  35271. this._totalVertices = totalVertices;
  35272. }
  35273. var meshes = this._meshes;
  35274. var numOfMeshes = meshes.length;
  35275. for (var index = 0; index < numOfMeshes; index++) {
  35276. meshes[index]._createGlobalSubMesh(true);
  35277. }
  35278. this.notifyUpdate();
  35279. };
  35280. /**
  35281. * Return the total number of indices
  35282. * @returns the total number of indices
  35283. */
  35284. Geometry.prototype.getTotalIndices = function () {
  35285. if (!this.isReady()) {
  35286. return 0;
  35287. }
  35288. return this._indices.length;
  35289. };
  35290. /**
  35291. * Gets the index buffer array
  35292. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35293. * @returns the index buffer array
  35294. */
  35295. Geometry.prototype.getIndices = function (copyWhenShared) {
  35296. if (!this.isReady()) {
  35297. return null;
  35298. }
  35299. var orig = this._indices;
  35300. if (!copyWhenShared || this._meshes.length === 1) {
  35301. return orig;
  35302. }
  35303. else {
  35304. var len = orig.length;
  35305. var copy = [];
  35306. for (var i = 0; i < len; i++) {
  35307. copy.push(orig[i]);
  35308. }
  35309. return copy;
  35310. }
  35311. };
  35312. /**
  35313. * Gets the index buffer
  35314. * @return the index buffer
  35315. */
  35316. Geometry.prototype.getIndexBuffer = function () {
  35317. if (!this.isReady()) {
  35318. return null;
  35319. }
  35320. return this._indexBuffer;
  35321. };
  35322. /** @ignore */
  35323. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35324. if (effect === void 0) { effect = null; }
  35325. if (!effect || !this._vertexArrayObjects) {
  35326. return;
  35327. }
  35328. if (this._vertexArrayObjects[effect.key]) {
  35329. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35330. delete this._vertexArrayObjects[effect.key];
  35331. }
  35332. };
  35333. /**
  35334. * Release the associated resources for a specific mesh
  35335. * @param mesh defines the source mesh
  35336. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35337. */
  35338. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35339. var meshes = this._meshes;
  35340. var index = meshes.indexOf(mesh);
  35341. if (index === -1) {
  35342. return;
  35343. }
  35344. meshes.splice(index, 1);
  35345. mesh._geometry = null;
  35346. if (meshes.length === 0 && shouldDispose) {
  35347. this.dispose();
  35348. }
  35349. };
  35350. /**
  35351. * Apply current geometry to a given mesh
  35352. * @param mesh defines the mesh to apply geometry to
  35353. */
  35354. Geometry.prototype.applyToMesh = function (mesh) {
  35355. if (mesh._geometry === this) {
  35356. return;
  35357. }
  35358. var previousGeometry = mesh._geometry;
  35359. if (previousGeometry) {
  35360. previousGeometry.releaseForMesh(mesh);
  35361. }
  35362. var meshes = this._meshes;
  35363. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35364. mesh._geometry = this;
  35365. this._scene.pushGeometry(this);
  35366. meshes.push(mesh);
  35367. if (this.isReady()) {
  35368. this._applyToMesh(mesh);
  35369. }
  35370. else {
  35371. mesh._boundingInfo = this._boundingInfo;
  35372. }
  35373. };
  35374. Geometry.prototype.updateExtend = function (data, stride) {
  35375. if (data === void 0) { data = null; }
  35376. if (!data) {
  35377. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35378. }
  35379. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35380. };
  35381. Geometry.prototype._applyToMesh = function (mesh) {
  35382. var numOfMeshes = this._meshes.length;
  35383. // vertexBuffers
  35384. for (var kind in this._vertexBuffers) {
  35385. if (numOfMeshes === 1) {
  35386. this._vertexBuffers[kind].create();
  35387. }
  35388. var buffer = this._vertexBuffers[kind].getBuffer();
  35389. if (buffer)
  35390. buffer.references = numOfMeshes;
  35391. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35392. if (!this._extend) {
  35393. this.updateExtend(this._vertexBuffers[kind].getData());
  35394. }
  35395. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35396. mesh._createGlobalSubMesh(false);
  35397. //bounding info was just created again, world matrix should be applied again.
  35398. mesh._updateBoundingInfo();
  35399. }
  35400. }
  35401. // indexBuffer
  35402. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35403. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35404. }
  35405. if (this._indexBuffer) {
  35406. this._indexBuffer.references = numOfMeshes;
  35407. }
  35408. };
  35409. Geometry.prototype.notifyUpdate = function (kind) {
  35410. if (this.onGeometryUpdated) {
  35411. this.onGeometryUpdated(this, kind);
  35412. }
  35413. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35414. var mesh = _a[_i];
  35415. mesh._markSubMeshesAsAttributesDirty();
  35416. }
  35417. };
  35418. /**
  35419. * Load the geometry if it was flagged as delay loaded
  35420. * @param scene defines the hosting scene
  35421. * @param onLoaded defines a callback called when the geometry is loaded
  35422. */
  35423. Geometry.prototype.load = function (scene, onLoaded) {
  35424. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35425. return;
  35426. }
  35427. if (this.isReady()) {
  35428. if (onLoaded) {
  35429. onLoaded();
  35430. }
  35431. return;
  35432. }
  35433. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35434. this._queueLoad(scene, onLoaded);
  35435. };
  35436. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35437. var _this = this;
  35438. if (!this.delayLoadingFile) {
  35439. return;
  35440. }
  35441. scene._addPendingData(this);
  35442. scene._loadFile(this.delayLoadingFile, function (data) {
  35443. if (!_this._delayLoadingFunction) {
  35444. return;
  35445. }
  35446. _this._delayLoadingFunction(JSON.parse(data), _this);
  35447. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35448. _this._delayInfo = [];
  35449. scene._removePendingData(_this);
  35450. var meshes = _this._meshes;
  35451. var numOfMeshes = meshes.length;
  35452. for (var index = 0; index < numOfMeshes; index++) {
  35453. _this._applyToMesh(meshes[index]);
  35454. }
  35455. if (onLoaded) {
  35456. onLoaded();
  35457. }
  35458. }, undefined, true);
  35459. };
  35460. /**
  35461. * Invert the geometry to move from a right handed system to a left handed one.
  35462. */
  35463. Geometry.prototype.toLeftHanded = function () {
  35464. // Flip faces
  35465. var tIndices = this.getIndices(false);
  35466. if (tIndices != null && tIndices.length > 0) {
  35467. for (var i = 0; i < tIndices.length; i += 3) {
  35468. var tTemp = tIndices[i + 0];
  35469. tIndices[i + 0] = tIndices[i + 2];
  35470. tIndices[i + 2] = tTemp;
  35471. }
  35472. this.setIndices(tIndices);
  35473. }
  35474. // Negate position.z
  35475. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35476. if (tPositions != null && tPositions.length > 0) {
  35477. for (var i = 0; i < tPositions.length; i += 3) {
  35478. tPositions[i + 2] = -tPositions[i + 2];
  35479. }
  35480. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35481. }
  35482. // Negate normal.z
  35483. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35484. if (tNormals != null && tNormals.length > 0) {
  35485. for (var i = 0; i < tNormals.length; i += 3) {
  35486. tNormals[i + 2] = -tNormals[i + 2];
  35487. }
  35488. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35489. }
  35490. };
  35491. // Cache
  35492. /** @ignore */
  35493. Geometry.prototype._resetPointsArrayCache = function () {
  35494. this._positions = null;
  35495. };
  35496. /** @ignore */
  35497. Geometry.prototype._generatePointsArray = function () {
  35498. if (this._positions)
  35499. return true;
  35500. this._positions = [];
  35501. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35502. if (!data) {
  35503. return false;
  35504. }
  35505. for (var index = 0; index < data.length; index += 3) {
  35506. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35507. }
  35508. return true;
  35509. };
  35510. /**
  35511. * Gets a value indicating if the geometry is disposed
  35512. * @returns true if the geometry was disposed
  35513. */
  35514. Geometry.prototype.isDisposed = function () {
  35515. return this._isDisposed;
  35516. };
  35517. Geometry.prototype._disposeVertexArrayObjects = function () {
  35518. if (this._vertexArrayObjects) {
  35519. for (var kind in this._vertexArrayObjects) {
  35520. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35521. }
  35522. this._vertexArrayObjects = {};
  35523. }
  35524. };
  35525. /**
  35526. * Free all associated resources
  35527. */
  35528. Geometry.prototype.dispose = function () {
  35529. var meshes = this._meshes;
  35530. var numOfMeshes = meshes.length;
  35531. var index;
  35532. for (index = 0; index < numOfMeshes; index++) {
  35533. this.releaseForMesh(meshes[index]);
  35534. }
  35535. this._meshes = [];
  35536. this._disposeVertexArrayObjects();
  35537. for (var kind in this._vertexBuffers) {
  35538. this._vertexBuffers[kind].dispose();
  35539. }
  35540. this._vertexBuffers = {};
  35541. this._totalVertices = 0;
  35542. if (this._indexBuffer) {
  35543. this._engine._releaseBuffer(this._indexBuffer);
  35544. }
  35545. this._indexBuffer = null;
  35546. this._indices = [];
  35547. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35548. this.delayLoadingFile = null;
  35549. this._delayLoadingFunction = null;
  35550. this._delayInfo = [];
  35551. this._boundingInfo = null;
  35552. this._scene.removeGeometry(this);
  35553. this._isDisposed = true;
  35554. };
  35555. /**
  35556. * Clone the current geometry into a new geometry
  35557. * @param id defines the unique ID of the new geometry
  35558. * @returns a new geometry object
  35559. */
  35560. Geometry.prototype.copy = function (id) {
  35561. var vertexData = new BABYLON.VertexData();
  35562. vertexData.indices = [];
  35563. var indices = this.getIndices();
  35564. if (indices) {
  35565. for (var index = 0; index < indices.length; index++) {
  35566. vertexData.indices.push(indices[index]);
  35567. }
  35568. }
  35569. var updatable = false;
  35570. var stopChecking = false;
  35571. var kind;
  35572. for (kind in this._vertexBuffers) {
  35573. // using slice() to make a copy of the array and not just reference it
  35574. var data = this.getVerticesData(kind);
  35575. if (data instanceof Float32Array) {
  35576. vertexData.set(new Float32Array(data), kind);
  35577. }
  35578. else {
  35579. vertexData.set(data.slice(0), kind);
  35580. }
  35581. if (!stopChecking) {
  35582. var vb = this.getVertexBuffer(kind);
  35583. if (vb) {
  35584. updatable = vb.isUpdatable();
  35585. stopChecking = !updatable;
  35586. }
  35587. }
  35588. }
  35589. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35590. geometry.delayLoadState = this.delayLoadState;
  35591. geometry.delayLoadingFile = this.delayLoadingFile;
  35592. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35593. for (kind in this._delayInfo) {
  35594. geometry._delayInfo = geometry._delayInfo || [];
  35595. geometry._delayInfo.push(kind);
  35596. }
  35597. // Bounding info
  35598. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35599. return geometry;
  35600. };
  35601. /**
  35602. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35603. * @return a JSON representation of the current geometry data (without the vertices data)
  35604. */
  35605. Geometry.prototype.serialize = function () {
  35606. var serializationObject = {};
  35607. serializationObject.id = this.id;
  35608. serializationObject.updatable = this._updatable;
  35609. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35610. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35611. }
  35612. return serializationObject;
  35613. };
  35614. Geometry.prototype.toNumberArray = function (origin) {
  35615. if (Array.isArray(origin)) {
  35616. return origin;
  35617. }
  35618. else {
  35619. return Array.prototype.slice.call(origin);
  35620. }
  35621. };
  35622. /**
  35623. * Serialize all vertices data into a JSON oject
  35624. * @returns a JSON representation of the current geometry data
  35625. */
  35626. Geometry.prototype.serializeVerticeData = function () {
  35627. var serializationObject = this.serialize();
  35628. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35629. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35630. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35631. serializationObject.positions._updatable = true;
  35632. }
  35633. }
  35634. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35635. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35636. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35637. serializationObject.normals._updatable = true;
  35638. }
  35639. }
  35640. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35641. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35642. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35643. serializationObject.tangets._updatable = true;
  35644. }
  35645. }
  35646. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35647. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35648. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35649. serializationObject.uvs._updatable = true;
  35650. }
  35651. }
  35652. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35653. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35654. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35655. serializationObject.uv2s._updatable = true;
  35656. }
  35657. }
  35658. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35659. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35660. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35661. serializationObject.uv3s._updatable = true;
  35662. }
  35663. }
  35664. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35665. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35666. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35667. serializationObject.uv4s._updatable = true;
  35668. }
  35669. }
  35670. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35671. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35672. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35673. serializationObject.uv5s._updatable = true;
  35674. }
  35675. }
  35676. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35677. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35678. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35679. serializationObject.uv6s._updatable = true;
  35680. }
  35681. }
  35682. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35683. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35684. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35685. serializationObject.colors._updatable = true;
  35686. }
  35687. }
  35688. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35689. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35690. serializationObject.matricesIndices._isExpanded = true;
  35691. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35692. serializationObject.matricesIndices._updatable = true;
  35693. }
  35694. }
  35695. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35696. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35697. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35698. serializationObject.matricesWeights._updatable = true;
  35699. }
  35700. }
  35701. serializationObject.indices = this.toNumberArray(this.getIndices());
  35702. return serializationObject;
  35703. };
  35704. // Statics
  35705. /**
  35706. * Extracts a clone of a mesh geometry
  35707. * @param mesh defines the source mesh
  35708. * @param id defines the unique ID of the new geometry object
  35709. * @returns the new geometry object
  35710. */
  35711. Geometry.ExtractFromMesh = function (mesh, id) {
  35712. var geometry = mesh._geometry;
  35713. if (!geometry) {
  35714. return null;
  35715. }
  35716. return geometry.copy(id);
  35717. };
  35718. /**
  35719. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35720. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35721. * Be aware Math.random() could cause collisions, but:
  35722. * "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"
  35723. * @returns a string containing a new GUID
  35724. */
  35725. Geometry.RandomId = function () {
  35726. return BABYLON.Tools.RandomId();
  35727. };
  35728. /** @ignore */
  35729. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35730. var scene = mesh.getScene();
  35731. // Geometry
  35732. var geometryId = parsedGeometry.geometryId;
  35733. if (geometryId) {
  35734. var geometry = scene.getGeometryByID(geometryId);
  35735. if (geometry) {
  35736. geometry.applyToMesh(mesh);
  35737. }
  35738. }
  35739. else if (parsedGeometry instanceof ArrayBuffer) {
  35740. var binaryInfo = mesh._binaryInfo;
  35741. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35742. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35743. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35744. }
  35745. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35746. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35747. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35748. }
  35749. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35750. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35751. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35752. }
  35753. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35754. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35755. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35756. }
  35757. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35758. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35759. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35760. }
  35761. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35762. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35763. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35764. }
  35765. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35766. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35767. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35768. }
  35769. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35770. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35771. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35772. }
  35773. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35774. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35775. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35776. }
  35777. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35778. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35779. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35780. }
  35781. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35782. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35783. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35784. }
  35785. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35786. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35787. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35788. }
  35789. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35790. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35791. mesh.setIndices(indicesData, null);
  35792. }
  35793. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35794. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35795. mesh.subMeshes = [];
  35796. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35797. var materialIndex = subMeshesData[(i * 5) + 0];
  35798. var verticesStart = subMeshesData[(i * 5) + 1];
  35799. var verticesCount = subMeshesData[(i * 5) + 2];
  35800. var indexStart = subMeshesData[(i * 5) + 3];
  35801. var indexCount = subMeshesData[(i * 5) + 4];
  35802. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35803. }
  35804. }
  35805. }
  35806. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35807. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35808. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35809. if (parsedGeometry.tangents) {
  35810. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35811. }
  35812. if (parsedGeometry.uvs) {
  35813. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35814. }
  35815. if (parsedGeometry.uvs2) {
  35816. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35817. }
  35818. if (parsedGeometry.uvs3) {
  35819. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35820. }
  35821. if (parsedGeometry.uvs4) {
  35822. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35823. }
  35824. if (parsedGeometry.uvs5) {
  35825. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35826. }
  35827. if (parsedGeometry.uvs6) {
  35828. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35829. }
  35830. if (parsedGeometry.colors) {
  35831. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35832. }
  35833. if (parsedGeometry.matricesIndices) {
  35834. if (!parsedGeometry.matricesIndices._isExpanded) {
  35835. var floatIndices = [];
  35836. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35837. var matricesIndex = parsedGeometry.matricesIndices[i];
  35838. floatIndices.push(matricesIndex & 0x000000FF);
  35839. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35840. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35841. floatIndices.push(matricesIndex >> 24);
  35842. }
  35843. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35844. }
  35845. else {
  35846. delete parsedGeometry.matricesIndices._isExpanded;
  35847. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35848. }
  35849. }
  35850. if (parsedGeometry.matricesIndicesExtra) {
  35851. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35852. var floatIndices = [];
  35853. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35854. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35855. floatIndices.push(matricesIndex & 0x000000FF);
  35856. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35857. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35858. floatIndices.push(matricesIndex >> 24);
  35859. }
  35860. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35861. }
  35862. else {
  35863. delete parsedGeometry.matricesIndices._isExpanded;
  35864. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35865. }
  35866. }
  35867. if (parsedGeometry.matricesWeights) {
  35868. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35869. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35870. }
  35871. if (parsedGeometry.matricesWeightsExtra) {
  35872. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35873. }
  35874. mesh.setIndices(parsedGeometry.indices, null);
  35875. }
  35876. // SubMeshes
  35877. if (parsedGeometry.subMeshes) {
  35878. mesh.subMeshes = [];
  35879. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35880. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35881. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35882. }
  35883. }
  35884. // Flat shading
  35885. if (mesh._shouldGenerateFlatShading) {
  35886. mesh.convertToFlatShadedMesh();
  35887. delete mesh._shouldGenerateFlatShading;
  35888. }
  35889. // Update
  35890. mesh.computeWorldMatrix(true);
  35891. // Octree
  35892. var sceneOctree = scene.selectionOctree;
  35893. if (sceneOctree !== undefined && sceneOctree !== null) {
  35894. sceneOctree.addMesh(mesh);
  35895. }
  35896. };
  35897. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35898. var epsilon = 1e-3;
  35899. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35900. return;
  35901. }
  35902. var noInfluenceBoneIndex = 0.0;
  35903. if (parsedGeometry.skeletonId > -1) {
  35904. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35905. if (!skeleton) {
  35906. return;
  35907. }
  35908. noInfluenceBoneIndex = skeleton.bones.length;
  35909. }
  35910. else {
  35911. return;
  35912. }
  35913. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35914. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35915. var matricesWeights = parsedGeometry.matricesWeights;
  35916. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35917. var influencers = parsedGeometry.numBoneInfluencer;
  35918. var size = matricesWeights.length;
  35919. for (var i = 0; i < size; i += 4) {
  35920. var weight = 0.0;
  35921. var firstZeroWeight = -1;
  35922. for (var j = 0; j < 4; j++) {
  35923. var w = matricesWeights[i + j];
  35924. weight += w;
  35925. if (w < epsilon && firstZeroWeight < 0) {
  35926. firstZeroWeight = j;
  35927. }
  35928. }
  35929. if (matricesWeightsExtra) {
  35930. for (var j = 0; j < 4; j++) {
  35931. var w = matricesWeightsExtra[i + j];
  35932. weight += w;
  35933. if (w < epsilon && firstZeroWeight < 0) {
  35934. firstZeroWeight = j + 4;
  35935. }
  35936. }
  35937. }
  35938. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35939. firstZeroWeight = influencers - 1;
  35940. }
  35941. if (weight > epsilon) {
  35942. var mweight = 1.0 / weight;
  35943. for (var j = 0; j < 4; j++) {
  35944. matricesWeights[i + j] *= mweight;
  35945. }
  35946. if (matricesWeightsExtra) {
  35947. for (var j = 0; j < 4; j++) {
  35948. matricesWeightsExtra[i + j] *= mweight;
  35949. }
  35950. }
  35951. }
  35952. else {
  35953. if (firstZeroWeight >= 4) {
  35954. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35955. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35956. }
  35957. else {
  35958. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35959. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35960. }
  35961. }
  35962. }
  35963. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35964. if (parsedGeometry.matricesWeightsExtra) {
  35965. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35966. }
  35967. };
  35968. /**
  35969. * Create a new geometry from persisted data (Using .babylon file format)
  35970. * @param parsedVertexData defines the persisted data
  35971. * @param scene defines the hosting scene
  35972. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35973. * @returns the new geometry object
  35974. */
  35975. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35976. if (scene.getGeometryByID(parsedVertexData.id)) {
  35977. return null; // null since geometry could be something else than a box...
  35978. }
  35979. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35980. if (BABYLON.Tags) {
  35981. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35982. }
  35983. if (parsedVertexData.delayLoadingFile) {
  35984. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35985. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35986. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35987. geometry._delayInfo = [];
  35988. if (parsedVertexData.hasUVs) {
  35989. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35990. }
  35991. if (parsedVertexData.hasUVs2) {
  35992. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35993. }
  35994. if (parsedVertexData.hasUVs3) {
  35995. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35996. }
  35997. if (parsedVertexData.hasUVs4) {
  35998. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35999. }
  36000. if (parsedVertexData.hasUVs5) {
  36001. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36002. }
  36003. if (parsedVertexData.hasUVs6) {
  36004. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36005. }
  36006. if (parsedVertexData.hasColors) {
  36007. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36008. }
  36009. if (parsedVertexData.hasMatricesIndices) {
  36010. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36011. }
  36012. if (parsedVertexData.hasMatricesWeights) {
  36013. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36014. }
  36015. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36016. }
  36017. else {
  36018. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36019. }
  36020. scene.pushGeometry(geometry, true);
  36021. return geometry;
  36022. };
  36023. return Geometry;
  36024. }());
  36025. BABYLON.Geometry = Geometry;
  36026. // Primitives
  36027. /// Abstract class
  36028. /**
  36029. * Abstract class used to provide common services for all typed geometries
  36030. */
  36031. var _PrimitiveGeometry = /** @class */ (function (_super) {
  36032. __extends(_PrimitiveGeometry, _super);
  36033. /**
  36034. * Creates a new typed geometry
  36035. * @param id defines the unique ID of the geometry
  36036. * @param scene defines the hosting scene
  36037. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36038. * @param mesh defines the hosting mesh (can be null)
  36039. */
  36040. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  36041. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  36042. if (mesh === void 0) { mesh = null; }
  36043. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  36044. _this._canBeRegenerated = _canBeRegenerated;
  36045. _this._beingRegenerated = true;
  36046. _this.regenerate();
  36047. _this._beingRegenerated = false;
  36048. return _this;
  36049. }
  36050. /**
  36051. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  36052. * @returns true if the geometry can be regenerated
  36053. */
  36054. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  36055. return this._canBeRegenerated;
  36056. };
  36057. /**
  36058. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  36059. */
  36060. _PrimitiveGeometry.prototype.regenerate = function () {
  36061. if (!this._canBeRegenerated) {
  36062. return;
  36063. }
  36064. this._beingRegenerated = true;
  36065. this.setAllVerticesData(this._regenerateVertexData(), false);
  36066. this._beingRegenerated = false;
  36067. };
  36068. /**
  36069. * Clone the geometry
  36070. * @param id defines the unique ID of the new geometry
  36071. * @returns the new geometry
  36072. */
  36073. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  36074. return _super.prototype.copy.call(this, id);
  36075. };
  36076. // overrides
  36077. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36078. if (!this._beingRegenerated) {
  36079. return;
  36080. }
  36081. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36082. };
  36083. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  36084. if (!this._beingRegenerated) {
  36085. return;
  36086. }
  36087. _super.prototype.setVerticesData.call(this, kind, data, false);
  36088. };
  36089. // to override
  36090. /** @ignore */
  36091. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  36092. throw new Error("Abstract method");
  36093. };
  36094. _PrimitiveGeometry.prototype.copy = function (id) {
  36095. throw new Error("Must be overriden in sub-classes.");
  36096. };
  36097. _PrimitiveGeometry.prototype.serialize = function () {
  36098. var serializationObject = _super.prototype.serialize.call(this);
  36099. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36100. return serializationObject;
  36101. };
  36102. return _PrimitiveGeometry;
  36103. }(Geometry));
  36104. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  36105. /**
  36106. * Creates a ribbon geometry
  36107. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  36108. */
  36109. var RibbonGeometry = /** @class */ (function (_super) {
  36110. __extends(RibbonGeometry, _super);
  36111. /**
  36112. * Creates a ribbon geometry
  36113. * @param id defines the unique ID of the geometry
  36114. * @param scene defines the hosting scene
  36115. * @param pathArray defines the array of paths to use
  36116. * @param closeArray defines if the last path and the first path must be joined
  36117. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  36118. * @param offset defines the offset between points
  36119. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36120. * @param mesh defines the hosting mesh (can be null)
  36121. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36122. */
  36123. function RibbonGeometry(id, scene,
  36124. /**
  36125. * Defines the array of paths to use
  36126. */
  36127. pathArray,
  36128. /**
  36129. * Defines if the last and first points of each path in your pathArray must be joined
  36130. */
  36131. closeArray,
  36132. /**
  36133. * Defines if the last and first points of each path in your pathArray must be joined
  36134. */
  36135. closePath,
  36136. /**
  36137. * Defines the offset between points
  36138. */
  36139. offset, canBeRegenerated, mesh,
  36140. /**
  36141. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36142. */
  36143. side) {
  36144. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36145. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36146. _this.pathArray = pathArray;
  36147. _this.closeArray = closeArray;
  36148. _this.closePath = closePath;
  36149. _this.offset = offset;
  36150. _this.side = side;
  36151. return _this;
  36152. }
  36153. /** @ignore */
  36154. RibbonGeometry.prototype._regenerateVertexData = function () {
  36155. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36156. };
  36157. RibbonGeometry.prototype.copy = function (id) {
  36158. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36159. };
  36160. return RibbonGeometry;
  36161. }(_PrimitiveGeometry));
  36162. BABYLON.RibbonGeometry = RibbonGeometry;
  36163. /**
  36164. * Creates a box geometry
  36165. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36166. */
  36167. var BoxGeometry = /** @class */ (function (_super) {
  36168. __extends(BoxGeometry, _super);
  36169. /**
  36170. * Creates a box geometry
  36171. * @param id defines the unique ID of the geometry
  36172. * @param scene defines the hosting scene
  36173. * @param size defines the zise of the box (width, height and depth are the same)
  36174. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36175. * @param mesh defines the hosting mesh (can be null)
  36176. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36177. */
  36178. function BoxGeometry(id, scene,
  36179. /**
  36180. * Defines the zise of the box (width, height and depth are the same)
  36181. */
  36182. size, canBeRegenerated, mesh,
  36183. /**
  36184. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36185. */
  36186. side) {
  36187. if (mesh === void 0) { mesh = null; }
  36188. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36189. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36190. _this.size = size;
  36191. _this.side = side;
  36192. return _this;
  36193. }
  36194. BoxGeometry.prototype._regenerateVertexData = function () {
  36195. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36196. };
  36197. BoxGeometry.prototype.copy = function (id) {
  36198. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36199. };
  36200. BoxGeometry.prototype.serialize = function () {
  36201. var serializationObject = _super.prototype.serialize.call(this);
  36202. serializationObject.size = this.size;
  36203. return serializationObject;
  36204. };
  36205. BoxGeometry.Parse = function (parsedBox, scene) {
  36206. if (scene.getGeometryByID(parsedBox.id)) {
  36207. return null; // null since geometry could be something else than a box...
  36208. }
  36209. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36210. if (BABYLON.Tags) {
  36211. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36212. }
  36213. scene.pushGeometry(box, true);
  36214. return box;
  36215. };
  36216. return BoxGeometry;
  36217. }(_PrimitiveGeometry));
  36218. BABYLON.BoxGeometry = BoxGeometry;
  36219. /**
  36220. * Creates a sphere geometry
  36221. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36222. */
  36223. var SphereGeometry = /** @class */ (function (_super) {
  36224. __extends(SphereGeometry, _super);
  36225. /**
  36226. * Create a new sphere geometry
  36227. * @param id defines the unique ID of the geometry
  36228. * @param scene defines the hosting scene
  36229. * @param segments defines the number of segments to use to create the sphere
  36230. * @param diameter defines the diameter of the sphere
  36231. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36232. * @param mesh defines the hosting mesh (can be null)
  36233. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36234. */
  36235. function SphereGeometry(id, scene,
  36236. /**
  36237. * Defines the number of segments to use to create the sphere
  36238. */
  36239. segments,
  36240. /**
  36241. * Defines the diameter of the sphere
  36242. */
  36243. diameter, canBeRegenerated, mesh,
  36244. /**
  36245. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36246. */
  36247. side) {
  36248. if (mesh === void 0) { mesh = null; }
  36249. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36250. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36251. _this.segments = segments;
  36252. _this.diameter = diameter;
  36253. _this.side = side;
  36254. return _this;
  36255. }
  36256. SphereGeometry.prototype._regenerateVertexData = function () {
  36257. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36258. };
  36259. SphereGeometry.prototype.copy = function (id) {
  36260. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36261. };
  36262. SphereGeometry.prototype.serialize = function () {
  36263. var serializationObject = _super.prototype.serialize.call(this);
  36264. serializationObject.segments = this.segments;
  36265. serializationObject.diameter = this.diameter;
  36266. return serializationObject;
  36267. };
  36268. SphereGeometry.Parse = function (parsedSphere, scene) {
  36269. if (scene.getGeometryByID(parsedSphere.id)) {
  36270. return null; // null since geometry could be something else than a sphere...
  36271. }
  36272. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36273. if (BABYLON.Tags) {
  36274. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36275. }
  36276. scene.pushGeometry(sphere, true);
  36277. return sphere;
  36278. };
  36279. return SphereGeometry;
  36280. }(_PrimitiveGeometry));
  36281. BABYLON.SphereGeometry = SphereGeometry;
  36282. /**
  36283. * Creates a disc geometry
  36284. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36285. */
  36286. var DiscGeometry = /** @class */ (function (_super) {
  36287. __extends(DiscGeometry, _super);
  36288. /**
  36289. * Creates a new disc geometry
  36290. * @param id defines the unique ID of the geometry
  36291. * @param scene defines the hosting scene
  36292. * @param radius defines the radius of the disc
  36293. * @param tessellation defines the tesselation factor to apply to the disc
  36294. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36295. * @param mesh defines the hosting mesh (can be null)
  36296. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36297. */
  36298. function DiscGeometry(id, scene,
  36299. /**
  36300. * Defines the radius of the disc
  36301. */
  36302. radius,
  36303. /**
  36304. * Defines the tesselation factor to apply to the disc
  36305. */
  36306. tessellation, canBeRegenerated, mesh,
  36307. /**
  36308. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36309. */
  36310. side) {
  36311. if (mesh === void 0) { mesh = null; }
  36312. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36313. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36314. _this.radius = radius;
  36315. _this.tessellation = tessellation;
  36316. _this.side = side;
  36317. return _this;
  36318. }
  36319. DiscGeometry.prototype._regenerateVertexData = function () {
  36320. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36321. };
  36322. DiscGeometry.prototype.copy = function (id) {
  36323. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36324. };
  36325. return DiscGeometry;
  36326. }(_PrimitiveGeometry));
  36327. BABYLON.DiscGeometry = DiscGeometry;
  36328. /**
  36329. * Creates a new cylinder geometry
  36330. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36331. */
  36332. var CylinderGeometry = /** @class */ (function (_super) {
  36333. __extends(CylinderGeometry, _super);
  36334. /**
  36335. * Creates a new cylinder geometry
  36336. * @param id defines the unique ID of the geometry
  36337. * @param scene defines the hosting scene
  36338. * @param height defines the height of the cylinder
  36339. * @param diameterTop defines the diameter of the cylinder's top cap
  36340. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36341. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36342. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36343. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36344. * @param mesh defines the hosting mesh (can be null)
  36345. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36346. */
  36347. function CylinderGeometry(id, scene,
  36348. /**
  36349. * Defines the height of the cylinder
  36350. */
  36351. height,
  36352. /**
  36353. * Defines the diameter of the cylinder's top cap
  36354. */
  36355. diameterTop,
  36356. /**
  36357. * Defines the diameter of the cylinder's bottom cap
  36358. */
  36359. diameterBottom,
  36360. /**
  36361. * Defines the tessellation factor to apply to the cylinder
  36362. */
  36363. tessellation,
  36364. /**
  36365. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36366. */
  36367. subdivisions, canBeRegenerated, mesh,
  36368. /**
  36369. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36370. */
  36371. side) {
  36372. if (subdivisions === void 0) { subdivisions = 1; }
  36373. if (mesh === void 0) { mesh = null; }
  36374. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36375. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36376. _this.height = height;
  36377. _this.diameterTop = diameterTop;
  36378. _this.diameterBottom = diameterBottom;
  36379. _this.tessellation = tessellation;
  36380. _this.subdivisions = subdivisions;
  36381. _this.side = side;
  36382. return _this;
  36383. }
  36384. CylinderGeometry.prototype._regenerateVertexData = function () {
  36385. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36386. };
  36387. CylinderGeometry.prototype.copy = function (id) {
  36388. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36389. };
  36390. CylinderGeometry.prototype.serialize = function () {
  36391. var serializationObject = _super.prototype.serialize.call(this);
  36392. serializationObject.height = this.height;
  36393. serializationObject.diameterTop = this.diameterTop;
  36394. serializationObject.diameterBottom = this.diameterBottom;
  36395. serializationObject.tessellation = this.tessellation;
  36396. return serializationObject;
  36397. };
  36398. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36399. if (scene.getGeometryByID(parsedCylinder.id)) {
  36400. return null; // null since geometry could be something else than a cylinder...
  36401. }
  36402. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36403. if (BABYLON.Tags) {
  36404. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36405. }
  36406. scene.pushGeometry(cylinder, true);
  36407. return cylinder;
  36408. };
  36409. return CylinderGeometry;
  36410. }(_PrimitiveGeometry));
  36411. BABYLON.CylinderGeometry = CylinderGeometry;
  36412. /**
  36413. * Creates a new torus geometry
  36414. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36415. */
  36416. var TorusGeometry = /** @class */ (function (_super) {
  36417. __extends(TorusGeometry, _super);
  36418. /**
  36419. * Creates a new torus geometry
  36420. * @param id defines the unique ID of the geometry
  36421. * @param scene defines the hosting scene
  36422. * @param diameter defines the diameter of the torus
  36423. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36424. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36425. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36426. * @param mesh defines the hosting mesh (can be null)
  36427. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36428. */
  36429. function TorusGeometry(id, scene,
  36430. /**
  36431. * Defines the diameter of the torus
  36432. */
  36433. diameter,
  36434. /**
  36435. * Defines the thickness of the torus (ie. internal diameter)
  36436. */
  36437. thickness,
  36438. /**
  36439. * Defines the tesselation factor to apply to the torus
  36440. */
  36441. tessellation, canBeRegenerated, mesh,
  36442. /**
  36443. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36444. */
  36445. side) {
  36446. if (mesh === void 0) { mesh = null; }
  36447. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36448. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36449. _this.diameter = diameter;
  36450. _this.thickness = thickness;
  36451. _this.tessellation = tessellation;
  36452. _this.side = side;
  36453. return _this;
  36454. }
  36455. TorusGeometry.prototype._regenerateVertexData = function () {
  36456. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36457. };
  36458. TorusGeometry.prototype.copy = function (id) {
  36459. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36460. };
  36461. TorusGeometry.prototype.serialize = function () {
  36462. var serializationObject = _super.prototype.serialize.call(this);
  36463. serializationObject.diameter = this.diameter;
  36464. serializationObject.thickness = this.thickness;
  36465. serializationObject.tessellation = this.tessellation;
  36466. return serializationObject;
  36467. };
  36468. TorusGeometry.Parse = function (parsedTorus, scene) {
  36469. if (scene.getGeometryByID(parsedTorus.id)) {
  36470. return null; // null since geometry could be something else than a torus...
  36471. }
  36472. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36473. if (BABYLON.Tags) {
  36474. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36475. }
  36476. scene.pushGeometry(torus, true);
  36477. return torus;
  36478. };
  36479. return TorusGeometry;
  36480. }(_PrimitiveGeometry));
  36481. BABYLON.TorusGeometry = TorusGeometry;
  36482. /**
  36483. * Creates a new ground geometry
  36484. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36485. */
  36486. var GroundGeometry = /** @class */ (function (_super) {
  36487. __extends(GroundGeometry, _super);
  36488. /**
  36489. * Creates a new ground geometry
  36490. * @param id defines the unique ID of the geometry
  36491. * @param scene defines the hosting scene
  36492. * @param width defines the width of the ground
  36493. * @param height defines the height of the ground
  36494. * @param subdivisions defines the subdivisions to apply to the ground
  36495. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36496. * @param mesh defines the hosting mesh (can be null)
  36497. */
  36498. function GroundGeometry(id, scene,
  36499. /**
  36500. * Defines the width of the ground
  36501. */
  36502. width,
  36503. /**
  36504. * Defines the height of the ground
  36505. */
  36506. height,
  36507. /**
  36508. * Defines the subdivisions to apply to the ground
  36509. */
  36510. subdivisions, canBeRegenerated, mesh) {
  36511. if (mesh === void 0) { mesh = null; }
  36512. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36513. _this.width = width;
  36514. _this.height = height;
  36515. _this.subdivisions = subdivisions;
  36516. return _this;
  36517. }
  36518. GroundGeometry.prototype._regenerateVertexData = function () {
  36519. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36520. };
  36521. GroundGeometry.prototype.copy = function (id) {
  36522. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36523. };
  36524. GroundGeometry.prototype.serialize = function () {
  36525. var serializationObject = _super.prototype.serialize.call(this);
  36526. serializationObject.width = this.width;
  36527. serializationObject.height = this.height;
  36528. serializationObject.subdivisions = this.subdivisions;
  36529. return serializationObject;
  36530. };
  36531. GroundGeometry.Parse = function (parsedGround, scene) {
  36532. if (scene.getGeometryByID(parsedGround.id)) {
  36533. return null; // null since geometry could be something else than a ground...
  36534. }
  36535. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36536. if (BABYLON.Tags) {
  36537. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36538. }
  36539. scene.pushGeometry(ground, true);
  36540. return ground;
  36541. };
  36542. return GroundGeometry;
  36543. }(_PrimitiveGeometry));
  36544. BABYLON.GroundGeometry = GroundGeometry;
  36545. /**
  36546. * Creates a tiled ground geometry
  36547. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36548. */
  36549. var TiledGroundGeometry = /** @class */ (function (_super) {
  36550. __extends(TiledGroundGeometry, _super);
  36551. /**
  36552. * Creates a tiled ground geometry
  36553. * @param id defines the unique ID of the geometry
  36554. * @param scene defines the hosting scene
  36555. * @param xmin defines the minimum value on X axis
  36556. * @param zmin defines the minimum value on Z axis
  36557. * @param xmax defines the maximum value on X axis
  36558. * @param zmax defines the maximum value on Z axis
  36559. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36560. * @param precision defines the precision to use when computing the tiles
  36561. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36562. * @param mesh defines the hosting mesh (can be null)
  36563. */
  36564. function TiledGroundGeometry(id, scene,
  36565. /**
  36566. * Defines the minimum value on X axis
  36567. */
  36568. xmin,
  36569. /**
  36570. * Defines the minimum value on Z axis
  36571. */
  36572. zmin,
  36573. /**
  36574. * Defines the maximum value on X axis
  36575. */
  36576. xmax,
  36577. /**
  36578. * Defines the maximum value on Z axis
  36579. */
  36580. zmax,
  36581. /**
  36582. * Defines the subdivisions to apply to the ground
  36583. */
  36584. subdivisions,
  36585. /**
  36586. * Defines the precision to use when computing the tiles
  36587. */
  36588. precision, canBeRegenerated, mesh) {
  36589. if (mesh === void 0) { mesh = null; }
  36590. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36591. _this.xmin = xmin;
  36592. _this.zmin = zmin;
  36593. _this.xmax = xmax;
  36594. _this.zmax = zmax;
  36595. _this.subdivisions = subdivisions;
  36596. _this.precision = precision;
  36597. return _this;
  36598. }
  36599. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36600. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36601. };
  36602. TiledGroundGeometry.prototype.copy = function (id) {
  36603. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36604. };
  36605. return TiledGroundGeometry;
  36606. }(_PrimitiveGeometry));
  36607. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36608. /**
  36609. * Creates a plane geometry
  36610. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36611. */
  36612. var PlaneGeometry = /** @class */ (function (_super) {
  36613. __extends(PlaneGeometry, _super);
  36614. /**
  36615. * Creates a plane geometry
  36616. * @param id defines the unique ID of the geometry
  36617. * @param scene defines the hosting scene
  36618. * @param size defines the size of the plane (width === height)
  36619. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36620. * @param mesh defines the hosting mesh (can be null)
  36621. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36622. */
  36623. function PlaneGeometry(id, scene,
  36624. /**
  36625. * Defines the size of the plane (width === height)
  36626. */
  36627. size, canBeRegenerated, mesh,
  36628. /**
  36629. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36630. */
  36631. side) {
  36632. if (mesh === void 0) { mesh = null; }
  36633. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36634. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36635. _this.size = size;
  36636. _this.side = side;
  36637. return _this;
  36638. }
  36639. PlaneGeometry.prototype._regenerateVertexData = function () {
  36640. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36641. };
  36642. PlaneGeometry.prototype.copy = function (id) {
  36643. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36644. };
  36645. PlaneGeometry.prototype.serialize = function () {
  36646. var serializationObject = _super.prototype.serialize.call(this);
  36647. serializationObject.size = this.size;
  36648. return serializationObject;
  36649. };
  36650. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36651. if (scene.getGeometryByID(parsedPlane.id)) {
  36652. return null; // null since geometry could be something else than a ground...
  36653. }
  36654. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36655. if (BABYLON.Tags) {
  36656. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36657. }
  36658. scene.pushGeometry(plane, true);
  36659. return plane;
  36660. };
  36661. return PlaneGeometry;
  36662. }(_PrimitiveGeometry));
  36663. BABYLON.PlaneGeometry = PlaneGeometry;
  36664. /**
  36665. * Creates a torus knot geometry
  36666. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36667. */
  36668. var TorusKnotGeometry = /** @class */ (function (_super) {
  36669. __extends(TorusKnotGeometry, _super);
  36670. /**
  36671. * Creates a torus knot geometry
  36672. * @param id defines the unique ID of the geometry
  36673. * @param scene defines the hosting scene
  36674. * @param radius defines the radius of the torus knot
  36675. * @param tube defines the thickness of the torus knot tube
  36676. * @param radialSegments defines the number of radial segments
  36677. * @param tubularSegments defines the number of tubular segments
  36678. * @param p defines the first number of windings
  36679. * @param q defines the second number of windings
  36680. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36681. * @param mesh defines the hosting mesh (can be null)
  36682. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36683. */
  36684. function TorusKnotGeometry(id, scene,
  36685. /**
  36686. * Defines the radius of the torus knot
  36687. */
  36688. radius,
  36689. /**
  36690. * Defines the thickness of the torus knot tube
  36691. */
  36692. tube,
  36693. /**
  36694. * Defines the number of radial segments
  36695. */
  36696. radialSegments,
  36697. /**
  36698. * Defines the number of tubular segments
  36699. */
  36700. tubularSegments,
  36701. /**
  36702. * Defines the first number of windings
  36703. */
  36704. p,
  36705. /**
  36706. * Defines the second number of windings
  36707. */
  36708. q, canBeRegenerated, mesh,
  36709. /**
  36710. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36711. */
  36712. side) {
  36713. if (mesh === void 0) { mesh = null; }
  36714. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36715. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36716. _this.radius = radius;
  36717. _this.tube = tube;
  36718. _this.radialSegments = radialSegments;
  36719. _this.tubularSegments = tubularSegments;
  36720. _this.p = p;
  36721. _this.q = q;
  36722. _this.side = side;
  36723. return _this;
  36724. }
  36725. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36726. 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 });
  36727. };
  36728. TorusKnotGeometry.prototype.copy = function (id) {
  36729. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36730. };
  36731. TorusKnotGeometry.prototype.serialize = function () {
  36732. var serializationObject = _super.prototype.serialize.call(this);
  36733. serializationObject.radius = this.radius;
  36734. serializationObject.tube = this.tube;
  36735. serializationObject.radialSegments = this.radialSegments;
  36736. serializationObject.tubularSegments = this.tubularSegments;
  36737. serializationObject.p = this.p;
  36738. serializationObject.q = this.q;
  36739. return serializationObject;
  36740. };
  36741. ;
  36742. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36743. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36744. return null; // null since geometry could be something else than a ground...
  36745. }
  36746. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36747. if (BABYLON.Tags) {
  36748. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36749. }
  36750. scene.pushGeometry(torusKnot, true);
  36751. return torusKnot;
  36752. };
  36753. return TorusKnotGeometry;
  36754. }(_PrimitiveGeometry));
  36755. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36756. //}
  36757. })(BABYLON || (BABYLON = {}));
  36758. //# sourceMappingURL=babylon.geometry.js.map
  36759. var BABYLON;
  36760. (function (BABYLON) {
  36761. /**
  36762. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36763. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36764. */
  36765. var PostProcessManager = /** @class */ (function () {
  36766. /**
  36767. * Creates a new instance of @see PostProcess
  36768. * @param scene The scene that the post process is associated with.
  36769. */
  36770. function PostProcessManager(scene) {
  36771. this._vertexBuffers = {};
  36772. this._scene = scene;
  36773. }
  36774. PostProcessManager.prototype._prepareBuffers = function () {
  36775. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36776. return;
  36777. }
  36778. // VBO
  36779. var vertices = [];
  36780. vertices.push(1, 1);
  36781. vertices.push(-1, 1);
  36782. vertices.push(-1, -1);
  36783. vertices.push(1, -1);
  36784. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36785. this._buildIndexBuffer();
  36786. };
  36787. PostProcessManager.prototype._buildIndexBuffer = function () {
  36788. // Indices
  36789. var indices = [];
  36790. indices.push(0);
  36791. indices.push(1);
  36792. indices.push(2);
  36793. indices.push(0);
  36794. indices.push(2);
  36795. indices.push(3);
  36796. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36797. };
  36798. /**
  36799. * Rebuilds the vertex buffers of the manager.
  36800. */
  36801. PostProcessManager.prototype._rebuild = function () {
  36802. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36803. if (!vb) {
  36804. return;
  36805. }
  36806. vb._rebuild();
  36807. this._buildIndexBuffer();
  36808. };
  36809. // Methods
  36810. /**
  36811. * Prepares a frame to be run through a post process.
  36812. * @param sourceTexture The input texture to the post procesess. (default: null)
  36813. * @param postProcesses An array of post processes to be run. (default: null)
  36814. * @returns True if the post processes were able to be run.
  36815. */
  36816. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36817. if (sourceTexture === void 0) { sourceTexture = null; }
  36818. if (postProcesses === void 0) { postProcesses = null; }
  36819. var camera = this._scene.activeCamera;
  36820. if (!camera) {
  36821. return false;
  36822. }
  36823. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  36824. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36825. return false;
  36826. }
  36827. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36828. return true;
  36829. };
  36830. /**
  36831. * Manually render a set of post processes to a texture.
  36832. * @param postProcesses An array of post processes to be run.
  36833. * @param targetTexture The target texture to render to.
  36834. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36835. */
  36836. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36837. if (targetTexture === void 0) { targetTexture = null; }
  36838. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36839. var engine = this._scene.getEngine();
  36840. for (var index = 0; index < postProcesses.length; index++) {
  36841. if (index < postProcesses.length - 1) {
  36842. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36843. }
  36844. else {
  36845. if (targetTexture) {
  36846. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36847. }
  36848. else {
  36849. engine.restoreDefaultFramebuffer();
  36850. }
  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 depth buffer
  36865. engine.setDepthBuffer(true);
  36866. engine.setDepthWrite(true);
  36867. };
  36868. /**
  36869. * Finalize the result of the output of the postprocesses.
  36870. * @param doNotPresent If true the result will not be displayed to the screen.
  36871. * @param targetTexture The target texture to render to.
  36872. * @param faceIndex The index of the face to bind the target texture to.
  36873. * @param postProcesses The array of post processes to render.
  36874. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36875. */
  36876. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36877. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36878. var camera = this._scene.activeCamera;
  36879. if (!camera) {
  36880. return;
  36881. }
  36882. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  36883. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36884. return;
  36885. }
  36886. var engine = this._scene.getEngine();
  36887. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36888. if (index < len - 1) {
  36889. postProcesses[index + 1].activate(camera, targetTexture);
  36890. }
  36891. else {
  36892. if (targetTexture) {
  36893. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36894. }
  36895. else {
  36896. engine.restoreDefaultFramebuffer();
  36897. }
  36898. }
  36899. if (doNotPresent) {
  36900. break;
  36901. }
  36902. var pp = postProcesses[index];
  36903. var effect = pp.apply();
  36904. if (effect) {
  36905. pp.onBeforeRenderObservable.notifyObservers(effect);
  36906. // VBOs
  36907. this._prepareBuffers();
  36908. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36909. // Draw order
  36910. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36911. pp.onAfterRenderObservable.notifyObservers(effect);
  36912. }
  36913. }
  36914. // Restore states
  36915. engine.setDepthBuffer(true);
  36916. engine.setDepthWrite(true);
  36917. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36918. };
  36919. /**
  36920. * Disposes of the post process manager.
  36921. */
  36922. PostProcessManager.prototype.dispose = function () {
  36923. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36924. if (buffer) {
  36925. buffer.dispose();
  36926. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36927. }
  36928. if (this._indexBuffer) {
  36929. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36930. this._indexBuffer = null;
  36931. }
  36932. };
  36933. return PostProcessManager;
  36934. }());
  36935. BABYLON.PostProcessManager = PostProcessManager;
  36936. })(BABYLON || (BABYLON = {}));
  36937. //# sourceMappingURL=babylon.postProcessManager.js.map
  36938. var BABYLON;
  36939. (function (BABYLON) {
  36940. /**
  36941. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36942. */
  36943. var PerformanceMonitor = /** @class */ (function () {
  36944. /**
  36945. * constructor
  36946. * @param frameSampleSize The number of samples required to saturate the sliding window
  36947. */
  36948. function PerformanceMonitor(frameSampleSize) {
  36949. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36950. this._enabled = true;
  36951. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36952. }
  36953. /**
  36954. * Samples current frame
  36955. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36956. */
  36957. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36958. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36959. if (!this._enabled)
  36960. return;
  36961. if (this._lastFrameTimeMs != null) {
  36962. var dt = timeMs - this._lastFrameTimeMs;
  36963. this._rollingFrameTime.add(dt);
  36964. }
  36965. this._lastFrameTimeMs = timeMs;
  36966. };
  36967. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36968. /**
  36969. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36970. * @return Average frame time in milliseconds
  36971. */
  36972. get: function () {
  36973. return this._rollingFrameTime.average;
  36974. },
  36975. enumerable: true,
  36976. configurable: true
  36977. });
  36978. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36979. /**
  36980. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36981. * @return Frame time variance in milliseconds squared
  36982. */
  36983. get: function () {
  36984. return this._rollingFrameTime.variance;
  36985. },
  36986. enumerable: true,
  36987. configurable: true
  36988. });
  36989. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36990. /**
  36991. * Returns the frame time of the most recent frame
  36992. * @return Frame time in milliseconds
  36993. */
  36994. get: function () {
  36995. return this._rollingFrameTime.history(0);
  36996. },
  36997. enumerable: true,
  36998. configurable: true
  36999. });
  37000. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  37001. /**
  37002. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  37003. * @return Framerate in frames per second
  37004. */
  37005. get: function () {
  37006. return 1000.0 / this._rollingFrameTime.average;
  37007. },
  37008. enumerable: true,
  37009. configurable: true
  37010. });
  37011. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  37012. /**
  37013. * Returns the average framerate in frames per second using the most recent frame time
  37014. * @return Framerate in frames per second
  37015. */
  37016. get: function () {
  37017. var history = this._rollingFrameTime.history(0);
  37018. if (history === 0) {
  37019. return 0;
  37020. }
  37021. return 1000.0 / history;
  37022. },
  37023. enumerable: true,
  37024. configurable: true
  37025. });
  37026. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  37027. /**
  37028. * Returns true if enough samples have been taken to completely fill the sliding window
  37029. * @return true if saturated
  37030. */
  37031. get: function () {
  37032. return this._rollingFrameTime.isSaturated();
  37033. },
  37034. enumerable: true,
  37035. configurable: true
  37036. });
  37037. /**
  37038. * Enables contributions to the sliding window sample set
  37039. */
  37040. PerformanceMonitor.prototype.enable = function () {
  37041. this._enabled = true;
  37042. };
  37043. /**
  37044. * Disables contributions to the sliding window sample set
  37045. * Samples will not be interpolated over the disabled period
  37046. */
  37047. PerformanceMonitor.prototype.disable = function () {
  37048. this._enabled = false;
  37049. //clear last sample to avoid interpolating over the disabled period when next enabled
  37050. this._lastFrameTimeMs = null;
  37051. };
  37052. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  37053. /**
  37054. * Returns true if sampling is enabled
  37055. * @return true if enabled
  37056. */
  37057. get: function () {
  37058. return this._enabled;
  37059. },
  37060. enumerable: true,
  37061. configurable: true
  37062. });
  37063. /**
  37064. * Resets performance monitor
  37065. */
  37066. PerformanceMonitor.prototype.reset = function () {
  37067. //clear last sample to avoid interpolating over the disabled period when next enabled
  37068. this._lastFrameTimeMs = null;
  37069. //wipe record
  37070. this._rollingFrameTime.reset();
  37071. };
  37072. return PerformanceMonitor;
  37073. }());
  37074. BABYLON.PerformanceMonitor = PerformanceMonitor;
  37075. /**
  37076. * RollingAverage
  37077. *
  37078. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  37079. */
  37080. var RollingAverage = /** @class */ (function () {
  37081. /**
  37082. * constructor
  37083. * @param length The number of samples required to saturate the sliding window
  37084. */
  37085. function RollingAverage(length) {
  37086. this._samples = new Array(length);
  37087. this.reset();
  37088. }
  37089. /**
  37090. * Adds a sample to the sample set
  37091. * @param v The sample value
  37092. */
  37093. RollingAverage.prototype.add = function (v) {
  37094. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  37095. var delta;
  37096. //we need to check if we've already wrapped round
  37097. if (this.isSaturated()) {
  37098. //remove bottom of stack from mean
  37099. var bottomValue = this._samples[this._pos];
  37100. delta = bottomValue - this.average;
  37101. this.average -= delta / (this._sampleCount - 1);
  37102. this._m2 -= delta * (bottomValue - this.average);
  37103. }
  37104. else {
  37105. this._sampleCount++;
  37106. }
  37107. //add new value to mean
  37108. delta = v - this.average;
  37109. this.average += delta / (this._sampleCount);
  37110. this._m2 += delta * (v - this.average);
  37111. //set the new variance
  37112. this.variance = this._m2 / (this._sampleCount - 1);
  37113. this._samples[this._pos] = v;
  37114. this._pos++;
  37115. this._pos %= this._samples.length; //positive wrap around
  37116. };
  37117. /**
  37118. * Returns previously added values or null if outside of history or outside the sliding window domain
  37119. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  37120. * @return Value previously recorded with add() or null if outside of range
  37121. */
  37122. RollingAverage.prototype.history = function (i) {
  37123. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  37124. return 0;
  37125. }
  37126. var i0 = this._wrapPosition(this._pos - 1.0);
  37127. return this._samples[this._wrapPosition(i0 - i)];
  37128. };
  37129. /**
  37130. * Returns true if enough samples have been taken to completely fill the sliding window
  37131. * @return true if sample-set saturated
  37132. */
  37133. RollingAverage.prototype.isSaturated = function () {
  37134. return this._sampleCount >= this._samples.length;
  37135. };
  37136. /**
  37137. * Resets the rolling average (equivalent to 0 samples taken so far)
  37138. */
  37139. RollingAverage.prototype.reset = function () {
  37140. this.average = 0;
  37141. this.variance = 0;
  37142. this._sampleCount = 0;
  37143. this._pos = 0;
  37144. this._m2 = 0;
  37145. };
  37146. /**
  37147. * Wraps a value around the sample range boundaries
  37148. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  37149. * @return Wrapped position in sample range
  37150. */
  37151. RollingAverage.prototype._wrapPosition = function (i) {
  37152. var max = this._samples.length;
  37153. return ((i % max) + max) % max;
  37154. };
  37155. return RollingAverage;
  37156. }());
  37157. BABYLON.RollingAverage = RollingAverage;
  37158. })(BABYLON || (BABYLON = {}));
  37159. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37160. var BABYLON;
  37161. (function (BABYLON) {
  37162. /**
  37163. * This groups together the common properties used for image processing either in direct forward pass
  37164. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37165. * or not.
  37166. */
  37167. var ImageProcessingConfiguration = /** @class */ (function () {
  37168. function ImageProcessingConfiguration() {
  37169. /**
  37170. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37171. */
  37172. this.colorCurves = new BABYLON.ColorCurves();
  37173. this._colorCurvesEnabled = false;
  37174. this._colorGradingEnabled = false;
  37175. this._colorGradingWithGreenDepth = true;
  37176. this._colorGradingBGR = true;
  37177. this._exposure = 1.0;
  37178. this._toneMappingEnabled = false;
  37179. this._contrast = 1.0;
  37180. /**
  37181. * Vignette stretch size.
  37182. */
  37183. this.vignetteStretch = 0;
  37184. /**
  37185. * Vignette centre X Offset.
  37186. */
  37187. this.vignetteCentreX = 0;
  37188. /**
  37189. * Vignette centre Y Offset.
  37190. */
  37191. this.vignetteCentreY = 0;
  37192. /**
  37193. * Vignette weight or intensity of the vignette effect.
  37194. */
  37195. this.vignetteWeight = 1.5;
  37196. /**
  37197. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37198. * if vignetteEnabled is set to true.
  37199. */
  37200. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37201. /**
  37202. * Camera field of view used by the Vignette effect.
  37203. */
  37204. this.vignetteCameraFov = 0.5;
  37205. this._grainEnabled = false;
  37206. this._grainIntensity = 30;
  37207. this._grainAnimated = false;
  37208. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37209. this._vignetteEnabled = false;
  37210. this._applyByPostProcess = false;
  37211. this._isEnabled = true;
  37212. /**
  37213. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37214. * @type {BABYLON.Observable}
  37215. */
  37216. this.onUpdateParameters = new BABYLON.Observable();
  37217. }
  37218. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37219. /**
  37220. * Gets wether the color curves effect is enabled.
  37221. */
  37222. get: function () {
  37223. return this._colorCurvesEnabled;
  37224. },
  37225. /**
  37226. * Sets wether the color curves effect is enabled.
  37227. */
  37228. set: function (value) {
  37229. if (this._colorCurvesEnabled === value) {
  37230. return;
  37231. }
  37232. this._colorCurvesEnabled = value;
  37233. this._updateParameters();
  37234. },
  37235. enumerable: true,
  37236. configurable: true
  37237. });
  37238. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37239. /**
  37240. * Gets wether the color grading effect is enabled.
  37241. */
  37242. get: function () {
  37243. return this._colorGradingEnabled;
  37244. },
  37245. /**
  37246. * Sets wether the color grading effect is enabled.
  37247. */
  37248. set: function (value) {
  37249. if (this._colorGradingEnabled === value) {
  37250. return;
  37251. }
  37252. this._colorGradingEnabled = value;
  37253. this._updateParameters();
  37254. },
  37255. enumerable: true,
  37256. configurable: true
  37257. });
  37258. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37259. /**
  37260. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37261. */
  37262. get: function () {
  37263. return this._colorGradingWithGreenDepth;
  37264. },
  37265. /**
  37266. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37267. */
  37268. set: function (value) {
  37269. if (this._colorGradingWithGreenDepth === value) {
  37270. return;
  37271. }
  37272. this._colorGradingWithGreenDepth = value;
  37273. this._updateParameters();
  37274. },
  37275. enumerable: true,
  37276. configurable: true
  37277. });
  37278. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37279. /**
  37280. * Gets wether the color grading texture contains BGR values.
  37281. */
  37282. get: function () {
  37283. return this._colorGradingBGR;
  37284. },
  37285. /**
  37286. * Sets wether the color grading texture contains BGR values.
  37287. */
  37288. set: function (value) {
  37289. if (this._colorGradingBGR === value) {
  37290. return;
  37291. }
  37292. this._colorGradingBGR = value;
  37293. this._updateParameters();
  37294. },
  37295. enumerable: true,
  37296. configurable: true
  37297. });
  37298. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37299. /**
  37300. * Gets the Exposure used in the effect.
  37301. */
  37302. get: function () {
  37303. return this._exposure;
  37304. },
  37305. /**
  37306. * Sets the Exposure used in the effect.
  37307. */
  37308. set: function (value) {
  37309. if (this._exposure === value) {
  37310. return;
  37311. }
  37312. this._exposure = value;
  37313. this._updateParameters();
  37314. },
  37315. enumerable: true,
  37316. configurable: true
  37317. });
  37318. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37319. /**
  37320. * Gets wether the tone mapping effect is enabled.
  37321. */
  37322. get: function () {
  37323. return this._toneMappingEnabled;
  37324. },
  37325. /**
  37326. * Sets wether the tone mapping effect is enabled.
  37327. */
  37328. set: function (value) {
  37329. if (this._toneMappingEnabled === value) {
  37330. return;
  37331. }
  37332. this._toneMappingEnabled = value;
  37333. this._updateParameters();
  37334. },
  37335. enumerable: true,
  37336. configurable: true
  37337. });
  37338. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37339. /**
  37340. * Gets the contrast used in the effect.
  37341. */
  37342. get: function () {
  37343. return this._contrast;
  37344. },
  37345. /**
  37346. * Sets the contrast used in the effect.
  37347. */
  37348. set: function (value) {
  37349. if (this._contrast === value) {
  37350. return;
  37351. }
  37352. this._contrast = value;
  37353. this._updateParameters();
  37354. },
  37355. enumerable: true,
  37356. configurable: true
  37357. });
  37358. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37359. /**
  37360. * If the grain effect should be enabled.
  37361. */
  37362. get: function () {
  37363. return this._grainEnabled;
  37364. },
  37365. set: function (value) {
  37366. if (this._grainEnabled === value) {
  37367. return;
  37368. }
  37369. this._grainEnabled = value;
  37370. this._updateParameters();
  37371. },
  37372. enumerable: true,
  37373. configurable: true
  37374. });
  37375. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37376. /**
  37377. * Amount of grain to be applied by the grain effect.
  37378. */
  37379. get: function () {
  37380. return this._grainIntensity;
  37381. },
  37382. set: function (value) {
  37383. if (this._grainIntensity === value) {
  37384. return;
  37385. }
  37386. this._grainIntensity = value;
  37387. },
  37388. enumerable: true,
  37389. configurable: true
  37390. });
  37391. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37392. /**
  37393. * If the grain effect should be animated.
  37394. */
  37395. get: function () {
  37396. return this._grainAnimated;
  37397. },
  37398. set: function (value) {
  37399. if (this._grainAnimated === value) {
  37400. return;
  37401. }
  37402. this._grainAnimated = value;
  37403. this._updateParameters();
  37404. },
  37405. enumerable: true,
  37406. configurable: true
  37407. });
  37408. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37409. /**
  37410. * Gets the vignette blend mode allowing different kind of effect.
  37411. */
  37412. get: function () {
  37413. return this._vignetteBlendMode;
  37414. },
  37415. /**
  37416. * Sets the vignette blend mode allowing different kind of effect.
  37417. */
  37418. set: function (value) {
  37419. if (this._vignetteBlendMode === value) {
  37420. return;
  37421. }
  37422. this._vignetteBlendMode = value;
  37423. this._updateParameters();
  37424. },
  37425. enumerable: true,
  37426. configurable: true
  37427. });
  37428. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37429. /**
  37430. * Gets wether the vignette effect is enabled.
  37431. */
  37432. get: function () {
  37433. return this._vignetteEnabled;
  37434. },
  37435. /**
  37436. * Sets wether the vignette effect is enabled.
  37437. */
  37438. set: function (value) {
  37439. if (this._vignetteEnabled === value) {
  37440. return;
  37441. }
  37442. this._vignetteEnabled = value;
  37443. this._updateParameters();
  37444. },
  37445. enumerable: true,
  37446. configurable: true
  37447. });
  37448. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37449. /**
  37450. * Gets wether the image processing is applied through a post process or not.
  37451. */
  37452. get: function () {
  37453. return this._applyByPostProcess;
  37454. },
  37455. /**
  37456. * Sets wether the image processing is applied through a post process or not.
  37457. */
  37458. set: function (value) {
  37459. if (this._applyByPostProcess === value) {
  37460. return;
  37461. }
  37462. this._applyByPostProcess = value;
  37463. this._updateParameters();
  37464. },
  37465. enumerable: true,
  37466. configurable: true
  37467. });
  37468. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37469. /**
  37470. * Gets wether the image processing is enabled or not.
  37471. */
  37472. get: function () {
  37473. return this._isEnabled;
  37474. },
  37475. /**
  37476. * Sets wether the image processing is enabled or not.
  37477. */
  37478. set: function (value) {
  37479. if (this._isEnabled === value) {
  37480. return;
  37481. }
  37482. this._isEnabled = value;
  37483. this._updateParameters();
  37484. },
  37485. enumerable: true,
  37486. configurable: true
  37487. });
  37488. /**
  37489. * Method called each time the image processing information changes requires to recompile the effect.
  37490. */
  37491. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37492. this.onUpdateParameters.notifyObservers(this);
  37493. };
  37494. ImageProcessingConfiguration.prototype.getClassName = function () {
  37495. return "ImageProcessingConfiguration";
  37496. };
  37497. /**
  37498. * Prepare the list of uniforms associated with the Image Processing effects.
  37499. * @param uniformsList The list of uniforms used in the effect
  37500. * @param defines the list of defines currently in use
  37501. */
  37502. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37503. if (defines.EXPOSURE) {
  37504. uniforms.push("exposureLinear");
  37505. }
  37506. if (defines.CONTRAST) {
  37507. uniforms.push("contrast");
  37508. }
  37509. if (defines.COLORGRADING) {
  37510. uniforms.push("colorTransformSettings");
  37511. }
  37512. if (defines.VIGNETTE) {
  37513. uniforms.push("vInverseScreenSize");
  37514. uniforms.push("vignetteSettings1");
  37515. uniforms.push("vignetteSettings2");
  37516. }
  37517. if (defines.COLORCURVES) {
  37518. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37519. }
  37520. if (defines.GRAIN) {
  37521. uniforms.push("grainVarianceAmount");
  37522. uniforms.push("grainAnimatedSeed");
  37523. }
  37524. };
  37525. /**
  37526. * Prepare the list of samplers associated with the Image Processing effects.
  37527. * @param uniformsList The list of uniforms used in the effect
  37528. * @param defines the list of defines currently in use
  37529. */
  37530. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37531. if (defines.COLORGRADING) {
  37532. samplersList.push("txColorTransform");
  37533. }
  37534. };
  37535. /**
  37536. * Prepare the list of defines associated to the shader.
  37537. * @param defines the list of defines to complete
  37538. */
  37539. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37540. if (forPostProcess === void 0) { forPostProcess = false; }
  37541. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37542. defines.VIGNETTE = false;
  37543. defines.TONEMAPPING = false;
  37544. defines.CONTRAST = false;
  37545. defines.EXPOSURE = false;
  37546. defines.COLORCURVES = false;
  37547. defines.COLORGRADING = false;
  37548. defines.COLORGRADING3D = false;
  37549. defines.IMAGEPROCESSING = false;
  37550. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37551. return;
  37552. }
  37553. defines.VIGNETTE = this.vignetteEnabled;
  37554. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37555. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37556. defines.TONEMAPPING = this.toneMappingEnabled;
  37557. defines.CONTRAST = (this.contrast !== 1.0);
  37558. defines.EXPOSURE = (this.exposure !== 1.0);
  37559. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37560. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37561. if (defines.COLORGRADING) {
  37562. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37563. }
  37564. else {
  37565. defines.COLORGRADING3D = false;
  37566. }
  37567. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37568. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37569. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37570. defines.GRAIN = this.grainEnabled;
  37571. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37572. };
  37573. /**
  37574. * Returns true if all the image processing information are ready.
  37575. */
  37576. ImageProcessingConfiguration.prototype.isReady = function () {
  37577. // Color Grading texure can not be none blocking.
  37578. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37579. };
  37580. /**
  37581. * Binds the image processing to the shader.
  37582. * @param effect The effect to bind to
  37583. */
  37584. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37585. if (aspectRatio === void 0) { aspectRatio = 1; }
  37586. // Color Curves
  37587. if (this._colorCurvesEnabled && this.colorCurves) {
  37588. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37589. }
  37590. // Vignette
  37591. if (this._vignetteEnabled) {
  37592. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37593. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37594. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37595. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37596. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37597. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37598. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37599. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37600. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37601. var vignettePower = -2.0 * this.vignetteWeight;
  37602. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37603. }
  37604. // Exposure
  37605. effect.setFloat("exposureLinear", this.exposure);
  37606. // Contrast
  37607. effect.setFloat("contrast", this.contrast);
  37608. // Color transform settings
  37609. if (this.colorGradingTexture) {
  37610. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37611. var textureSize = this.colorGradingTexture.getSize().height;
  37612. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37613. 0.5 / textureSize, // textureOffset
  37614. textureSize, // textureSize
  37615. this.colorGradingTexture.level // weight
  37616. );
  37617. }
  37618. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37619. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37620. };
  37621. /**
  37622. * Clones the current image processing instance.
  37623. * @return The cloned image processing
  37624. */
  37625. ImageProcessingConfiguration.prototype.clone = function () {
  37626. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37627. };
  37628. /**
  37629. * Serializes the current image processing instance to a json representation.
  37630. * @return a JSON representation
  37631. */
  37632. ImageProcessingConfiguration.prototype.serialize = function () {
  37633. return BABYLON.SerializationHelper.Serialize(this);
  37634. };
  37635. /**
  37636. * Parses the image processing from a json representation.
  37637. * @param source the JSON source to parse
  37638. * @return The parsed image processing
  37639. */
  37640. ImageProcessingConfiguration.Parse = function (source) {
  37641. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37642. };
  37643. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37644. /**
  37645. * Used to apply the vignette as a mix with the pixel color.
  37646. */
  37647. get: function () {
  37648. return this._VIGNETTEMODE_MULTIPLY;
  37649. },
  37650. enumerable: true,
  37651. configurable: true
  37652. });
  37653. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37654. /**
  37655. * Used to apply the vignette as a replacement of the pixel color.
  37656. */
  37657. get: function () {
  37658. return this._VIGNETTEMODE_OPAQUE;
  37659. },
  37660. enumerable: true,
  37661. configurable: true
  37662. });
  37663. // Static constants associated to the image processing.
  37664. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37665. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37666. __decorate([
  37667. BABYLON.serializeAsColorCurves()
  37668. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37669. __decorate([
  37670. BABYLON.serialize()
  37671. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37672. __decorate([
  37673. BABYLON.serializeAsTexture()
  37674. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37675. __decorate([
  37676. BABYLON.serialize()
  37677. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37678. __decorate([
  37679. BABYLON.serialize()
  37680. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37681. __decorate([
  37682. BABYLON.serialize()
  37683. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37684. __decorate([
  37685. BABYLON.serialize()
  37686. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37687. __decorate([
  37688. BABYLON.serialize()
  37689. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37690. __decorate([
  37691. BABYLON.serialize()
  37692. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37693. __decorate([
  37694. BABYLON.serialize()
  37695. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37696. __decorate([
  37697. BABYLON.serialize()
  37698. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37699. __decorate([
  37700. BABYLON.serialize()
  37701. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37702. __decorate([
  37703. BABYLON.serialize()
  37704. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37705. __decorate([
  37706. BABYLON.serializeAsColor4()
  37707. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37708. __decorate([
  37709. BABYLON.serialize()
  37710. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37711. __decorate([
  37712. BABYLON.serialize()
  37713. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  37714. __decorate([
  37715. BABYLON.serialize()
  37716. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  37717. __decorate([
  37718. BABYLON.serialize()
  37719. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  37720. __decorate([
  37721. BABYLON.serialize()
  37722. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37723. __decorate([
  37724. BABYLON.serialize()
  37725. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37726. __decorate([
  37727. BABYLON.serialize()
  37728. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37729. __decorate([
  37730. BABYLON.serialize()
  37731. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37732. return ImageProcessingConfiguration;
  37733. }());
  37734. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37735. })(BABYLON || (BABYLON = {}));
  37736. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37737. var BABYLON;
  37738. (function (BABYLON) {
  37739. /**
  37740. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37741. * It can help converting any input color in a desired output one. This can then be used to create effects
  37742. * from sepia, black and white to sixties or futuristic rendering...
  37743. *
  37744. * The only supported format is currently 3dl.
  37745. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37746. */
  37747. var ColorGradingTexture = /** @class */ (function (_super) {
  37748. __extends(ColorGradingTexture, _super);
  37749. /**
  37750. * Instantiates a ColorGradingTexture from the following parameters.
  37751. *
  37752. * @param url The location of the color gradind data (currently only supporting 3dl)
  37753. * @param scene The scene the texture will be used in
  37754. */
  37755. function ColorGradingTexture(url, scene) {
  37756. var _this = _super.call(this, scene) || this;
  37757. if (!url) {
  37758. return _this;
  37759. }
  37760. _this._engine = scene.getEngine();
  37761. _this._textureMatrix = BABYLON.Matrix.Identity();
  37762. _this.name = url;
  37763. _this.url = url;
  37764. _this.hasAlpha = false;
  37765. _this.isCube = false;
  37766. _this.is3D = _this._engine.webGLVersion > 1;
  37767. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37768. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37769. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37770. _this.anisotropicFilteringLevel = 1;
  37771. _this._texture = _this._getFromCache(url, true);
  37772. if (!_this._texture) {
  37773. if (!scene.useDelayedTextureLoading) {
  37774. _this.loadTexture();
  37775. }
  37776. else {
  37777. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37778. }
  37779. }
  37780. return _this;
  37781. }
  37782. /**
  37783. * Returns the texture matrix used in most of the material.
  37784. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37785. */
  37786. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37787. return this._textureMatrix;
  37788. };
  37789. /**
  37790. * Occurs when the file being loaded is a .3dl LUT file.
  37791. */
  37792. ColorGradingTexture.prototype.load3dlTexture = function () {
  37793. var engine = this._engine;
  37794. var texture;
  37795. if (engine.webGLVersion === 1) {
  37796. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37797. }
  37798. else {
  37799. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37800. }
  37801. this._texture = texture;
  37802. var callback = function (text) {
  37803. if (typeof text !== "string") {
  37804. return;
  37805. }
  37806. var data = null;
  37807. var tempData = null;
  37808. var line;
  37809. var lines = text.split('\n');
  37810. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37811. var maxColor = 0;
  37812. for (var i = 0; i < lines.length; i++) {
  37813. line = lines[i];
  37814. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37815. continue;
  37816. if (line.indexOf('#') === 0)
  37817. continue;
  37818. var words = line.split(" ");
  37819. if (size === 0) {
  37820. // Number of space + one
  37821. size = words.length;
  37822. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37823. tempData = new Float32Array(size * size * size * 4);
  37824. continue;
  37825. }
  37826. if (size != 0) {
  37827. var r = Math.max(parseInt(words[0]), 0);
  37828. var g = Math.max(parseInt(words[1]), 0);
  37829. var b = Math.max(parseInt(words[2]), 0);
  37830. maxColor = Math.max(r, maxColor);
  37831. maxColor = Math.max(g, maxColor);
  37832. maxColor = Math.max(b, maxColor);
  37833. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37834. if (tempData) {
  37835. tempData[pixelStorageIndex + 0] = r;
  37836. tempData[pixelStorageIndex + 1] = g;
  37837. tempData[pixelStorageIndex + 2] = b;
  37838. }
  37839. pixelIndexSlice++;
  37840. if (pixelIndexSlice % size == 0) {
  37841. pixelIndexH++;
  37842. pixelIndexSlice = 0;
  37843. if (pixelIndexH % size == 0) {
  37844. pixelIndexW++;
  37845. pixelIndexH = 0;
  37846. }
  37847. }
  37848. }
  37849. }
  37850. if (tempData && data) {
  37851. for (var i = 0; i < tempData.length; i++) {
  37852. if (i > 0 && (i + 1) % 4 === 0) {
  37853. data[i] = 255;
  37854. }
  37855. else {
  37856. var value = tempData[i];
  37857. data[i] = (value / maxColor * 255);
  37858. }
  37859. }
  37860. }
  37861. if (texture.is3D) {
  37862. texture.updateSize(size, size, size);
  37863. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37864. }
  37865. else {
  37866. texture.updateSize(size * size, size);
  37867. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37868. }
  37869. };
  37870. var scene = this.getScene();
  37871. if (scene) {
  37872. scene._loadFile(this.url, callback);
  37873. }
  37874. else {
  37875. this._engine._loadFile(this.url, callback);
  37876. }
  37877. return this._texture;
  37878. };
  37879. /**
  37880. * Starts the loading process of the texture.
  37881. */
  37882. ColorGradingTexture.prototype.loadTexture = function () {
  37883. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37884. this.load3dlTexture();
  37885. }
  37886. };
  37887. /**
  37888. * Clones the color gradind texture.
  37889. */
  37890. ColorGradingTexture.prototype.clone = function () {
  37891. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37892. // Base texture
  37893. newTexture.level = this.level;
  37894. return newTexture;
  37895. };
  37896. /**
  37897. * Called during delayed load for textures.
  37898. */
  37899. ColorGradingTexture.prototype.delayLoad = function () {
  37900. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37901. return;
  37902. }
  37903. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37904. this._texture = this._getFromCache(this.url, true);
  37905. if (!this._texture) {
  37906. this.loadTexture();
  37907. }
  37908. };
  37909. /**
  37910. * Parses a color grading texture serialized by Babylon.
  37911. * @param parsedTexture The texture information being parsedTexture
  37912. * @param scene The scene to load the texture in
  37913. * @param rootUrl The root url of the data assets to load
  37914. * @return A color gradind texture
  37915. */
  37916. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37917. var texture = null;
  37918. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37919. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37920. texture.name = parsedTexture.name;
  37921. texture.level = parsedTexture.level;
  37922. }
  37923. return texture;
  37924. };
  37925. /**
  37926. * Serializes the LUT texture to json format.
  37927. */
  37928. ColorGradingTexture.prototype.serialize = function () {
  37929. if (!this.name) {
  37930. return null;
  37931. }
  37932. var serializationObject = {};
  37933. serializationObject.name = this.name;
  37934. serializationObject.level = this.level;
  37935. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37936. return serializationObject;
  37937. };
  37938. /**
  37939. * Empty line regex stored for GC.
  37940. */
  37941. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37942. return ColorGradingTexture;
  37943. }(BABYLON.BaseTexture));
  37944. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37945. })(BABYLON || (BABYLON = {}));
  37946. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37947. var BABYLON;
  37948. (function (BABYLON) {
  37949. /**
  37950. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37951. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37952. * 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;
  37953. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37954. */
  37955. var ColorCurves = /** @class */ (function () {
  37956. function ColorCurves() {
  37957. this._dirty = true;
  37958. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37959. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37960. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37961. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37962. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37963. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37964. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37965. this._globalHue = 30;
  37966. this._globalDensity = 0;
  37967. this._globalSaturation = 0;
  37968. this._globalExposure = 0;
  37969. this._highlightsHue = 30;
  37970. this._highlightsDensity = 0;
  37971. this._highlightsSaturation = 0;
  37972. this._highlightsExposure = 0;
  37973. this._midtonesHue = 30;
  37974. this._midtonesDensity = 0;
  37975. this._midtonesSaturation = 0;
  37976. this._midtonesExposure = 0;
  37977. this._shadowsHue = 30;
  37978. this._shadowsDensity = 0;
  37979. this._shadowsSaturation = 0;
  37980. this._shadowsExposure = 0;
  37981. }
  37982. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37983. /**
  37984. * Gets the global Hue value.
  37985. * 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).
  37986. */
  37987. get: function () {
  37988. return this._globalHue;
  37989. },
  37990. /**
  37991. * Sets the global Hue value.
  37992. * 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).
  37993. */
  37994. set: function (value) {
  37995. this._globalHue = value;
  37996. this._dirty = true;
  37997. },
  37998. enumerable: true,
  37999. configurable: true
  38000. });
  38001. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  38002. /**
  38003. * Gets the global Density value.
  38004. * 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.
  38005. * Values less than zero provide a filter of opposite hue.
  38006. */
  38007. get: function () {
  38008. return this._globalDensity;
  38009. },
  38010. /**
  38011. * Sets the global Density value.
  38012. * 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.
  38013. * Values less than zero provide a filter of opposite hue.
  38014. */
  38015. set: function (value) {
  38016. this._globalDensity = value;
  38017. this._dirty = true;
  38018. },
  38019. enumerable: true,
  38020. configurable: true
  38021. });
  38022. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  38023. /**
  38024. * Gets the global Saturation value.
  38025. * 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.
  38026. */
  38027. get: function () {
  38028. return this._globalSaturation;
  38029. },
  38030. /**
  38031. * Sets the global Saturation value.
  38032. * 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.
  38033. */
  38034. set: function (value) {
  38035. this._globalSaturation = value;
  38036. this._dirty = true;
  38037. },
  38038. enumerable: true,
  38039. configurable: true
  38040. });
  38041. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  38042. /**
  38043. * Gets the highlights Hue value.
  38044. * 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).
  38045. */
  38046. get: function () {
  38047. return this._highlightsHue;
  38048. },
  38049. /**
  38050. * Sets the highlights Hue value.
  38051. * 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).
  38052. */
  38053. set: function (value) {
  38054. this._highlightsHue = value;
  38055. this._dirty = true;
  38056. },
  38057. enumerable: true,
  38058. configurable: true
  38059. });
  38060. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  38061. /**
  38062. * Gets the highlights Density value.
  38063. * 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.
  38064. * Values less than zero provide a filter of opposite hue.
  38065. */
  38066. get: function () {
  38067. return this._highlightsDensity;
  38068. },
  38069. /**
  38070. * Sets the highlights Density value.
  38071. * 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.
  38072. * Values less than zero provide a filter of opposite hue.
  38073. */
  38074. set: function (value) {
  38075. this._highlightsDensity = value;
  38076. this._dirty = true;
  38077. },
  38078. enumerable: true,
  38079. configurable: true
  38080. });
  38081. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  38082. /**
  38083. * Gets the highlights Saturation value.
  38084. * 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.
  38085. */
  38086. get: function () {
  38087. return this._highlightsSaturation;
  38088. },
  38089. /**
  38090. * Sets the highlights Saturation value.
  38091. * 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.
  38092. */
  38093. set: function (value) {
  38094. this._highlightsSaturation = value;
  38095. this._dirty = true;
  38096. },
  38097. enumerable: true,
  38098. configurable: true
  38099. });
  38100. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  38101. /**
  38102. * Gets the highlights Exposure value.
  38103. * 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.
  38104. */
  38105. get: function () {
  38106. return this._highlightsExposure;
  38107. },
  38108. /**
  38109. * Sets the highlights Exposure value.
  38110. * 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.
  38111. */
  38112. set: function (value) {
  38113. this._highlightsExposure = value;
  38114. this._dirty = true;
  38115. },
  38116. enumerable: true,
  38117. configurable: true
  38118. });
  38119. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  38120. /**
  38121. * Gets the midtones Hue value.
  38122. * 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).
  38123. */
  38124. get: function () {
  38125. return this._midtonesHue;
  38126. },
  38127. /**
  38128. * Sets the midtones Hue value.
  38129. * 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).
  38130. */
  38131. set: function (value) {
  38132. this._midtonesHue = value;
  38133. this._dirty = true;
  38134. },
  38135. enumerable: true,
  38136. configurable: true
  38137. });
  38138. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  38139. /**
  38140. * Gets the midtones Density value.
  38141. * 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.
  38142. * Values less than zero provide a filter of opposite hue.
  38143. */
  38144. get: function () {
  38145. return this._midtonesDensity;
  38146. },
  38147. /**
  38148. * Sets the midtones Density value.
  38149. * 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.
  38150. * Values less than zero provide a filter of opposite hue.
  38151. */
  38152. set: function (value) {
  38153. this._midtonesDensity = value;
  38154. this._dirty = true;
  38155. },
  38156. enumerable: true,
  38157. configurable: true
  38158. });
  38159. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38160. /**
  38161. * Gets the midtones Saturation value.
  38162. * 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.
  38163. */
  38164. get: function () {
  38165. return this._midtonesSaturation;
  38166. },
  38167. /**
  38168. * Sets the midtones Saturation value.
  38169. * 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.
  38170. */
  38171. set: function (value) {
  38172. this._midtonesSaturation = value;
  38173. this._dirty = true;
  38174. },
  38175. enumerable: true,
  38176. configurable: true
  38177. });
  38178. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38179. /**
  38180. * Gets the midtones Exposure value.
  38181. * 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.
  38182. */
  38183. get: function () {
  38184. return this._midtonesExposure;
  38185. },
  38186. /**
  38187. * Sets the midtones Exposure value.
  38188. * 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.
  38189. */
  38190. set: function (value) {
  38191. this._midtonesExposure = value;
  38192. this._dirty = true;
  38193. },
  38194. enumerable: true,
  38195. configurable: true
  38196. });
  38197. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38198. /**
  38199. * Gets the shadows Hue value.
  38200. * 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).
  38201. */
  38202. get: function () {
  38203. return this._shadowsHue;
  38204. },
  38205. /**
  38206. * Sets the shadows Hue value.
  38207. * 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).
  38208. */
  38209. set: function (value) {
  38210. this._shadowsHue = value;
  38211. this._dirty = true;
  38212. },
  38213. enumerable: true,
  38214. configurable: true
  38215. });
  38216. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38217. /**
  38218. * Gets the shadows Density value.
  38219. * 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.
  38220. * Values less than zero provide a filter of opposite hue.
  38221. */
  38222. get: function () {
  38223. return this._shadowsDensity;
  38224. },
  38225. /**
  38226. * Sets the shadows Density value.
  38227. * 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.
  38228. * Values less than zero provide a filter of opposite hue.
  38229. */
  38230. set: function (value) {
  38231. this._shadowsDensity = value;
  38232. this._dirty = true;
  38233. },
  38234. enumerable: true,
  38235. configurable: true
  38236. });
  38237. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38238. /**
  38239. * Gets the shadows Saturation value.
  38240. * 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.
  38241. */
  38242. get: function () {
  38243. return this._shadowsSaturation;
  38244. },
  38245. /**
  38246. * Sets the shadows Saturation value.
  38247. * 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.
  38248. */
  38249. set: function (value) {
  38250. this._shadowsSaturation = value;
  38251. this._dirty = true;
  38252. },
  38253. enumerable: true,
  38254. configurable: true
  38255. });
  38256. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38257. /**
  38258. * Gets the shadows Exposure value.
  38259. * 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.
  38260. */
  38261. get: function () {
  38262. return this._shadowsExposure;
  38263. },
  38264. /**
  38265. * Sets the shadows Exposure value.
  38266. * 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.
  38267. */
  38268. set: function (value) {
  38269. this._shadowsExposure = value;
  38270. this._dirty = true;
  38271. },
  38272. enumerable: true,
  38273. configurable: true
  38274. });
  38275. ColorCurves.prototype.getClassName = function () {
  38276. return "ColorCurves";
  38277. };
  38278. /**
  38279. * Binds the color curves to the shader.
  38280. * @param colorCurves The color curve to bind
  38281. * @param effect The effect to bind to
  38282. */
  38283. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38284. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38285. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38286. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38287. if (colorCurves._dirty) {
  38288. colorCurves._dirty = false;
  38289. // Fill in global info.
  38290. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38291. // Compute highlights info.
  38292. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38293. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38294. // Compute midtones info.
  38295. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38296. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38297. // Compute shadows info.
  38298. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38299. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38300. // Compute deltas (neutral is midtones).
  38301. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38302. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38303. }
  38304. if (effect) {
  38305. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38306. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38307. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38308. }
  38309. };
  38310. /**
  38311. * Prepare the list of uniforms associated with the ColorCurves effects.
  38312. * @param uniformsList The list of uniforms used in the effect
  38313. */
  38314. ColorCurves.PrepareUniforms = function (uniformsList) {
  38315. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38316. };
  38317. /**
  38318. * Returns color grading data based on a hue, density, saturation and exposure value.
  38319. * @param filterHue The hue of the color filter.
  38320. * @param filterDensity The density of the color filter.
  38321. * @param saturation The saturation.
  38322. * @param exposure The exposure.
  38323. * @param result The result data container.
  38324. */
  38325. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38326. if (hue == null) {
  38327. return;
  38328. }
  38329. hue = ColorCurves.clamp(hue, 0, 360);
  38330. density = ColorCurves.clamp(density, -100, 100);
  38331. saturation = ColorCurves.clamp(saturation, -100, 100);
  38332. exposure = ColorCurves.clamp(exposure, -100, 100);
  38333. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38334. // so that the maximum filter density is only 50% control. This provides fine control
  38335. // for small values and reasonable range.
  38336. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38337. density *= 0.5;
  38338. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38339. if (density < 0) {
  38340. density *= -1;
  38341. hue = (hue + 180) % 360;
  38342. }
  38343. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38344. result.scaleToRef(2, result);
  38345. result.a = 1 + 0.01 * saturation;
  38346. };
  38347. /**
  38348. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38349. * @param value The input slider value in range [-100,100].
  38350. * @returns Adjusted value.
  38351. */
  38352. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38353. value /= 100;
  38354. var x = Math.abs(value);
  38355. x = Math.pow(x, 2);
  38356. if (value < 0) {
  38357. x *= -1;
  38358. }
  38359. x *= 100;
  38360. return x;
  38361. };
  38362. /**
  38363. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38364. * @param hue The hue (H) input.
  38365. * @param saturation The saturation (S) input.
  38366. * @param brightness The brightness (B) input.
  38367. * @result An RGBA color represented as Vector4.
  38368. */
  38369. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38370. var h = ColorCurves.clamp(hue, 0, 360);
  38371. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38372. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38373. if (s === 0) {
  38374. result.r = v;
  38375. result.g = v;
  38376. result.b = v;
  38377. }
  38378. else {
  38379. // sector 0 to 5
  38380. h /= 60;
  38381. var i = Math.floor(h);
  38382. // fractional part of h
  38383. var f = h - i;
  38384. var p = v * (1 - s);
  38385. var q = v * (1 - s * f);
  38386. var t = v * (1 - s * (1 - f));
  38387. switch (i) {
  38388. case 0:
  38389. result.r = v;
  38390. result.g = t;
  38391. result.b = p;
  38392. break;
  38393. case 1:
  38394. result.r = q;
  38395. result.g = v;
  38396. result.b = p;
  38397. break;
  38398. case 2:
  38399. result.r = p;
  38400. result.g = v;
  38401. result.b = t;
  38402. break;
  38403. case 3:
  38404. result.r = p;
  38405. result.g = q;
  38406. result.b = v;
  38407. break;
  38408. case 4:
  38409. result.r = t;
  38410. result.g = p;
  38411. result.b = v;
  38412. break;
  38413. default:// case 5:
  38414. result.r = v;
  38415. result.g = p;
  38416. result.b = q;
  38417. break;
  38418. }
  38419. }
  38420. result.a = 1;
  38421. };
  38422. /**
  38423. * Returns a value clamped between min and max
  38424. * @param value The value to clamp
  38425. * @param min The minimum of value
  38426. * @param max The maximum of value
  38427. * @returns The clamped value.
  38428. */
  38429. ColorCurves.clamp = function (value, min, max) {
  38430. return Math.min(Math.max(value, min), max);
  38431. };
  38432. /**
  38433. * Clones the current color curve instance.
  38434. * @return The cloned curves
  38435. */
  38436. ColorCurves.prototype.clone = function () {
  38437. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38438. };
  38439. /**
  38440. * Serializes the current color curve instance to a json representation.
  38441. * @return a JSON representation
  38442. */
  38443. ColorCurves.prototype.serialize = function () {
  38444. return BABYLON.SerializationHelper.Serialize(this);
  38445. };
  38446. /**
  38447. * Parses the color curve from a json representation.
  38448. * @param source the JSON source to parse
  38449. * @return The parsed curves
  38450. */
  38451. ColorCurves.Parse = function (source) {
  38452. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38453. };
  38454. __decorate([
  38455. BABYLON.serialize()
  38456. ], ColorCurves.prototype, "_globalHue", void 0);
  38457. __decorate([
  38458. BABYLON.serialize()
  38459. ], ColorCurves.prototype, "_globalDensity", void 0);
  38460. __decorate([
  38461. BABYLON.serialize()
  38462. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38463. __decorate([
  38464. BABYLON.serialize()
  38465. ], ColorCurves.prototype, "_globalExposure", void 0);
  38466. __decorate([
  38467. BABYLON.serialize()
  38468. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38469. __decorate([
  38470. BABYLON.serialize()
  38471. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38472. __decorate([
  38473. BABYLON.serialize()
  38474. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38475. __decorate([
  38476. BABYLON.serialize()
  38477. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38478. __decorate([
  38479. BABYLON.serialize()
  38480. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38481. __decorate([
  38482. BABYLON.serialize()
  38483. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38484. __decorate([
  38485. BABYLON.serialize()
  38486. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38487. __decorate([
  38488. BABYLON.serialize()
  38489. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38490. return ColorCurves;
  38491. }());
  38492. BABYLON.ColorCurves = ColorCurves;
  38493. })(BABYLON || (BABYLON = {}));
  38494. //# sourceMappingURL=babylon.colorCurves.js.map
  38495. //# sourceMappingURL=babylon.behavior.js.map
  38496. var BABYLON;
  38497. (function (BABYLON) {
  38498. /**
  38499. * "Static Class" containing the most commonly used helper while dealing with material for
  38500. * rendering purpose.
  38501. *
  38502. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38503. *
  38504. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38505. */
  38506. var MaterialHelper = /** @class */ (function () {
  38507. function MaterialHelper() {
  38508. }
  38509. /**
  38510. * Bind the current view position to an effect.
  38511. * @param effect The effect to be bound
  38512. * @param scene The scene the eyes position is used from
  38513. */
  38514. MaterialHelper.BindEyePosition = function (effect, scene) {
  38515. if (scene._forcedViewPosition) {
  38516. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38517. return;
  38518. }
  38519. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38520. };
  38521. /**
  38522. * Helps preparing the defines values about the UVs in used in the effect.
  38523. * UVs are shared as much as we can accross chanels in the shaders.
  38524. * @param texture The texture we are preparing the UVs for
  38525. * @param defines The defines to update
  38526. * @param key The chanel key "diffuse", "specular"... used in the shader
  38527. */
  38528. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38529. defines._needUVs = true;
  38530. defines[key] = true;
  38531. if (texture.getTextureMatrix().isIdentity(true)) {
  38532. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38533. if (texture.coordinatesIndex === 0) {
  38534. defines["MAINUV1"] = true;
  38535. }
  38536. else {
  38537. defines["MAINUV2"] = true;
  38538. }
  38539. }
  38540. else {
  38541. defines[key + "DIRECTUV"] = 0;
  38542. }
  38543. };
  38544. /**
  38545. * Binds a texture matrix value to its corrsponding uniform
  38546. * @param texture The texture to bind the matrix for
  38547. * @param uniformBuffer The uniform buffer receivin the data
  38548. * @param key The chanel key "diffuse", "specular"... used in the shader
  38549. */
  38550. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38551. var matrix = texture.getTextureMatrix();
  38552. if (!matrix.isIdentity(true)) {
  38553. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38554. }
  38555. };
  38556. /**
  38557. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38558. * @param mesh defines the current mesh
  38559. * @param scene defines the current scene
  38560. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38561. * @param pointsCloud defines if point cloud rendering has to be turned on
  38562. * @param fogEnabled defines if fog has to be turned on
  38563. * @param alphaTest defines if alpha testing has to be turned on
  38564. * @param defines defines the current list of defines
  38565. */
  38566. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38567. if (defines._areMiscDirty) {
  38568. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38569. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  38570. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38571. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38572. defines["ALPHATEST"] = alphaTest;
  38573. }
  38574. };
  38575. /**
  38576. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38577. * @param scene defines the current scene
  38578. * @param engine defines the current engine
  38579. * @param defines specifies the list of active defines
  38580. * @param useInstances defines if instances have to be turned on
  38581. * @param useClipPlane defines if clip plane have to be turned on
  38582. */
  38583. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38584. if (useClipPlane === void 0) { useClipPlane = null; }
  38585. var changed = false;
  38586. if (useClipPlane == null) {
  38587. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38588. }
  38589. if (defines["CLIPPLANE"] !== useClipPlane) {
  38590. defines["CLIPPLANE"] = useClipPlane;
  38591. changed = true;
  38592. }
  38593. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38594. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38595. changed = true;
  38596. }
  38597. if (defines["INSTANCES"] !== useInstances) {
  38598. defines["INSTANCES"] = useInstances;
  38599. changed = true;
  38600. }
  38601. if (changed) {
  38602. defines.markAsUnprocessed();
  38603. }
  38604. };
  38605. /**
  38606. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38607. * @param mesh The mesh containing the geometry data we will draw
  38608. * @param defines The defines to update
  38609. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38610. * @param useBones Precise whether bones should be used or not (override mesh info)
  38611. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38612. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38613. * @returns false if defines are considered not dirty and have not been checked
  38614. */
  38615. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38616. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38617. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38618. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38619. return false;
  38620. }
  38621. defines._normals = defines._needNormals;
  38622. defines._uvs = defines._needUVs;
  38623. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38624. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38625. defines["TANGENT"] = true;
  38626. }
  38627. if (defines._needUVs) {
  38628. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38629. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38630. }
  38631. else {
  38632. defines["UV1"] = false;
  38633. defines["UV2"] = false;
  38634. }
  38635. if (useVertexColor) {
  38636. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38637. defines["VERTEXCOLOR"] = hasVertexColors;
  38638. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38639. }
  38640. if (useBones) {
  38641. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38642. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38643. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38644. }
  38645. else {
  38646. defines["NUM_BONE_INFLUENCERS"] = 0;
  38647. defines["BonesPerMesh"] = 0;
  38648. }
  38649. }
  38650. if (useMorphTargets) {
  38651. var manager = mesh.morphTargetManager;
  38652. if (manager) {
  38653. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38654. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38655. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38656. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38657. }
  38658. else {
  38659. defines["MORPHTARGETS_TANGENT"] = false;
  38660. defines["MORPHTARGETS_NORMAL"] = false;
  38661. defines["MORPHTARGETS"] = false;
  38662. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38663. }
  38664. }
  38665. return true;
  38666. };
  38667. /**
  38668. * Prepares the defines related to the light information passed in parameter
  38669. * @param scene The scene we are intending to draw
  38670. * @param mesh The mesh the effect is compiling for
  38671. * @param defines The defines to update
  38672. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38673. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38674. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38675. * @returns true if normals will be required for the rest of the effect
  38676. */
  38677. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38678. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38679. if (disableLighting === void 0) { disableLighting = false; }
  38680. if (!defines._areLightsDirty) {
  38681. return defines._needNormals;
  38682. }
  38683. var lightIndex = 0;
  38684. var needNormals = false;
  38685. var needRebuild = false;
  38686. var lightmapMode = false;
  38687. var shadowEnabled = false;
  38688. var specularEnabled = false;
  38689. if (scene.lightsEnabled && !disableLighting) {
  38690. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38691. var light = _a[_i];
  38692. needNormals = true;
  38693. if (defines["LIGHT" + lightIndex] === undefined) {
  38694. needRebuild = true;
  38695. }
  38696. defines["LIGHT" + lightIndex] = true;
  38697. defines["SPOTLIGHT" + lightIndex] = false;
  38698. defines["HEMILIGHT" + lightIndex] = false;
  38699. defines["POINTLIGHT" + lightIndex] = false;
  38700. defines["DIRLIGHT" + lightIndex] = false;
  38701. var type;
  38702. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38703. type = "SPOTLIGHT" + lightIndex;
  38704. var spotLight = light;
  38705. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38706. }
  38707. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38708. type = "HEMILIGHT" + lightIndex;
  38709. }
  38710. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38711. type = "POINTLIGHT" + lightIndex;
  38712. }
  38713. else {
  38714. type = "DIRLIGHT" + lightIndex;
  38715. }
  38716. defines[type] = true;
  38717. // Specular
  38718. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38719. specularEnabled = true;
  38720. }
  38721. // Shadows
  38722. defines["SHADOW" + lightIndex] = false;
  38723. defines["SHADOWPCF" + lightIndex] = false;
  38724. defines["SHADOWPCSS" + lightIndex] = false;
  38725. defines["SHADOWPOISSON" + lightIndex] = false;
  38726. defines["SHADOWESM" + lightIndex] = false;
  38727. defines["SHADOWCUBE" + lightIndex] = false;
  38728. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  38729. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  38730. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38731. var shadowGenerator = light.getShadowGenerator();
  38732. if (shadowGenerator) {
  38733. shadowEnabled = true;
  38734. shadowGenerator.prepareDefines(defines, lightIndex);
  38735. }
  38736. }
  38737. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38738. lightmapMode = true;
  38739. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38740. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38741. }
  38742. else {
  38743. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38744. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38745. }
  38746. lightIndex++;
  38747. if (lightIndex === maxSimultaneousLights)
  38748. break;
  38749. }
  38750. }
  38751. defines["SPECULARTERM"] = specularEnabled;
  38752. defines["SHADOWS"] = shadowEnabled;
  38753. // Resetting all other lights if any
  38754. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38755. if (defines["LIGHT" + index] !== undefined) {
  38756. defines["LIGHT" + index] = false;
  38757. defines["HEMILIGHT" + lightIndex] = false;
  38758. defines["POINTLIGHT" + lightIndex] = false;
  38759. defines["DIRLIGHT" + lightIndex] = false;
  38760. defines["SPOTLIGHT" + lightIndex] = false;
  38761. defines["SHADOW" + lightIndex] = false;
  38762. }
  38763. }
  38764. var caps = scene.getEngine().getCaps();
  38765. if (defines["SHADOWFLOAT"] === undefined) {
  38766. needRebuild = true;
  38767. }
  38768. defines["SHADOWFLOAT"] = shadowEnabled &&
  38769. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38770. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38771. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38772. if (needRebuild) {
  38773. defines.rebuild();
  38774. }
  38775. return needNormals;
  38776. };
  38777. /**
  38778. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38779. * that won t be acctive due to defines being turned off.
  38780. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38781. * @param samplersList The samplers list
  38782. * @param defines The defines helping in the list generation
  38783. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38784. */
  38785. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38786. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38787. var uniformsList;
  38788. var uniformBuffersList = null;
  38789. if (uniformsListOrOptions.uniformsNames) {
  38790. var options = uniformsListOrOptions;
  38791. uniformsList = options.uniformsNames;
  38792. uniformBuffersList = options.uniformBuffersNames;
  38793. samplersList = options.samplers;
  38794. defines = options.defines;
  38795. maxSimultaneousLights = options.maxSimultaneousLights;
  38796. }
  38797. else {
  38798. uniformsList = uniformsListOrOptions;
  38799. if (!samplersList) {
  38800. samplersList = [];
  38801. }
  38802. }
  38803. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38804. if (!defines["LIGHT" + lightIndex]) {
  38805. break;
  38806. }
  38807. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38808. if (uniformBuffersList) {
  38809. uniformBuffersList.push("Light" + lightIndex);
  38810. }
  38811. samplersList.push("shadowSampler" + lightIndex);
  38812. samplersList.push("depthSampler" + lightIndex);
  38813. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38814. samplersList.push("projectionLightSampler" + lightIndex);
  38815. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38816. }
  38817. }
  38818. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38819. uniformsList.push("morphTargetInfluences");
  38820. }
  38821. };
  38822. /**
  38823. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38824. * @param defines The defines to update while falling back
  38825. * @param fallbacks The authorized effect fallbacks
  38826. * @param maxSimultaneousLights The maximum number of lights allowed
  38827. * @param rank the current rank of the Effect
  38828. * @returns The newly affected rank
  38829. */
  38830. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38831. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38832. if (rank === void 0) { rank = 0; }
  38833. var lightFallbackRank = 0;
  38834. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38835. if (!defines["LIGHT" + lightIndex]) {
  38836. break;
  38837. }
  38838. if (lightIndex > 0) {
  38839. lightFallbackRank = rank + lightIndex;
  38840. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38841. }
  38842. if (!defines["SHADOWS"]) {
  38843. if (defines["SHADOW" + lightIndex]) {
  38844. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38845. }
  38846. if (defines["SHADOWPCF" + lightIndex]) {
  38847. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38848. }
  38849. if (defines["SHADOWPCSS" + lightIndex]) {
  38850. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  38851. }
  38852. if (defines["SHADOWPOISSON" + lightIndex]) {
  38853. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  38854. }
  38855. if (defines["SHADOWESM" + lightIndex]) {
  38856. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38857. }
  38858. }
  38859. }
  38860. return lightFallbackRank++;
  38861. };
  38862. /**
  38863. * Prepares the list of attributes required for morph targets according to the effect defines.
  38864. * @param attribs The current list of supported attribs
  38865. * @param mesh The mesh to prepare the morph targets attributes for
  38866. * @param defines The current Defines of the effect
  38867. */
  38868. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38869. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38870. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38871. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38872. var manager = mesh.morphTargetManager;
  38873. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38874. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38875. for (var index = 0; index < influencers; index++) {
  38876. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38877. if (normal) {
  38878. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38879. }
  38880. if (tangent) {
  38881. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38882. }
  38883. if (attribs.length > maxAttributesCount) {
  38884. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38885. }
  38886. }
  38887. }
  38888. };
  38889. /**
  38890. * Prepares the list of attributes required for bones according to the effect defines.
  38891. * @param attribs The current list of supported attribs
  38892. * @param mesh The mesh to prepare the bones attributes for
  38893. * @param defines The current Defines of the effect
  38894. * @param fallbacks The current efffect fallback strategy
  38895. */
  38896. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38897. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38898. fallbacks.addCPUSkinningFallback(0, mesh);
  38899. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38900. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38901. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38902. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38903. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38904. }
  38905. }
  38906. };
  38907. /**
  38908. * Prepares the list of attributes required for instances according to the effect defines.
  38909. * @param attribs The current list of supported attribs
  38910. * @param defines The current Defines of the effect
  38911. */
  38912. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38913. if (defines["INSTANCES"]) {
  38914. attribs.push("world0");
  38915. attribs.push("world1");
  38916. attribs.push("world2");
  38917. attribs.push("world3");
  38918. }
  38919. };
  38920. /**
  38921. * Binds the light shadow information to the effect for the given mesh.
  38922. * @param light The light containing the generator
  38923. * @param scene The scene the lights belongs to
  38924. * @param mesh The mesh we are binding the information to render
  38925. * @param lightIndex The light index in the effect used to render the mesh
  38926. * @param effect The effect we are binding the data to
  38927. */
  38928. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38929. if (light.shadowEnabled && mesh.receiveShadows) {
  38930. var shadowGenerator = light.getShadowGenerator();
  38931. if (shadowGenerator) {
  38932. shadowGenerator.bindShadowLight(lightIndex, effect);
  38933. }
  38934. }
  38935. };
  38936. /**
  38937. * Binds the light information to the effect.
  38938. * @param light The light containing the generator
  38939. * @param effect The effect we are binding the data to
  38940. * @param lightIndex The light index in the effect used to render
  38941. */
  38942. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38943. light.transferToEffect(effect, lightIndex + "");
  38944. };
  38945. /**
  38946. * Binds the lights information from the scene to the effect for the given mesh.
  38947. * @param scene The scene the lights belongs to
  38948. * @param mesh The mesh we are binding the information to render
  38949. * @param effect The effect we are binding the data to
  38950. * @param defines The generated defines for the effect
  38951. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38952. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38953. */
  38954. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38955. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38956. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38957. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38958. for (var i = 0; i < len; i++) {
  38959. var light = mesh._lightSources[i];
  38960. var iAsString = i.toString();
  38961. var scaledIntensity = light.getScaledIntensity();
  38962. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38963. MaterialHelper.BindLightProperties(light, effect, i);
  38964. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38965. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38966. if (defines["SPECULARTERM"]) {
  38967. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38968. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38969. }
  38970. // Shadows
  38971. if (scene.shadowsEnabled) {
  38972. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38973. }
  38974. light._uniformBuffer.update();
  38975. }
  38976. };
  38977. /**
  38978. * Binds the fog information from the scene to the effect for the given mesh.
  38979. * @param scene The scene the lights belongs to
  38980. * @param mesh The mesh we are binding the information to render
  38981. * @param effect The effect we are binding the data to
  38982. */
  38983. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38984. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38985. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38986. effect.setColor3("vFogColor", scene.fogColor);
  38987. }
  38988. };
  38989. /**
  38990. * Binds the bones information from the mesh to the effect.
  38991. * @param mesh The mesh we are binding the information to render
  38992. * @param effect The effect we are binding the data to
  38993. */
  38994. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38995. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38996. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38997. if (matrices && effect) {
  38998. effect.setMatrices("mBones", matrices);
  38999. }
  39000. }
  39001. };
  39002. /**
  39003. * Binds the morph targets information from the mesh to the effect.
  39004. * @param abstractMesh The mesh we are binding the information to render
  39005. * @param effect The effect we are binding the data to
  39006. */
  39007. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  39008. var manager = abstractMesh.morphTargetManager;
  39009. if (!abstractMesh || !manager) {
  39010. return;
  39011. }
  39012. effect.setFloatArray("morphTargetInfluences", manager.influences);
  39013. };
  39014. /**
  39015. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  39016. * @param defines The generated defines used in the effect
  39017. * @param effect The effect we are binding the data to
  39018. * @param scene The scene we are willing to render with logarithmic scale for
  39019. */
  39020. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  39021. if (defines["LOGARITHMICDEPTH"]) {
  39022. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  39023. }
  39024. };
  39025. /**
  39026. * Binds the clip plane information from the scene to the effect.
  39027. * @param scene The scene the clip plane information are extracted from
  39028. * @param effect The effect we are binding the data to
  39029. */
  39030. MaterialHelper.BindClipPlane = function (effect, scene) {
  39031. if (scene.clipPlane) {
  39032. var clipPlane = scene.clipPlane;
  39033. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  39034. }
  39035. };
  39036. return MaterialHelper;
  39037. }());
  39038. BABYLON.MaterialHelper = MaterialHelper;
  39039. })(BABYLON || (BABYLON = {}));
  39040. //# sourceMappingURL=babylon.materialHelper.js.map
  39041. var BABYLON;
  39042. (function (BABYLON) {
  39043. var PushMaterial = /** @class */ (function (_super) {
  39044. __extends(PushMaterial, _super);
  39045. function PushMaterial(name, scene) {
  39046. var _this = _super.call(this, name, scene) || this;
  39047. _this._normalMatrix = new BABYLON.Matrix();
  39048. _this.storeEffectOnSubMeshes = true;
  39049. return _this;
  39050. }
  39051. PushMaterial.prototype.getEffect = function () {
  39052. return this._activeEffect;
  39053. };
  39054. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  39055. if (!mesh) {
  39056. return false;
  39057. }
  39058. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  39059. return true;
  39060. }
  39061. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  39062. };
  39063. /**
  39064. * Binds the given world matrix to the active effect
  39065. *
  39066. * @param world the matrix to bind
  39067. */
  39068. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39069. this._activeEffect.setMatrix("world", world);
  39070. };
  39071. /**
  39072. * Binds the given normal matrix to the active effect
  39073. *
  39074. * @param normalMatrix the matrix to bind
  39075. */
  39076. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  39077. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  39078. };
  39079. PushMaterial.prototype.bind = function (world, mesh) {
  39080. if (!mesh) {
  39081. return;
  39082. }
  39083. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  39084. };
  39085. PushMaterial.prototype._afterBind = function (mesh, effect) {
  39086. if (effect === void 0) { effect = null; }
  39087. _super.prototype._afterBind.call(this, mesh);
  39088. this.getScene()._cachedEffect = effect;
  39089. };
  39090. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  39091. if (visibility === void 0) { visibility = 1; }
  39092. return scene.isCachedMaterialInvalid(this, effect, visibility);
  39093. };
  39094. return PushMaterial;
  39095. }(BABYLON.Material));
  39096. BABYLON.PushMaterial = PushMaterial;
  39097. })(BABYLON || (BABYLON = {}));
  39098. //# sourceMappingURL=babylon.pushMaterial.js.map
  39099. var BABYLON;
  39100. (function (BABYLON) {
  39101. /** @ignore */
  39102. var StandardMaterialDefines = /** @class */ (function (_super) {
  39103. __extends(StandardMaterialDefines, _super);
  39104. function StandardMaterialDefines() {
  39105. var _this = _super.call(this) || this;
  39106. _this.MAINUV1 = false;
  39107. _this.MAINUV2 = false;
  39108. _this.DIFFUSE = false;
  39109. _this.DIFFUSEDIRECTUV = 0;
  39110. _this.AMBIENT = false;
  39111. _this.AMBIENTDIRECTUV = 0;
  39112. _this.OPACITY = false;
  39113. _this.OPACITYDIRECTUV = 0;
  39114. _this.OPACITYRGB = false;
  39115. _this.REFLECTION = false;
  39116. _this.EMISSIVE = false;
  39117. _this.EMISSIVEDIRECTUV = 0;
  39118. _this.SPECULAR = false;
  39119. _this.SPECULARDIRECTUV = 0;
  39120. _this.BUMP = false;
  39121. _this.BUMPDIRECTUV = 0;
  39122. _this.PARALLAX = false;
  39123. _this.PARALLAXOCCLUSION = false;
  39124. _this.SPECULAROVERALPHA = false;
  39125. _this.CLIPPLANE = false;
  39126. _this.ALPHATEST = false;
  39127. _this.DEPTHPREPASS = false;
  39128. _this.ALPHAFROMDIFFUSE = false;
  39129. _this.POINTSIZE = false;
  39130. _this.FOG = false;
  39131. _this.SPECULARTERM = false;
  39132. _this.DIFFUSEFRESNEL = false;
  39133. _this.OPACITYFRESNEL = false;
  39134. _this.REFLECTIONFRESNEL = false;
  39135. _this.REFRACTIONFRESNEL = false;
  39136. _this.EMISSIVEFRESNEL = false;
  39137. _this.FRESNEL = false;
  39138. _this.NORMAL = false;
  39139. _this.UV1 = false;
  39140. _this.UV2 = false;
  39141. _this.VERTEXCOLOR = false;
  39142. _this.VERTEXALPHA = false;
  39143. _this.NUM_BONE_INFLUENCERS = 0;
  39144. _this.BonesPerMesh = 0;
  39145. _this.INSTANCES = false;
  39146. _this.GLOSSINESS = false;
  39147. _this.ROUGHNESS = false;
  39148. _this.EMISSIVEASILLUMINATION = false;
  39149. _this.LINKEMISSIVEWITHDIFFUSE = false;
  39150. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  39151. _this.LIGHTMAP = false;
  39152. _this.LIGHTMAPDIRECTUV = 0;
  39153. _this.OBJECTSPACE_NORMALMAP = false;
  39154. _this.USELIGHTMAPASSHADOWMAP = false;
  39155. _this.REFLECTIONMAP_3D = false;
  39156. _this.REFLECTIONMAP_SPHERICAL = false;
  39157. _this.REFLECTIONMAP_PLANAR = false;
  39158. _this.REFLECTIONMAP_CUBIC = false;
  39159. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39160. _this.REFLECTIONMAP_PROJECTION = false;
  39161. _this.REFLECTIONMAP_SKYBOX = false;
  39162. _this.REFLECTIONMAP_EXPLICIT = false;
  39163. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39164. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39165. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39166. _this.INVERTCUBICMAP = false;
  39167. _this.LOGARITHMICDEPTH = false;
  39168. _this.REFRACTION = false;
  39169. _this.REFRACTIONMAP_3D = false;
  39170. _this.REFLECTIONOVERALPHA = false;
  39171. _this.TWOSIDEDLIGHTING = false;
  39172. _this.SHADOWFLOAT = false;
  39173. _this.MORPHTARGETS = false;
  39174. _this.MORPHTARGETS_NORMAL = false;
  39175. _this.MORPHTARGETS_TANGENT = false;
  39176. _this.NUM_MORPH_INFLUENCERS = 0;
  39177. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39178. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39179. _this.IMAGEPROCESSING = false;
  39180. _this.VIGNETTE = false;
  39181. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39182. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39183. _this.TONEMAPPING = false;
  39184. _this.CONTRAST = false;
  39185. _this.COLORCURVES = false;
  39186. _this.COLORGRADING = false;
  39187. _this.COLORGRADING3D = false;
  39188. _this.SAMPLER3DGREENDEPTH = false;
  39189. _this.SAMPLER3DBGRMAP = false;
  39190. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39191. _this.EXPOSURE = false;
  39192. _this.GRAIN = false;
  39193. _this.rebuild();
  39194. return _this;
  39195. }
  39196. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39197. var modes = [
  39198. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39199. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39200. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39201. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39202. ];
  39203. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39204. var mode = modes_1[_i];
  39205. this[mode] = (mode === modeToEnable);
  39206. }
  39207. };
  39208. return StandardMaterialDefines;
  39209. }(BABYLON.MaterialDefines));
  39210. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39211. var StandardMaterial = /** @class */ (function (_super) {
  39212. __extends(StandardMaterial, _super);
  39213. function StandardMaterial(name, scene) {
  39214. var _this = _super.call(this, name, scene) || this;
  39215. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39216. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39217. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39218. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39219. _this.specularPower = 64;
  39220. _this._useAlphaFromDiffuseTexture = false;
  39221. _this._useEmissiveAsIllumination = false;
  39222. _this._linkEmissiveWithDiffuse = false;
  39223. _this._useSpecularOverAlpha = false;
  39224. _this._useReflectionOverAlpha = false;
  39225. _this._disableLighting = false;
  39226. _this._useObjectSpaceNormalMap = false;
  39227. _this._useParallax = false;
  39228. _this._useParallaxOcclusion = false;
  39229. _this.parallaxScaleBias = 0.05;
  39230. _this._roughness = 0;
  39231. _this.indexOfRefraction = 0.98;
  39232. _this.invertRefractionY = true;
  39233. _this._useLightmapAsShadowmap = false;
  39234. _this._useReflectionFresnelFromSpecular = false;
  39235. _this._useGlossinessFromSpecularMapAlpha = false;
  39236. _this._maxSimultaneousLights = 4;
  39237. /**
  39238. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39239. */
  39240. _this._invertNormalMapX = false;
  39241. /**
  39242. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39243. */
  39244. _this._invertNormalMapY = false;
  39245. /**
  39246. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39247. */
  39248. _this._twoSidedLighting = false;
  39249. _this._renderTargets = new BABYLON.SmartArray(16);
  39250. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39251. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39252. // Setup the default processing configuration to the scene.
  39253. _this._attachImageProcessingConfiguration(null);
  39254. _this.getRenderTargetTextures = function () {
  39255. _this._renderTargets.reset();
  39256. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39257. _this._renderTargets.push(_this._reflectionTexture);
  39258. }
  39259. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39260. _this._renderTargets.push(_this._refractionTexture);
  39261. }
  39262. return _this._renderTargets;
  39263. };
  39264. return _this;
  39265. }
  39266. ;
  39267. ;
  39268. ;
  39269. ;
  39270. ;
  39271. ;
  39272. ;
  39273. ;
  39274. ;
  39275. ;
  39276. ;
  39277. ;
  39278. ;
  39279. ;
  39280. ;
  39281. ;
  39282. ;
  39283. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39284. /**
  39285. * Gets the image processing configuration used either in this material.
  39286. */
  39287. get: function () {
  39288. return this._imageProcessingConfiguration;
  39289. },
  39290. /**
  39291. * Sets the Default image processing configuration used either in the this material.
  39292. *
  39293. * If sets to null, the scene one is in use.
  39294. */
  39295. set: function (value) {
  39296. this._attachImageProcessingConfiguration(value);
  39297. // Ensure the effect will be rebuilt.
  39298. this._markAllSubMeshesAsTexturesDirty();
  39299. },
  39300. enumerable: true,
  39301. configurable: true
  39302. });
  39303. /**
  39304. * Attaches a new image processing configuration to the Standard Material.
  39305. * @param configuration
  39306. */
  39307. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39308. var _this = this;
  39309. if (configuration === this._imageProcessingConfiguration) {
  39310. return;
  39311. }
  39312. // Detaches observer.
  39313. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39314. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39315. }
  39316. // Pick the scene configuration if needed.
  39317. if (!configuration) {
  39318. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39319. }
  39320. else {
  39321. this._imageProcessingConfiguration = configuration;
  39322. }
  39323. // Attaches observer.
  39324. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39325. _this._markAllSubMeshesAsImageProcessingDirty();
  39326. });
  39327. };
  39328. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39329. /**
  39330. * Gets wether the color curves effect is enabled.
  39331. */
  39332. get: function () {
  39333. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39334. },
  39335. /**
  39336. * Sets wether the color curves effect is enabled.
  39337. */
  39338. set: function (value) {
  39339. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39340. },
  39341. enumerable: true,
  39342. configurable: true
  39343. });
  39344. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39345. /**
  39346. * Gets wether the color grading effect is enabled.
  39347. */
  39348. get: function () {
  39349. return this.imageProcessingConfiguration.colorGradingEnabled;
  39350. },
  39351. /**
  39352. * Gets wether the color grading effect is enabled.
  39353. */
  39354. set: function (value) {
  39355. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39356. },
  39357. enumerable: true,
  39358. configurable: true
  39359. });
  39360. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39361. /**
  39362. * Gets wether tonemapping is enabled or not.
  39363. */
  39364. get: function () {
  39365. return this._imageProcessingConfiguration.toneMappingEnabled;
  39366. },
  39367. /**
  39368. * Sets wether tonemapping is enabled or not
  39369. */
  39370. set: function (value) {
  39371. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39372. },
  39373. enumerable: true,
  39374. configurable: true
  39375. });
  39376. ;
  39377. ;
  39378. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39379. /**
  39380. * The camera exposure used on this material.
  39381. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39382. * This corresponds to a photographic exposure.
  39383. */
  39384. get: function () {
  39385. return this._imageProcessingConfiguration.exposure;
  39386. },
  39387. /**
  39388. * The camera exposure used on this material.
  39389. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39390. * This corresponds to a photographic exposure.
  39391. */
  39392. set: function (value) {
  39393. this._imageProcessingConfiguration.exposure = value;
  39394. },
  39395. enumerable: true,
  39396. configurable: true
  39397. });
  39398. ;
  39399. ;
  39400. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39401. /**
  39402. * Gets The camera contrast used on this material.
  39403. */
  39404. get: function () {
  39405. return this._imageProcessingConfiguration.contrast;
  39406. },
  39407. /**
  39408. * Sets The camera contrast used on this material.
  39409. */
  39410. set: function (value) {
  39411. this._imageProcessingConfiguration.contrast = value;
  39412. },
  39413. enumerable: true,
  39414. configurable: true
  39415. });
  39416. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39417. /**
  39418. * Gets the Color Grading 2D Lookup Texture.
  39419. */
  39420. get: function () {
  39421. return this._imageProcessingConfiguration.colorGradingTexture;
  39422. },
  39423. /**
  39424. * Sets the Color Grading 2D Lookup Texture.
  39425. */
  39426. set: function (value) {
  39427. this._imageProcessingConfiguration.colorGradingTexture = value;
  39428. },
  39429. enumerable: true,
  39430. configurable: true
  39431. });
  39432. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39433. /**
  39434. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39435. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39436. * 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;
  39437. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39438. */
  39439. get: function () {
  39440. return this._imageProcessingConfiguration.colorCurves;
  39441. },
  39442. /**
  39443. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39444. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39445. * 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;
  39446. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39447. */
  39448. set: function (value) {
  39449. this._imageProcessingConfiguration.colorCurves = value;
  39450. },
  39451. enumerable: true,
  39452. configurable: true
  39453. });
  39454. StandardMaterial.prototype.getClassName = function () {
  39455. return "StandardMaterial";
  39456. };
  39457. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39458. get: function () {
  39459. return this._useLogarithmicDepth;
  39460. },
  39461. set: function (value) {
  39462. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39463. this._markAllSubMeshesAsMiscDirty();
  39464. },
  39465. enumerable: true,
  39466. configurable: true
  39467. });
  39468. StandardMaterial.prototype.needAlphaBlending = function () {
  39469. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39470. };
  39471. StandardMaterial.prototype.needAlphaTesting = function () {
  39472. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39473. };
  39474. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39475. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39476. };
  39477. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39478. return this._diffuseTexture;
  39479. };
  39480. /**
  39481. * Child classes can use it to update shaders
  39482. */
  39483. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39484. if (useInstances === void 0) { useInstances = false; }
  39485. if (subMesh.effect && this.isFrozen) {
  39486. if (this._wasPreviouslyReady && subMesh.effect) {
  39487. return true;
  39488. }
  39489. }
  39490. if (!subMesh._materialDefines) {
  39491. subMesh._materialDefines = new StandardMaterialDefines();
  39492. }
  39493. var scene = this.getScene();
  39494. var defines = subMesh._materialDefines;
  39495. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39496. if (defines._renderId === scene.getRenderId()) {
  39497. return true;
  39498. }
  39499. }
  39500. var engine = scene.getEngine();
  39501. // Lights
  39502. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39503. // Textures
  39504. if (defines._areTexturesDirty) {
  39505. defines._needUVs = false;
  39506. defines.MAINUV1 = false;
  39507. defines.MAINUV2 = false;
  39508. if (scene.texturesEnabled) {
  39509. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39510. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39511. return false;
  39512. }
  39513. else {
  39514. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39515. }
  39516. }
  39517. else {
  39518. defines.DIFFUSE = false;
  39519. }
  39520. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39521. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39522. return false;
  39523. }
  39524. else {
  39525. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39526. }
  39527. }
  39528. else {
  39529. defines.AMBIENT = false;
  39530. }
  39531. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39532. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39533. return false;
  39534. }
  39535. else {
  39536. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39537. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39538. }
  39539. }
  39540. else {
  39541. defines.OPACITY = false;
  39542. }
  39543. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39544. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39545. return false;
  39546. }
  39547. else {
  39548. defines._needNormals = true;
  39549. defines.REFLECTION = true;
  39550. defines.ROUGHNESS = (this._roughness > 0);
  39551. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39552. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39553. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39554. switch (this._reflectionTexture.coordinatesMode) {
  39555. case BABYLON.Texture.CUBIC_MODE:
  39556. case BABYLON.Texture.INVCUBIC_MODE:
  39557. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39558. break;
  39559. case BABYLON.Texture.EXPLICIT_MODE:
  39560. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39561. break;
  39562. case BABYLON.Texture.PLANAR_MODE:
  39563. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39564. break;
  39565. case BABYLON.Texture.PROJECTION_MODE:
  39566. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39567. break;
  39568. case BABYLON.Texture.SKYBOX_MODE:
  39569. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39570. break;
  39571. case BABYLON.Texture.SPHERICAL_MODE:
  39572. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39573. break;
  39574. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39575. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39576. break;
  39577. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39578. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39579. break;
  39580. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39581. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39582. break;
  39583. }
  39584. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39585. }
  39586. }
  39587. else {
  39588. defines.REFLECTION = false;
  39589. }
  39590. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39591. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39592. return false;
  39593. }
  39594. else {
  39595. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39596. }
  39597. }
  39598. else {
  39599. defines.EMISSIVE = false;
  39600. }
  39601. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39602. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39603. return false;
  39604. }
  39605. else {
  39606. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39607. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39608. }
  39609. }
  39610. else {
  39611. defines.LIGHTMAP = false;
  39612. }
  39613. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39614. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39615. return false;
  39616. }
  39617. else {
  39618. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39619. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39620. }
  39621. }
  39622. else {
  39623. defines.SPECULAR = false;
  39624. }
  39625. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39626. // Bump texure can not be not blocking.
  39627. if (!this._bumpTexture.isReady()) {
  39628. return false;
  39629. }
  39630. else {
  39631. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39632. defines.PARALLAX = this._useParallax;
  39633. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39634. }
  39635. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39636. }
  39637. else {
  39638. defines.BUMP = false;
  39639. }
  39640. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39641. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39642. return false;
  39643. }
  39644. else {
  39645. defines._needUVs = true;
  39646. defines.REFRACTION = true;
  39647. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39648. }
  39649. }
  39650. else {
  39651. defines.REFRACTION = false;
  39652. }
  39653. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39654. }
  39655. else {
  39656. defines.DIFFUSE = false;
  39657. defines.AMBIENT = false;
  39658. defines.OPACITY = false;
  39659. defines.REFLECTION = false;
  39660. defines.EMISSIVE = false;
  39661. defines.LIGHTMAP = false;
  39662. defines.BUMP = false;
  39663. defines.REFRACTION = false;
  39664. }
  39665. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39666. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39667. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39668. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39669. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39670. }
  39671. if (defines._areImageProcessingDirty) {
  39672. if (!this._imageProcessingConfiguration.isReady()) {
  39673. return false;
  39674. }
  39675. this._imageProcessingConfiguration.prepareDefines(defines);
  39676. }
  39677. if (defines._areFresnelDirty) {
  39678. if (StandardMaterial.FresnelEnabled) {
  39679. // Fresnel
  39680. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39681. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39682. this._reflectionFresnelParameters) {
  39683. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39684. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39685. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39686. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39687. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39688. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39689. defines._needNormals = true;
  39690. defines.FRESNEL = true;
  39691. }
  39692. }
  39693. else {
  39694. defines.FRESNEL = false;
  39695. }
  39696. }
  39697. // Misc.
  39698. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39699. // Attribs
  39700. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39701. // Values that need to be evaluated on every frame
  39702. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39703. // Get correct effect
  39704. if (defines.isDirty) {
  39705. defines.markAsProcessed();
  39706. scene.resetCachedMaterial();
  39707. // Fallbacks
  39708. var fallbacks = new BABYLON.EffectFallbacks();
  39709. if (defines.REFLECTION) {
  39710. fallbacks.addFallback(0, "REFLECTION");
  39711. }
  39712. if (defines.SPECULAR) {
  39713. fallbacks.addFallback(0, "SPECULAR");
  39714. }
  39715. if (defines.BUMP) {
  39716. fallbacks.addFallback(0, "BUMP");
  39717. }
  39718. if (defines.PARALLAX) {
  39719. fallbacks.addFallback(1, "PARALLAX");
  39720. }
  39721. if (defines.PARALLAXOCCLUSION) {
  39722. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39723. }
  39724. if (defines.SPECULAROVERALPHA) {
  39725. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39726. }
  39727. if (defines.FOG) {
  39728. fallbacks.addFallback(1, "FOG");
  39729. }
  39730. if (defines.POINTSIZE) {
  39731. fallbacks.addFallback(0, "POINTSIZE");
  39732. }
  39733. if (defines.LOGARITHMICDEPTH) {
  39734. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39735. }
  39736. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39737. if (defines.SPECULARTERM) {
  39738. fallbacks.addFallback(0, "SPECULARTERM");
  39739. }
  39740. if (defines.DIFFUSEFRESNEL) {
  39741. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39742. }
  39743. if (defines.OPACITYFRESNEL) {
  39744. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39745. }
  39746. if (defines.REFLECTIONFRESNEL) {
  39747. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39748. }
  39749. if (defines.EMISSIVEFRESNEL) {
  39750. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39751. }
  39752. if (defines.FRESNEL) {
  39753. fallbacks.addFallback(4, "FRESNEL");
  39754. }
  39755. //Attributes
  39756. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39757. if (defines.NORMAL) {
  39758. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39759. }
  39760. if (defines.UV1) {
  39761. attribs.push(BABYLON.VertexBuffer.UVKind);
  39762. }
  39763. if (defines.UV2) {
  39764. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39765. }
  39766. if (defines.VERTEXCOLOR) {
  39767. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39768. }
  39769. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39770. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39771. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39772. var shaderName = "default";
  39773. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39774. "vFogInfos", "vFogColor", "pointSize",
  39775. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39776. "mBones",
  39777. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39778. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39779. "vReflectionPosition", "vReflectionSize",
  39780. "logarithmicDepthConstant", "vTangentSpaceParams"
  39781. ];
  39782. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39783. var uniformBuffers = ["Material", "Scene"];
  39784. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39785. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39786. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39787. uniformsNames: uniforms,
  39788. uniformBuffersNames: uniformBuffers,
  39789. samplers: samplers,
  39790. defines: defines,
  39791. maxSimultaneousLights: this._maxSimultaneousLights
  39792. });
  39793. if (this.customShaderNameResolve) {
  39794. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39795. }
  39796. var join = defines.toString();
  39797. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39798. attributes: attribs,
  39799. uniformsNames: uniforms,
  39800. uniformBuffersNames: uniformBuffers,
  39801. samplers: samplers,
  39802. defines: join,
  39803. fallbacks: fallbacks,
  39804. onCompiled: this.onCompiled,
  39805. onError: this.onError,
  39806. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39807. }, engine), defines);
  39808. this.buildUniformLayout();
  39809. }
  39810. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39811. return false;
  39812. }
  39813. defines._renderId = scene.getRenderId();
  39814. this._wasPreviouslyReady = true;
  39815. return true;
  39816. };
  39817. StandardMaterial.prototype.buildUniformLayout = function () {
  39818. // Order is important !
  39819. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39820. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39821. this._uniformBuffer.addUniform("opacityParts", 4);
  39822. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39823. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39824. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39825. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39826. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39827. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39828. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39829. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39830. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39831. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39832. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39833. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39834. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39835. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39836. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39837. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39838. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39839. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39840. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39841. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39842. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39843. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39844. this._uniformBuffer.addUniform("specularMatrix", 16);
  39845. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39846. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39847. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39848. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39849. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39850. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39851. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39852. this._uniformBuffer.addUniform("pointSize", 1);
  39853. this._uniformBuffer.create();
  39854. };
  39855. StandardMaterial.prototype.unbind = function () {
  39856. if (this._activeEffect) {
  39857. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39858. this._activeEffect.setTexture("reflection2DSampler", null);
  39859. }
  39860. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39861. this._activeEffect.setTexture("refraction2DSampler", null);
  39862. }
  39863. }
  39864. _super.prototype.unbind.call(this);
  39865. };
  39866. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39867. var scene = this.getScene();
  39868. var defines = subMesh._materialDefines;
  39869. if (!defines) {
  39870. return;
  39871. }
  39872. var effect = subMesh.effect;
  39873. if (!effect) {
  39874. return;
  39875. }
  39876. this._activeEffect = effect;
  39877. // Matrices
  39878. this.bindOnlyWorldMatrix(world);
  39879. // Normal Matrix
  39880. if (defines.OBJECTSPACE_NORMALMAP) {
  39881. world.toNormalMatrix(this._normalMatrix);
  39882. this.bindOnlyNormalMatrix(this._normalMatrix);
  39883. }
  39884. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39885. // Bones
  39886. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39887. if (mustRebind) {
  39888. this._uniformBuffer.bindToEffect(effect, "Material");
  39889. this.bindViewProjection(effect);
  39890. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39891. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39892. // Fresnel
  39893. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39894. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39895. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39896. }
  39897. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39898. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39899. }
  39900. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39901. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39902. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39903. }
  39904. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39905. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39906. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39907. }
  39908. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39909. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39910. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39911. }
  39912. }
  39913. // Textures
  39914. if (scene.texturesEnabled) {
  39915. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39916. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39917. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39918. }
  39919. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39920. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39921. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39922. }
  39923. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39924. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39925. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39926. }
  39927. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39928. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39929. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39930. if (this._reflectionTexture.boundingBoxSize) {
  39931. var cubeTexture = this._reflectionTexture;
  39932. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39933. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39934. }
  39935. }
  39936. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39937. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39938. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39939. }
  39940. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39941. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39942. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39943. }
  39944. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39945. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39946. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39947. }
  39948. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39949. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39950. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39951. if (scene._mirroredCameraPosition) {
  39952. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39953. }
  39954. else {
  39955. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39956. }
  39957. }
  39958. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39959. var depth = 1.0;
  39960. if (!this._refractionTexture.isCube) {
  39961. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39962. if (this._refractionTexture.depth) {
  39963. depth = this._refractionTexture.depth;
  39964. }
  39965. }
  39966. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39967. }
  39968. }
  39969. // Point size
  39970. if (this.pointsCloud) {
  39971. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39972. }
  39973. if (defines.SPECULARTERM) {
  39974. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39975. }
  39976. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39977. // Diffuse
  39978. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39979. }
  39980. // Textures
  39981. if (scene.texturesEnabled) {
  39982. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39983. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39984. }
  39985. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39986. effect.setTexture("ambientSampler", this._ambientTexture);
  39987. }
  39988. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39989. effect.setTexture("opacitySampler", this._opacityTexture);
  39990. }
  39991. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39992. if (this._reflectionTexture.isCube) {
  39993. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39994. }
  39995. else {
  39996. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39997. }
  39998. }
  39999. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40000. effect.setTexture("emissiveSampler", this._emissiveTexture);
  40001. }
  40002. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40003. effect.setTexture("lightmapSampler", this._lightmapTexture);
  40004. }
  40005. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40006. effect.setTexture("specularSampler", this._specularTexture);
  40007. }
  40008. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40009. effect.setTexture("bumpSampler", this._bumpTexture);
  40010. }
  40011. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40012. var depth = 1.0;
  40013. if (this._refractionTexture.isCube) {
  40014. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  40015. }
  40016. else {
  40017. effect.setTexture("refraction2DSampler", this._refractionTexture);
  40018. }
  40019. }
  40020. }
  40021. // Clip plane
  40022. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  40023. // Colors
  40024. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  40025. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  40026. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40027. }
  40028. if (mustRebind || !this.isFrozen) {
  40029. // Lights
  40030. if (scene.lightsEnabled && !this._disableLighting) {
  40031. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  40032. }
  40033. // View
  40034. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  40035. this.bindView(effect);
  40036. }
  40037. // Fog
  40038. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  40039. // Morph targets
  40040. if (defines.NUM_MORPH_INFLUENCERS) {
  40041. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  40042. }
  40043. // Log. depth
  40044. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  40045. // image processing
  40046. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  40047. this._imageProcessingConfiguration.bind(this._activeEffect);
  40048. }
  40049. }
  40050. this._uniformBuffer.update();
  40051. this._afterBind(mesh, this._activeEffect);
  40052. };
  40053. StandardMaterial.prototype.getAnimatables = function () {
  40054. var results = [];
  40055. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  40056. results.push(this._diffuseTexture);
  40057. }
  40058. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40059. results.push(this._ambientTexture);
  40060. }
  40061. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40062. results.push(this._opacityTexture);
  40063. }
  40064. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40065. results.push(this._reflectionTexture);
  40066. }
  40067. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40068. results.push(this._emissiveTexture);
  40069. }
  40070. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  40071. results.push(this._specularTexture);
  40072. }
  40073. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40074. results.push(this._bumpTexture);
  40075. }
  40076. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40077. results.push(this._lightmapTexture);
  40078. }
  40079. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40080. results.push(this._refractionTexture);
  40081. }
  40082. return results;
  40083. };
  40084. StandardMaterial.prototype.getActiveTextures = function () {
  40085. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40086. if (this._diffuseTexture) {
  40087. activeTextures.push(this._diffuseTexture);
  40088. }
  40089. if (this._ambientTexture) {
  40090. activeTextures.push(this._ambientTexture);
  40091. }
  40092. if (this._opacityTexture) {
  40093. activeTextures.push(this._opacityTexture);
  40094. }
  40095. if (this._reflectionTexture) {
  40096. activeTextures.push(this._reflectionTexture);
  40097. }
  40098. if (this._emissiveTexture) {
  40099. activeTextures.push(this._emissiveTexture);
  40100. }
  40101. if (this._specularTexture) {
  40102. activeTextures.push(this._specularTexture);
  40103. }
  40104. if (this._bumpTexture) {
  40105. activeTextures.push(this._bumpTexture);
  40106. }
  40107. if (this._lightmapTexture) {
  40108. activeTextures.push(this._lightmapTexture);
  40109. }
  40110. if (this._refractionTexture) {
  40111. activeTextures.push(this._refractionTexture);
  40112. }
  40113. return activeTextures;
  40114. };
  40115. StandardMaterial.prototype.hasTexture = function (texture) {
  40116. if (_super.prototype.hasTexture.call(this, texture)) {
  40117. return true;
  40118. }
  40119. if (this._diffuseTexture === texture) {
  40120. return true;
  40121. }
  40122. if (this._ambientTexture === texture) {
  40123. return true;
  40124. }
  40125. if (this._opacityTexture === texture) {
  40126. return true;
  40127. }
  40128. if (this._reflectionTexture === texture) {
  40129. return true;
  40130. }
  40131. if (this._emissiveTexture === texture) {
  40132. return true;
  40133. }
  40134. if (this._specularTexture === texture) {
  40135. return true;
  40136. }
  40137. if (this._bumpTexture === texture) {
  40138. return true;
  40139. }
  40140. if (this._lightmapTexture === texture) {
  40141. return true;
  40142. }
  40143. if (this._refractionTexture === texture) {
  40144. return true;
  40145. }
  40146. return false;
  40147. };
  40148. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40149. if (forceDisposeTextures) {
  40150. if (this._diffuseTexture) {
  40151. this._diffuseTexture.dispose();
  40152. }
  40153. if (this._ambientTexture) {
  40154. this._ambientTexture.dispose();
  40155. }
  40156. if (this._opacityTexture) {
  40157. this._opacityTexture.dispose();
  40158. }
  40159. if (this._reflectionTexture) {
  40160. this._reflectionTexture.dispose();
  40161. }
  40162. if (this._emissiveTexture) {
  40163. this._emissiveTexture.dispose();
  40164. }
  40165. if (this._specularTexture) {
  40166. this._specularTexture.dispose();
  40167. }
  40168. if (this._bumpTexture) {
  40169. this._bumpTexture.dispose();
  40170. }
  40171. if (this._lightmapTexture) {
  40172. this._lightmapTexture.dispose();
  40173. }
  40174. if (this._refractionTexture) {
  40175. this._refractionTexture.dispose();
  40176. }
  40177. }
  40178. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40179. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40180. }
  40181. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40182. };
  40183. StandardMaterial.prototype.clone = function (name) {
  40184. var _this = this;
  40185. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40186. result.name = name;
  40187. result.id = name;
  40188. return result;
  40189. };
  40190. StandardMaterial.prototype.serialize = function () {
  40191. return BABYLON.SerializationHelper.Serialize(this);
  40192. };
  40193. // Statics
  40194. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40195. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40196. };
  40197. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40198. get: function () {
  40199. return StandardMaterial._DiffuseTextureEnabled;
  40200. },
  40201. set: function (value) {
  40202. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40203. return;
  40204. }
  40205. StandardMaterial._DiffuseTextureEnabled = value;
  40206. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40207. },
  40208. enumerable: true,
  40209. configurable: true
  40210. });
  40211. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40212. get: function () {
  40213. return StandardMaterial._AmbientTextureEnabled;
  40214. },
  40215. set: function (value) {
  40216. if (StandardMaterial._AmbientTextureEnabled === value) {
  40217. return;
  40218. }
  40219. StandardMaterial._AmbientTextureEnabled = value;
  40220. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40221. },
  40222. enumerable: true,
  40223. configurable: true
  40224. });
  40225. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40226. get: function () {
  40227. return StandardMaterial._OpacityTextureEnabled;
  40228. },
  40229. set: function (value) {
  40230. if (StandardMaterial._OpacityTextureEnabled === value) {
  40231. return;
  40232. }
  40233. StandardMaterial._OpacityTextureEnabled = value;
  40234. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40235. },
  40236. enumerable: true,
  40237. configurable: true
  40238. });
  40239. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40240. get: function () {
  40241. return StandardMaterial._ReflectionTextureEnabled;
  40242. },
  40243. set: function (value) {
  40244. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40245. return;
  40246. }
  40247. StandardMaterial._ReflectionTextureEnabled = value;
  40248. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40249. },
  40250. enumerable: true,
  40251. configurable: true
  40252. });
  40253. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40254. get: function () {
  40255. return StandardMaterial._EmissiveTextureEnabled;
  40256. },
  40257. set: function (value) {
  40258. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40259. return;
  40260. }
  40261. StandardMaterial._EmissiveTextureEnabled = value;
  40262. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40263. },
  40264. enumerable: true,
  40265. configurable: true
  40266. });
  40267. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40268. get: function () {
  40269. return StandardMaterial._SpecularTextureEnabled;
  40270. },
  40271. set: function (value) {
  40272. if (StandardMaterial._SpecularTextureEnabled === value) {
  40273. return;
  40274. }
  40275. StandardMaterial._SpecularTextureEnabled = value;
  40276. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40277. },
  40278. enumerable: true,
  40279. configurable: true
  40280. });
  40281. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40282. get: function () {
  40283. return StandardMaterial._BumpTextureEnabled;
  40284. },
  40285. set: function (value) {
  40286. if (StandardMaterial._BumpTextureEnabled === value) {
  40287. return;
  40288. }
  40289. StandardMaterial._BumpTextureEnabled = value;
  40290. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40291. },
  40292. enumerable: true,
  40293. configurable: true
  40294. });
  40295. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40296. get: function () {
  40297. return StandardMaterial._LightmapTextureEnabled;
  40298. },
  40299. set: function (value) {
  40300. if (StandardMaterial._LightmapTextureEnabled === value) {
  40301. return;
  40302. }
  40303. StandardMaterial._LightmapTextureEnabled = value;
  40304. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40305. },
  40306. enumerable: true,
  40307. configurable: true
  40308. });
  40309. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40310. get: function () {
  40311. return StandardMaterial._RefractionTextureEnabled;
  40312. },
  40313. set: function (value) {
  40314. if (StandardMaterial._RefractionTextureEnabled === value) {
  40315. return;
  40316. }
  40317. StandardMaterial._RefractionTextureEnabled = value;
  40318. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40319. },
  40320. enumerable: true,
  40321. configurable: true
  40322. });
  40323. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40324. get: function () {
  40325. return StandardMaterial._ColorGradingTextureEnabled;
  40326. },
  40327. set: function (value) {
  40328. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40329. return;
  40330. }
  40331. StandardMaterial._ColorGradingTextureEnabled = value;
  40332. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40333. },
  40334. enumerable: true,
  40335. configurable: true
  40336. });
  40337. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40338. get: function () {
  40339. return StandardMaterial._FresnelEnabled;
  40340. },
  40341. set: function (value) {
  40342. if (StandardMaterial._FresnelEnabled === value) {
  40343. return;
  40344. }
  40345. StandardMaterial._FresnelEnabled = value;
  40346. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40347. },
  40348. enumerable: true,
  40349. configurable: true
  40350. });
  40351. // Flags used to enable or disable a type of texture for all Standard Materials
  40352. StandardMaterial._DiffuseTextureEnabled = true;
  40353. StandardMaterial._AmbientTextureEnabled = true;
  40354. StandardMaterial._OpacityTextureEnabled = true;
  40355. StandardMaterial._ReflectionTextureEnabled = true;
  40356. StandardMaterial._EmissiveTextureEnabled = true;
  40357. StandardMaterial._SpecularTextureEnabled = true;
  40358. StandardMaterial._BumpTextureEnabled = true;
  40359. StandardMaterial._LightmapTextureEnabled = true;
  40360. StandardMaterial._RefractionTextureEnabled = true;
  40361. StandardMaterial._ColorGradingTextureEnabled = true;
  40362. StandardMaterial._FresnelEnabled = true;
  40363. __decorate([
  40364. BABYLON.serializeAsTexture("diffuseTexture")
  40365. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40366. __decorate([
  40367. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40368. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40369. __decorate([
  40370. BABYLON.serializeAsTexture("ambientTexture")
  40371. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40372. __decorate([
  40373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40374. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40375. __decorate([
  40376. BABYLON.serializeAsTexture("opacityTexture")
  40377. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40378. __decorate([
  40379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40380. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40381. __decorate([
  40382. BABYLON.serializeAsTexture("reflectionTexture")
  40383. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40384. __decorate([
  40385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40386. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40387. __decorate([
  40388. BABYLON.serializeAsTexture("emissiveTexture")
  40389. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40390. __decorate([
  40391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40392. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40393. __decorate([
  40394. BABYLON.serializeAsTexture("specularTexture")
  40395. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40396. __decorate([
  40397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40398. ], StandardMaterial.prototype, "specularTexture", void 0);
  40399. __decorate([
  40400. BABYLON.serializeAsTexture("bumpTexture")
  40401. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40402. __decorate([
  40403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40404. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40405. __decorate([
  40406. BABYLON.serializeAsTexture("lightmapTexture")
  40407. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40408. __decorate([
  40409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40410. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40411. __decorate([
  40412. BABYLON.serializeAsTexture("refractionTexture")
  40413. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40414. __decorate([
  40415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40416. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40417. __decorate([
  40418. BABYLON.serializeAsColor3("ambient")
  40419. ], StandardMaterial.prototype, "ambientColor", void 0);
  40420. __decorate([
  40421. BABYLON.serializeAsColor3("diffuse")
  40422. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40423. __decorate([
  40424. BABYLON.serializeAsColor3("specular")
  40425. ], StandardMaterial.prototype, "specularColor", void 0);
  40426. __decorate([
  40427. BABYLON.serializeAsColor3("emissive")
  40428. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40429. __decorate([
  40430. BABYLON.serialize()
  40431. ], StandardMaterial.prototype, "specularPower", void 0);
  40432. __decorate([
  40433. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40434. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40435. __decorate([
  40436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40437. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40438. __decorate([
  40439. BABYLON.serialize("useEmissiveAsIllumination")
  40440. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40441. __decorate([
  40442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40443. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40444. __decorate([
  40445. BABYLON.serialize("linkEmissiveWithDiffuse")
  40446. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40447. __decorate([
  40448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40449. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40450. __decorate([
  40451. BABYLON.serialize("useSpecularOverAlpha")
  40452. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40453. __decorate([
  40454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40455. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40456. __decorate([
  40457. BABYLON.serialize("useReflectionOverAlpha")
  40458. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40459. __decorate([
  40460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40461. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40462. __decorate([
  40463. BABYLON.serialize("disableLighting")
  40464. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40465. __decorate([
  40466. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40467. ], StandardMaterial.prototype, "disableLighting", void 0);
  40468. __decorate([
  40469. BABYLON.serialize("useObjectSpaceNormalMap")
  40470. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40471. __decorate([
  40472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40473. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40474. __decorate([
  40475. BABYLON.serialize("useParallax")
  40476. ], StandardMaterial.prototype, "_useParallax", void 0);
  40477. __decorate([
  40478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40479. ], StandardMaterial.prototype, "useParallax", void 0);
  40480. __decorate([
  40481. BABYLON.serialize("useParallaxOcclusion")
  40482. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40483. __decorate([
  40484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40485. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40486. __decorate([
  40487. BABYLON.serialize()
  40488. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40489. __decorate([
  40490. BABYLON.serialize("roughness")
  40491. ], StandardMaterial.prototype, "_roughness", void 0);
  40492. __decorate([
  40493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40494. ], StandardMaterial.prototype, "roughness", void 0);
  40495. __decorate([
  40496. BABYLON.serialize()
  40497. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40498. __decorate([
  40499. BABYLON.serialize()
  40500. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40501. __decorate([
  40502. BABYLON.serialize("useLightmapAsShadowmap")
  40503. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40504. __decorate([
  40505. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40506. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40507. __decorate([
  40508. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40509. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40510. __decorate([
  40511. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40512. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40513. __decorate([
  40514. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40515. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40516. __decorate([
  40517. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40518. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40519. __decorate([
  40520. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40521. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40522. __decorate([
  40523. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40524. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40525. __decorate([
  40526. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40527. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40528. __decorate([
  40529. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40530. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40531. __decorate([
  40532. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40533. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40534. __decorate([
  40535. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40536. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40537. __decorate([
  40538. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40539. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40540. __decorate([
  40541. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40542. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40543. __decorate([
  40544. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40545. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40546. __decorate([
  40547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40548. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40549. __decorate([
  40550. BABYLON.serialize("maxSimultaneousLights")
  40551. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40552. __decorate([
  40553. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40554. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40555. __decorate([
  40556. BABYLON.serialize("invertNormalMapX")
  40557. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40558. __decorate([
  40559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40560. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40561. __decorate([
  40562. BABYLON.serialize("invertNormalMapY")
  40563. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40564. __decorate([
  40565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40566. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40567. __decorate([
  40568. BABYLON.serialize("twoSidedLighting")
  40569. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40570. __decorate([
  40571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40572. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40573. __decorate([
  40574. BABYLON.serialize()
  40575. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40576. return StandardMaterial;
  40577. }(BABYLON.PushMaterial));
  40578. BABYLON.StandardMaterial = StandardMaterial;
  40579. })(BABYLON || (BABYLON = {}));
  40580. //# sourceMappingURL=babylon.standardMaterial.js.map
  40581. var BABYLON;
  40582. (function (BABYLON) {
  40583. /**
  40584. * Manages the defines for the PBR Material.
  40585. */
  40586. var PBRMaterialDefines = /** @class */ (function (_super) {
  40587. __extends(PBRMaterialDefines, _super);
  40588. /**
  40589. * Initializes the PBR Material defines.
  40590. */
  40591. function PBRMaterialDefines() {
  40592. var _this = _super.call(this) || this;
  40593. _this.PBR = true;
  40594. _this.MAINUV1 = false;
  40595. _this.MAINUV2 = false;
  40596. _this.UV1 = false;
  40597. _this.UV2 = false;
  40598. _this.ALBEDO = false;
  40599. _this.ALBEDODIRECTUV = 0;
  40600. _this.VERTEXCOLOR = false;
  40601. _this.AMBIENT = false;
  40602. _this.AMBIENTDIRECTUV = 0;
  40603. _this.AMBIENTINGRAYSCALE = false;
  40604. _this.OPACITY = false;
  40605. _this.VERTEXALPHA = false;
  40606. _this.OPACITYDIRECTUV = 0;
  40607. _this.OPACITYRGB = false;
  40608. _this.ALPHATEST = false;
  40609. _this.DEPTHPREPASS = false;
  40610. _this.ALPHABLEND = false;
  40611. _this.ALPHAFROMALBEDO = false;
  40612. _this.ALPHATESTVALUE = 0.5;
  40613. _this.SPECULAROVERALPHA = false;
  40614. _this.RADIANCEOVERALPHA = false;
  40615. _this.ALPHAFRESNEL = false;
  40616. _this.LINEARALPHAFRESNEL = false;
  40617. _this.PREMULTIPLYALPHA = false;
  40618. _this.EMISSIVE = false;
  40619. _this.EMISSIVEDIRECTUV = 0;
  40620. _this.REFLECTIVITY = false;
  40621. _this.REFLECTIVITYDIRECTUV = 0;
  40622. _this.SPECULARTERM = false;
  40623. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40624. _this.MICROSURFACEAUTOMATIC = false;
  40625. _this.LODBASEDMICROSFURACE = false;
  40626. _this.MICROSURFACEMAP = false;
  40627. _this.MICROSURFACEMAPDIRECTUV = 0;
  40628. _this.METALLICWORKFLOW = false;
  40629. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40630. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40631. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40632. _this.AOSTOREINMETALMAPRED = false;
  40633. _this.ENVIRONMENTBRDF = false;
  40634. _this.NORMAL = false;
  40635. _this.TANGENT = false;
  40636. _this.BUMP = false;
  40637. _this.BUMPDIRECTUV = 0;
  40638. _this.OBJECTSPACE_NORMALMAP = false;
  40639. _this.PARALLAX = false;
  40640. _this.PARALLAXOCCLUSION = false;
  40641. _this.NORMALXYSCALE = true;
  40642. _this.LIGHTMAP = false;
  40643. _this.LIGHTMAPDIRECTUV = 0;
  40644. _this.USELIGHTMAPASSHADOWMAP = false;
  40645. _this.GAMMALIGHTMAP = false;
  40646. _this.REFLECTION = false;
  40647. _this.REFLECTIONMAP_3D = false;
  40648. _this.REFLECTIONMAP_SPHERICAL = false;
  40649. _this.REFLECTIONMAP_PLANAR = false;
  40650. _this.REFLECTIONMAP_CUBIC = false;
  40651. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40652. _this.REFLECTIONMAP_PROJECTION = false;
  40653. _this.REFLECTIONMAP_SKYBOX = false;
  40654. _this.REFLECTIONMAP_EXPLICIT = false;
  40655. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40656. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40657. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40658. _this.INVERTCUBICMAP = false;
  40659. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40660. _this.USESPHERICALINVERTEX = false;
  40661. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40662. _this.LODINREFLECTIONALPHA = false;
  40663. _this.GAMMAREFLECTION = false;
  40664. _this.RADIANCEOCCLUSION = false;
  40665. _this.HORIZONOCCLUSION = false;
  40666. _this.REFRACTION = false;
  40667. _this.REFRACTIONMAP_3D = false;
  40668. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40669. _this.LODINREFRACTIONALPHA = false;
  40670. _this.GAMMAREFRACTION = false;
  40671. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40672. _this.INSTANCES = false;
  40673. _this.NUM_BONE_INFLUENCERS = 0;
  40674. _this.BonesPerMesh = 0;
  40675. _this.NONUNIFORMSCALING = false;
  40676. _this.MORPHTARGETS = false;
  40677. _this.MORPHTARGETS_NORMAL = false;
  40678. _this.MORPHTARGETS_TANGENT = false;
  40679. _this.NUM_MORPH_INFLUENCERS = 0;
  40680. _this.IMAGEPROCESSING = false;
  40681. _this.VIGNETTE = false;
  40682. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40683. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40684. _this.TONEMAPPING = false;
  40685. _this.CONTRAST = false;
  40686. _this.COLORCURVES = false;
  40687. _this.COLORGRADING = false;
  40688. _this.COLORGRADING3D = false;
  40689. _this.SAMPLER3DGREENDEPTH = false;
  40690. _this.SAMPLER3DBGRMAP = false;
  40691. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40692. _this.EXPOSURE = false;
  40693. _this.GRAIN = false;
  40694. _this.USEPHYSICALLIGHTFALLOFF = false;
  40695. _this.TWOSIDEDLIGHTING = false;
  40696. _this.SHADOWFLOAT = false;
  40697. _this.CLIPPLANE = false;
  40698. _this.POINTSIZE = false;
  40699. _this.FOG = false;
  40700. _this.LOGARITHMICDEPTH = false;
  40701. _this.FORCENORMALFORWARD = false;
  40702. _this.rebuild();
  40703. return _this;
  40704. }
  40705. /**
  40706. * Resets the PBR Material defines.
  40707. */
  40708. PBRMaterialDefines.prototype.reset = function () {
  40709. _super.prototype.reset.call(this);
  40710. this.ALPHATESTVALUE = 0.5;
  40711. this.PBR = true;
  40712. };
  40713. return PBRMaterialDefines;
  40714. }(BABYLON.MaterialDefines));
  40715. /**
  40716. * The Physically based material base class of BJS.
  40717. *
  40718. * This offers the main features of a standard PBR material.
  40719. * For more information, please refer to the documentation :
  40720. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40721. */
  40722. var PBRBaseMaterial = /** @class */ (function (_super) {
  40723. __extends(PBRBaseMaterial, _super);
  40724. /**
  40725. * Instantiates a new PBRMaterial instance.
  40726. *
  40727. * @param name The material name
  40728. * @param scene The scene the material will be use in.
  40729. */
  40730. function PBRBaseMaterial(name, scene) {
  40731. var _this = _super.call(this, name, scene) || this;
  40732. /**
  40733. * Intensity of the direct lights e.g. the four lights available in your scene.
  40734. * This impacts both the direct diffuse and specular highlights.
  40735. */
  40736. _this._directIntensity = 1.0;
  40737. /**
  40738. * Intensity of the emissive part of the material.
  40739. * This helps controlling the emissive effect without modifying the emissive color.
  40740. */
  40741. _this._emissiveIntensity = 1.0;
  40742. /**
  40743. * Intensity of the environment e.g. how much the environment will light the object
  40744. * either through harmonics for rough material or through the refelction for shiny ones.
  40745. */
  40746. _this._environmentIntensity = 1.0;
  40747. /**
  40748. * This is a special control allowing the reduction of the specular highlights coming from the
  40749. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40750. */
  40751. _this._specularIntensity = 1.0;
  40752. /**
  40753. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40754. */
  40755. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40756. /**
  40757. * Debug Control allowing disabling the bump map on this material.
  40758. */
  40759. _this._disableBumpMap = false;
  40760. /**
  40761. * AKA Occlusion Texture Intensity in other nomenclature.
  40762. */
  40763. _this._ambientTextureStrength = 1.0;
  40764. /**
  40765. * The color of a material in ambient lighting.
  40766. */
  40767. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40768. /**
  40769. * AKA Diffuse Color in other nomenclature.
  40770. */
  40771. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40772. /**
  40773. * AKA Specular Color in other nomenclature.
  40774. */
  40775. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40776. /**
  40777. * The color applied when light is reflected from a material.
  40778. */
  40779. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40780. /**
  40781. * The color applied when light is emitted from a material.
  40782. */
  40783. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40784. /**
  40785. * AKA Glossiness in other nomenclature.
  40786. */
  40787. _this._microSurface = 0.9;
  40788. /**
  40789. * source material index of refraction (IOR)' / 'destination material IOR.
  40790. */
  40791. _this._indexOfRefraction = 0.66;
  40792. /**
  40793. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40794. */
  40795. _this._invertRefractionY = false;
  40796. /**
  40797. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40798. * Materials half opaque for instance using refraction could benefit from this control.
  40799. */
  40800. _this._linkRefractionWithTransparency = false;
  40801. /**
  40802. * Specifies that the material will use the light map as a show map.
  40803. */
  40804. _this._useLightmapAsShadowmap = false;
  40805. /**
  40806. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40807. * makes the reflect vector face the model (under horizon).
  40808. */
  40809. _this._useHorizonOcclusion = true;
  40810. /**
  40811. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40812. * too much the area relying on ambient texture to define their ambient occlusion.
  40813. */
  40814. _this._useRadianceOcclusion = true;
  40815. /**
  40816. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40817. */
  40818. _this._useAlphaFromAlbedoTexture = false;
  40819. /**
  40820. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40821. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40822. */
  40823. _this._useSpecularOverAlpha = true;
  40824. /**
  40825. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40826. */
  40827. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40828. /**
  40829. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40830. */
  40831. _this._useRoughnessFromMetallicTextureAlpha = true;
  40832. /**
  40833. * Specifies if the metallic texture contains the roughness information in its green channel.
  40834. */
  40835. _this._useRoughnessFromMetallicTextureGreen = false;
  40836. /**
  40837. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40838. */
  40839. _this._useMetallnessFromMetallicTextureBlue = false;
  40840. /**
  40841. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40842. */
  40843. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40844. /**
  40845. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40846. */
  40847. _this._useAmbientInGrayScale = false;
  40848. /**
  40849. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40850. * The material will try to infer what glossiness each pixel should be.
  40851. */
  40852. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40853. /**
  40854. * BJS is using an harcoded light falloff based on a manually sets up range.
  40855. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40856. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40857. */
  40858. _this._usePhysicalLightFalloff = true;
  40859. /**
  40860. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40861. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40862. */
  40863. _this._useRadianceOverAlpha = true;
  40864. /**
  40865. * Allows using an object space normal map (instead of tangent space).
  40866. */
  40867. _this._useObjectSpaceNormalMap = false;
  40868. /**
  40869. * Allows using the bump map in parallax mode.
  40870. */
  40871. _this._useParallax = false;
  40872. /**
  40873. * Allows using the bump map in parallax occlusion mode.
  40874. */
  40875. _this._useParallaxOcclusion = false;
  40876. /**
  40877. * Controls the scale bias of the parallax mode.
  40878. */
  40879. _this._parallaxScaleBias = 0.05;
  40880. /**
  40881. * If sets to true, disables all the lights affecting the material.
  40882. */
  40883. _this._disableLighting = false;
  40884. /**
  40885. * Number of Simultaneous lights allowed on the material.
  40886. */
  40887. _this._maxSimultaneousLights = 4;
  40888. /**
  40889. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40890. */
  40891. _this._invertNormalMapX = false;
  40892. /**
  40893. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40894. */
  40895. _this._invertNormalMapY = false;
  40896. /**
  40897. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40898. */
  40899. _this._twoSidedLighting = false;
  40900. /**
  40901. * Defines the alpha limits in alpha test mode.
  40902. */
  40903. _this._alphaCutOff = 0.4;
  40904. /**
  40905. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40906. */
  40907. _this._forceAlphaTest = false;
  40908. /**
  40909. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40910. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40911. */
  40912. _this._useAlphaFresnel = false;
  40913. /**
  40914. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40915. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40916. */
  40917. _this._useLinearAlphaFresnel = false;
  40918. /**
  40919. * The transparency mode of the material.
  40920. */
  40921. _this._transparencyMode = null;
  40922. /**
  40923. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40924. * from cos thetav and roughness:
  40925. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40926. */
  40927. _this._environmentBRDFTexture = null;
  40928. /**
  40929. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40930. */
  40931. _this._forceIrradianceInFragment = false;
  40932. /**
  40933. * Force normal to face away from face.
  40934. */
  40935. _this._forceNormalForward = false;
  40936. /**
  40937. * Stores the available render targets.
  40938. */
  40939. _this._renderTargets = new BABYLON.SmartArray(16);
  40940. /**
  40941. * Sets the global ambient color for the material used in lighting calculations.
  40942. */
  40943. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40944. // Setup the default processing configuration to the scene.
  40945. _this._attachImageProcessingConfiguration(null);
  40946. _this.getRenderTargetTextures = function () {
  40947. _this._renderTargets.reset();
  40948. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40949. _this._renderTargets.push(_this._reflectionTexture);
  40950. }
  40951. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40952. _this._renderTargets.push(_this._refractionTexture);
  40953. }
  40954. return _this._renderTargets;
  40955. };
  40956. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40957. return _this;
  40958. }
  40959. /**
  40960. * Attaches a new image processing configuration to the PBR Material.
  40961. * @param configuration
  40962. */
  40963. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40964. var _this = this;
  40965. if (configuration === this._imageProcessingConfiguration) {
  40966. return;
  40967. }
  40968. // Detaches observer.
  40969. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40970. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40971. }
  40972. // Pick the scene configuration if needed.
  40973. if (!configuration) {
  40974. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40975. }
  40976. else {
  40977. this._imageProcessingConfiguration = configuration;
  40978. }
  40979. // Attaches observer.
  40980. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40981. _this._markAllSubMeshesAsImageProcessingDirty();
  40982. });
  40983. };
  40984. /**
  40985. * Gets the name of the material class.
  40986. */
  40987. PBRBaseMaterial.prototype.getClassName = function () {
  40988. return "PBRBaseMaterial";
  40989. };
  40990. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40991. /**
  40992. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40993. */
  40994. get: function () {
  40995. return this._useLogarithmicDepth;
  40996. },
  40997. /**
  40998. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40999. */
  41000. set: function (value) {
  41001. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41002. },
  41003. enumerable: true,
  41004. configurable: true
  41005. });
  41006. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  41007. /**
  41008. * Gets the current transparency mode.
  41009. */
  41010. get: function () {
  41011. return this._transparencyMode;
  41012. },
  41013. /**
  41014. * Sets the transparency mode of the material.
  41015. */
  41016. set: function (value) {
  41017. if (this._transparencyMode === value) {
  41018. return;
  41019. }
  41020. this._transparencyMode = value;
  41021. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  41022. this._markAllSubMeshesAsTexturesAndMiscDirty();
  41023. },
  41024. enumerable: true,
  41025. configurable: true
  41026. });
  41027. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  41028. /**
  41029. * Returns true if alpha blending should be disabled.
  41030. */
  41031. get: function () {
  41032. return (this._linkRefractionWithTransparency ||
  41033. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  41034. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41035. },
  41036. enumerable: true,
  41037. configurable: true
  41038. });
  41039. /**
  41040. * Specifies whether or not this material should be rendered in alpha blend mode.
  41041. */
  41042. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  41043. if (this._disableAlphaBlending) {
  41044. return false;
  41045. }
  41046. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  41047. };
  41048. /**
  41049. * Specifies if the mesh will require alpha blending.
  41050. * @param mesh - BJS mesh.
  41051. */
  41052. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  41053. if (this._disableAlphaBlending) {
  41054. return false;
  41055. }
  41056. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  41057. };
  41058. /**
  41059. * Specifies whether or not this material should be rendered in alpha test mode.
  41060. */
  41061. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  41062. if (this._forceAlphaTest) {
  41063. return true;
  41064. }
  41065. if (this._linkRefractionWithTransparency) {
  41066. return false;
  41067. }
  41068. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41069. };
  41070. /**
  41071. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  41072. */
  41073. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  41074. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  41075. };
  41076. /**
  41077. * Gets the texture used for the alpha test.
  41078. */
  41079. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  41080. return this._albedoTexture;
  41081. };
  41082. /**
  41083. * Specifies that the submesh is ready to be used.
  41084. * @param mesh - BJS mesh.
  41085. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  41086. * @param useInstances - Specifies that instances should be used.
  41087. * @returns - boolean indicating that the submesh is ready or not.
  41088. */
  41089. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41090. if (subMesh.effect && this.isFrozen) {
  41091. if (this._wasPreviouslyReady) {
  41092. return true;
  41093. }
  41094. }
  41095. if (!subMesh._materialDefines) {
  41096. subMesh._materialDefines = new PBRMaterialDefines();
  41097. }
  41098. var defines = subMesh._materialDefines;
  41099. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41100. if (defines._renderId === this.getScene().getRenderId()) {
  41101. return true;
  41102. }
  41103. }
  41104. var scene = this.getScene();
  41105. var engine = scene.getEngine();
  41106. if (defines._areTexturesDirty) {
  41107. if (scene.texturesEnabled) {
  41108. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41109. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  41110. return false;
  41111. }
  41112. }
  41113. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41114. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41115. return false;
  41116. }
  41117. }
  41118. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41119. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41120. return false;
  41121. }
  41122. }
  41123. var reflectionTexture = this._getReflectionTexture();
  41124. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41125. if (!reflectionTexture.isReadyOrNotBlocking()) {
  41126. return false;
  41127. }
  41128. }
  41129. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41130. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41131. return false;
  41132. }
  41133. }
  41134. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41135. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41136. return false;
  41137. }
  41138. }
  41139. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41140. if (this._metallicTexture) {
  41141. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  41142. return false;
  41143. }
  41144. }
  41145. else if (this._reflectivityTexture) {
  41146. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  41147. return false;
  41148. }
  41149. }
  41150. if (this._microSurfaceTexture) {
  41151. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  41152. return false;
  41153. }
  41154. }
  41155. }
  41156. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41157. // Bump texture cannot be not blocking.
  41158. if (!this._bumpTexture.isReady()) {
  41159. return false;
  41160. }
  41161. }
  41162. var refractionTexture = this._getRefractionTexture();
  41163. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41164. if (!refractionTexture.isReadyOrNotBlocking()) {
  41165. return false;
  41166. }
  41167. }
  41168. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41169. // This is blocking.
  41170. if (!this._environmentBRDFTexture.isReady()) {
  41171. return false;
  41172. }
  41173. }
  41174. }
  41175. }
  41176. if (defines._areImageProcessingDirty) {
  41177. if (!this._imageProcessingConfiguration.isReady()) {
  41178. return false;
  41179. }
  41180. }
  41181. if (!engine.getCaps().standardDerivatives) {
  41182. var bufferMesh = null;
  41183. if (mesh.getClassName() === "InstancedMesh") {
  41184. bufferMesh = mesh.sourceMesh;
  41185. }
  41186. else if (mesh.getClassName() === "Mesh") {
  41187. bufferMesh = mesh;
  41188. }
  41189. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41190. bufferMesh.createNormals(true);
  41191. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  41192. }
  41193. }
  41194. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41195. if (effect) {
  41196. scene.resetCachedMaterial();
  41197. subMesh.setEffect(effect, defines);
  41198. this.buildUniformLayout();
  41199. }
  41200. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41201. return false;
  41202. }
  41203. defines._renderId = scene.getRenderId();
  41204. this._wasPreviouslyReady = true;
  41205. return true;
  41206. };
  41207. /**
  41208. * Specifies if the material uses metallic roughness workflow.
  41209. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41210. */
  41211. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41212. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41213. return true;
  41214. }
  41215. return false;
  41216. };
  41217. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41218. if (onCompiled === void 0) { onCompiled = null; }
  41219. if (onError === void 0) { onError = null; }
  41220. if (useInstances === void 0) { useInstances = null; }
  41221. if (useClipPlane === void 0) { useClipPlane = null; }
  41222. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41223. if (!defines.isDirty) {
  41224. return null;
  41225. }
  41226. defines.markAsProcessed();
  41227. var scene = this.getScene();
  41228. var engine = scene.getEngine();
  41229. // Fallbacks
  41230. var fallbacks = new BABYLON.EffectFallbacks();
  41231. var fallbackRank = 0;
  41232. if (defines.USESPHERICALINVERTEX) {
  41233. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41234. }
  41235. if (defines.FOG) {
  41236. fallbacks.addFallback(fallbackRank, "FOG");
  41237. }
  41238. if (defines.POINTSIZE) {
  41239. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41240. }
  41241. if (defines.LOGARITHMICDEPTH) {
  41242. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41243. }
  41244. if (defines.PARALLAX) {
  41245. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41246. }
  41247. if (defines.PARALLAXOCCLUSION) {
  41248. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41249. }
  41250. if (defines.ENVIRONMENTBRDF) {
  41251. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41252. }
  41253. if (defines.TANGENT) {
  41254. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41255. }
  41256. if (defines.BUMP) {
  41257. fallbacks.addFallback(fallbackRank++, "BUMP");
  41258. }
  41259. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41260. if (defines.SPECULARTERM) {
  41261. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41262. }
  41263. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41264. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41265. }
  41266. if (defines.LIGHTMAP) {
  41267. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41268. }
  41269. if (defines.NORMAL) {
  41270. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41271. }
  41272. if (defines.AMBIENT) {
  41273. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41274. }
  41275. if (defines.EMISSIVE) {
  41276. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41277. }
  41278. if (defines.VERTEXCOLOR) {
  41279. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41280. }
  41281. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41282. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41283. }
  41284. if (defines.MORPHTARGETS) {
  41285. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41286. }
  41287. //Attributes
  41288. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41289. if (defines.NORMAL) {
  41290. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41291. }
  41292. if (defines.TANGENT) {
  41293. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41294. }
  41295. if (defines.UV1) {
  41296. attribs.push(BABYLON.VertexBuffer.UVKind);
  41297. }
  41298. if (defines.UV2) {
  41299. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41300. }
  41301. if (defines.VERTEXCOLOR) {
  41302. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41303. }
  41304. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41305. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41306. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41307. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41308. "vFogInfos", "vFogColor", "pointSize",
  41309. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41310. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41311. "mBones",
  41312. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41313. "vLightingIntensity",
  41314. "logarithmicDepthConstant",
  41315. "vSphericalX", "vSphericalY", "vSphericalZ",
  41316. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41317. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41318. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41319. "vTangentSpaceParams"
  41320. ];
  41321. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41322. "bumpSampler", "lightmapSampler", "opacitySampler",
  41323. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41324. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41325. "microSurfaceSampler", "environmentBrdfSampler"];
  41326. var uniformBuffers = ["Material", "Scene"];
  41327. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41328. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41329. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41330. uniformsNames: uniforms,
  41331. uniformBuffersNames: uniformBuffers,
  41332. samplers: samplers,
  41333. defines: defines,
  41334. maxSimultaneousLights: this._maxSimultaneousLights
  41335. });
  41336. var join = defines.toString();
  41337. return engine.createEffect("pbr", {
  41338. attributes: attribs,
  41339. uniformsNames: uniforms,
  41340. uniformBuffersNames: uniformBuffers,
  41341. samplers: samplers,
  41342. defines: join,
  41343. fallbacks: fallbacks,
  41344. onCompiled: onCompiled,
  41345. onError: onError,
  41346. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41347. }, engine);
  41348. };
  41349. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41350. if (useInstances === void 0) { useInstances = null; }
  41351. if (useClipPlane === void 0) { useClipPlane = null; }
  41352. var scene = this.getScene();
  41353. var engine = scene.getEngine();
  41354. // Lights
  41355. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41356. defines._needNormals = true;
  41357. // Textures
  41358. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41359. if (defines._areTexturesDirty) {
  41360. defines._needUVs = false;
  41361. if (scene.texturesEnabled) {
  41362. if (scene.getEngine().getCaps().textureLOD) {
  41363. defines.LODBASEDMICROSFURACE = true;
  41364. }
  41365. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41366. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41367. }
  41368. else {
  41369. defines.ALBEDO = false;
  41370. }
  41371. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41372. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41373. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41374. }
  41375. else {
  41376. defines.AMBIENT = false;
  41377. }
  41378. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41379. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41380. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41381. }
  41382. else {
  41383. defines.OPACITY = false;
  41384. }
  41385. var reflectionTexture = this._getReflectionTexture();
  41386. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41387. defines.REFLECTION = true;
  41388. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41389. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41390. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41391. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41392. defines.INVERTCUBICMAP = true;
  41393. }
  41394. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41395. switch (reflectionTexture.coordinatesMode) {
  41396. case BABYLON.Texture.CUBIC_MODE:
  41397. case BABYLON.Texture.INVCUBIC_MODE:
  41398. defines.REFLECTIONMAP_CUBIC = true;
  41399. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41400. break;
  41401. case BABYLON.Texture.EXPLICIT_MODE:
  41402. defines.REFLECTIONMAP_EXPLICIT = true;
  41403. break;
  41404. case BABYLON.Texture.PLANAR_MODE:
  41405. defines.REFLECTIONMAP_PLANAR = true;
  41406. break;
  41407. case BABYLON.Texture.PROJECTION_MODE:
  41408. defines.REFLECTIONMAP_PROJECTION = true;
  41409. break;
  41410. case BABYLON.Texture.SKYBOX_MODE:
  41411. defines.REFLECTIONMAP_SKYBOX = true;
  41412. break;
  41413. case BABYLON.Texture.SPHERICAL_MODE:
  41414. defines.REFLECTIONMAP_SPHERICAL = true;
  41415. break;
  41416. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41417. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41418. break;
  41419. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41420. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41421. break;
  41422. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41423. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41424. break;
  41425. }
  41426. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41427. if (reflectionTexture.sphericalPolynomial) {
  41428. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41429. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41430. defines.USESPHERICALINVERTEX = false;
  41431. }
  41432. else {
  41433. defines.USESPHERICALINVERTEX = true;
  41434. }
  41435. }
  41436. }
  41437. }
  41438. else {
  41439. defines.REFLECTION = false;
  41440. defines.REFLECTIONMAP_3D = false;
  41441. defines.REFLECTIONMAP_SPHERICAL = false;
  41442. defines.REFLECTIONMAP_PLANAR = false;
  41443. defines.REFLECTIONMAP_CUBIC = false;
  41444. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41445. defines.REFLECTIONMAP_PROJECTION = false;
  41446. defines.REFLECTIONMAP_SKYBOX = false;
  41447. defines.REFLECTIONMAP_EXPLICIT = false;
  41448. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41449. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41450. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41451. defines.INVERTCUBICMAP = false;
  41452. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41453. defines.USESPHERICALINVERTEX = false;
  41454. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41455. defines.LODINREFLECTIONALPHA = false;
  41456. defines.GAMMAREFLECTION = false;
  41457. }
  41458. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41459. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41460. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41461. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  41462. }
  41463. else {
  41464. defines.LIGHTMAP = false;
  41465. }
  41466. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41467. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41468. }
  41469. else {
  41470. defines.EMISSIVE = false;
  41471. }
  41472. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41473. if (this._metallicTexture) {
  41474. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41475. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41476. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41477. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41478. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41479. }
  41480. else if (this._reflectivityTexture) {
  41481. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41482. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41483. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41484. }
  41485. else {
  41486. defines.REFLECTIVITY = false;
  41487. }
  41488. if (this._microSurfaceTexture) {
  41489. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41490. }
  41491. else {
  41492. defines.MICROSURFACEMAP = false;
  41493. }
  41494. }
  41495. else {
  41496. defines.REFLECTIVITY = false;
  41497. defines.MICROSURFACEMAP = false;
  41498. }
  41499. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41500. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41501. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41502. defines.PARALLAX = true;
  41503. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41504. }
  41505. else {
  41506. defines.PARALLAX = false;
  41507. }
  41508. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41509. }
  41510. else {
  41511. defines.BUMP = false;
  41512. }
  41513. var refractionTexture = this._getRefractionTexture();
  41514. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41515. defines.REFRACTION = true;
  41516. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41517. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41518. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41519. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41520. if (this._linkRefractionWithTransparency) {
  41521. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41522. }
  41523. }
  41524. else {
  41525. defines.REFRACTION = false;
  41526. }
  41527. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41528. defines.ENVIRONMENTBRDF = true;
  41529. }
  41530. else {
  41531. defines.ENVIRONMENTBRDF = false;
  41532. }
  41533. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41534. defines.ALPHAFROMALBEDO = true;
  41535. }
  41536. else {
  41537. defines.ALPHAFROMALBEDO = false;
  41538. }
  41539. }
  41540. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41541. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41542. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41543. if (!this.backFaceCulling && this._twoSidedLighting) {
  41544. defines.TWOSIDEDLIGHTING = true;
  41545. }
  41546. else {
  41547. defines.TWOSIDEDLIGHTING = false;
  41548. }
  41549. defines.ALPHATESTVALUE = this._alphaCutOff;
  41550. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41551. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41552. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41553. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41554. }
  41555. if (defines._areImageProcessingDirty) {
  41556. this._imageProcessingConfiguration.prepareDefines(defines);
  41557. }
  41558. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41559. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41560. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41561. // Misc.
  41562. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41563. // Values that need to be evaluated on every frame
  41564. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41565. // Attribs
  41566. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41567. };
  41568. /**
  41569. * Force shader compilation
  41570. */
  41571. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41572. var _this = this;
  41573. var localOptions = __assign({ clipPlane: false }, options);
  41574. var defines = new PBRMaterialDefines();
  41575. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41576. if (effect.isReady()) {
  41577. if (onCompiled) {
  41578. onCompiled(this);
  41579. }
  41580. }
  41581. else {
  41582. effect.onCompileObservable.add(function () {
  41583. if (onCompiled) {
  41584. onCompiled(_this);
  41585. }
  41586. });
  41587. }
  41588. };
  41589. /**
  41590. * Initializes the uniform buffer layout for the shader.
  41591. */
  41592. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41593. // Order is important !
  41594. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41595. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41596. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41597. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41598. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41599. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41600. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41601. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41602. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41603. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41604. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41605. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41606. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41607. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41608. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41609. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41610. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41611. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41612. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41613. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41614. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41615. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41616. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41617. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41618. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41619. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41620. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41621. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41622. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41623. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41624. this._uniformBuffer.addUniform("pointSize", 1);
  41625. this._uniformBuffer.create();
  41626. };
  41627. /**
  41628. * Unbinds the textures.
  41629. */
  41630. PBRBaseMaterial.prototype.unbind = function () {
  41631. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41632. this._uniformBuffer.setTexture("reflectionSampler", null);
  41633. }
  41634. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41635. this._uniformBuffer.setTexture("refractionSampler", null);
  41636. }
  41637. _super.prototype.unbind.call(this);
  41638. };
  41639. /**
  41640. * Binds the submesh data.
  41641. * @param world - The world matrix.
  41642. * @param mesh - The BJS mesh.
  41643. * @param subMesh - A submesh of the BJS mesh.
  41644. */
  41645. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41646. var scene = this.getScene();
  41647. var defines = subMesh._materialDefines;
  41648. if (!defines) {
  41649. return;
  41650. }
  41651. var effect = subMesh.effect;
  41652. if (!effect) {
  41653. return;
  41654. }
  41655. this._activeEffect = effect;
  41656. // Matrices
  41657. this.bindOnlyWorldMatrix(world);
  41658. // Normal Matrix
  41659. if (defines.OBJECTSPACE_NORMALMAP) {
  41660. world.toNormalMatrix(this._normalMatrix);
  41661. this.bindOnlyNormalMatrix(this._normalMatrix);
  41662. }
  41663. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41664. // Bones
  41665. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41666. var reflectionTexture = null;
  41667. if (mustRebind) {
  41668. this._uniformBuffer.bindToEffect(effect, "Material");
  41669. this.bindViewProjection(effect);
  41670. reflectionTexture = this._getReflectionTexture();
  41671. var refractionTexture = this._getRefractionTexture();
  41672. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41673. // Texture uniforms
  41674. if (scene.texturesEnabled) {
  41675. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41676. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41677. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41678. }
  41679. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41680. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41681. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41682. }
  41683. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41684. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41685. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41686. }
  41687. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41688. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41689. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41690. if (reflectionTexture.boundingBoxSize) {
  41691. var cubeTexture = reflectionTexture;
  41692. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41693. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41694. }
  41695. var polynomials = reflectionTexture.sphericalPolynomial;
  41696. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41697. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41698. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41699. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41700. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41701. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41702. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41703. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41704. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41705. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41706. }
  41707. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41708. }
  41709. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41710. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41711. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41712. }
  41713. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41714. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41715. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41716. }
  41717. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41718. if (this._metallicTexture) {
  41719. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41720. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41721. }
  41722. else if (this._reflectivityTexture) {
  41723. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41724. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41725. }
  41726. if (this._microSurfaceTexture) {
  41727. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41728. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41729. }
  41730. }
  41731. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41732. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41733. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41734. if (scene._mirroredCameraPosition) {
  41735. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41736. }
  41737. else {
  41738. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41739. }
  41740. }
  41741. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41742. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41743. var depth = 1.0;
  41744. if (!refractionTexture.isCube) {
  41745. if (refractionTexture.depth) {
  41746. depth = refractionTexture.depth;
  41747. }
  41748. }
  41749. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41750. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41751. }
  41752. }
  41753. // Point size
  41754. if (this.pointsCloud) {
  41755. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41756. }
  41757. // Colors
  41758. if (defines.METALLICWORKFLOW) {
  41759. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41760. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41761. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41762. }
  41763. else {
  41764. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41765. }
  41766. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41767. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41768. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41769. // Misc
  41770. this._lightingInfos.x = this._directIntensity;
  41771. this._lightingInfos.y = this._emissiveIntensity;
  41772. this._lightingInfos.z = this._environmentIntensity;
  41773. this._lightingInfos.w = this._specularIntensity;
  41774. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41775. }
  41776. // Textures
  41777. if (scene.texturesEnabled) {
  41778. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41779. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41780. }
  41781. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41782. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41783. }
  41784. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41785. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41786. }
  41787. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41788. if (defines.LODBASEDMICROSFURACE) {
  41789. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41790. }
  41791. else {
  41792. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41793. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41794. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41795. }
  41796. }
  41797. if (defines.ENVIRONMENTBRDF) {
  41798. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41799. }
  41800. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41801. if (defines.LODBASEDMICROSFURACE) {
  41802. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41803. }
  41804. else {
  41805. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41806. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41807. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41808. }
  41809. }
  41810. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41811. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41812. }
  41813. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41814. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41815. }
  41816. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41817. if (this._metallicTexture) {
  41818. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41819. }
  41820. else if (this._reflectivityTexture) {
  41821. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41822. }
  41823. if (this._microSurfaceTexture) {
  41824. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41825. }
  41826. }
  41827. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41828. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41829. }
  41830. }
  41831. // Clip plane
  41832. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41833. // Colors
  41834. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41835. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41836. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41837. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41838. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41839. }
  41840. if (mustRebind || !this.isFrozen) {
  41841. // Lights
  41842. if (scene.lightsEnabled && !this._disableLighting) {
  41843. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41844. }
  41845. // View
  41846. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41847. this.bindView(effect);
  41848. }
  41849. // Fog
  41850. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41851. // Morph targets
  41852. if (defines.NUM_MORPH_INFLUENCERS) {
  41853. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41854. }
  41855. // image processing
  41856. this._imageProcessingConfiguration.bind(this._activeEffect);
  41857. // Log. depth
  41858. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41859. }
  41860. this._uniformBuffer.update();
  41861. this._afterBind(mesh);
  41862. };
  41863. /**
  41864. * Returns the animatable textures.
  41865. * @returns - Array of animatable textures.
  41866. */
  41867. PBRBaseMaterial.prototype.getAnimatables = function () {
  41868. var results = [];
  41869. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41870. results.push(this._albedoTexture);
  41871. }
  41872. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41873. results.push(this._ambientTexture);
  41874. }
  41875. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41876. results.push(this._opacityTexture);
  41877. }
  41878. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41879. results.push(this._reflectionTexture);
  41880. }
  41881. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41882. results.push(this._emissiveTexture);
  41883. }
  41884. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41885. results.push(this._metallicTexture);
  41886. }
  41887. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41888. results.push(this._reflectivityTexture);
  41889. }
  41890. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41891. results.push(this._bumpTexture);
  41892. }
  41893. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41894. results.push(this._lightmapTexture);
  41895. }
  41896. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41897. results.push(this._refractionTexture);
  41898. }
  41899. return results;
  41900. };
  41901. /**
  41902. * Returns the texture used for reflections.
  41903. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41904. */
  41905. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41906. if (this._reflectionTexture) {
  41907. return this._reflectionTexture;
  41908. }
  41909. return this.getScene().environmentTexture;
  41910. };
  41911. /**
  41912. * Returns the texture used for refraction or null if none is used.
  41913. * @returns - Refection texture if present. If no refraction texture and refraction
  41914. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41915. */
  41916. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41917. if (this._refractionTexture) {
  41918. return this._refractionTexture;
  41919. }
  41920. if (this._linkRefractionWithTransparency) {
  41921. return this.getScene().environmentTexture;
  41922. }
  41923. return null;
  41924. };
  41925. /**
  41926. * Disposes the resources of the material.
  41927. * @param forceDisposeEffect - Forces the disposal of effects.
  41928. * @param forceDisposeTextures - Forces the disposal of all textures.
  41929. */
  41930. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41931. if (forceDisposeTextures) {
  41932. if (this._albedoTexture) {
  41933. this._albedoTexture.dispose();
  41934. }
  41935. if (this._ambientTexture) {
  41936. this._ambientTexture.dispose();
  41937. }
  41938. if (this._opacityTexture) {
  41939. this._opacityTexture.dispose();
  41940. }
  41941. if (this._reflectionTexture) {
  41942. this._reflectionTexture.dispose();
  41943. }
  41944. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41945. this._environmentBRDFTexture.dispose();
  41946. }
  41947. if (this._emissiveTexture) {
  41948. this._emissiveTexture.dispose();
  41949. }
  41950. if (this._metallicTexture) {
  41951. this._metallicTexture.dispose();
  41952. }
  41953. if (this._reflectivityTexture) {
  41954. this._reflectivityTexture.dispose();
  41955. }
  41956. if (this._bumpTexture) {
  41957. this._bumpTexture.dispose();
  41958. }
  41959. if (this._lightmapTexture) {
  41960. this._lightmapTexture.dispose();
  41961. }
  41962. if (this._refractionTexture) {
  41963. this._refractionTexture.dispose();
  41964. }
  41965. }
  41966. this._renderTargets.dispose();
  41967. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41968. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41969. }
  41970. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41971. };
  41972. /**
  41973. * Stores the reflectivity values based on metallic roughness workflow.
  41974. */
  41975. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41976. __decorate([
  41977. BABYLON.serializeAsImageProcessingConfiguration()
  41978. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41979. __decorate([
  41980. BABYLON.serialize()
  41981. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41982. __decorate([
  41983. BABYLON.serialize()
  41984. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41985. return PBRBaseMaterial;
  41986. }(BABYLON.PushMaterial));
  41987. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41988. })(BABYLON || (BABYLON = {}));
  41989. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41990. var BABYLON;
  41991. (function (BABYLON) {
  41992. /**
  41993. * The Physically based simple base material of BJS.
  41994. *
  41995. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41996. * It is used as the base class for both the specGloss and metalRough conventions.
  41997. */
  41998. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41999. __extends(PBRBaseSimpleMaterial, _super);
  42000. /**
  42001. * Instantiates a new PBRMaterial instance.
  42002. *
  42003. * @param name The material name
  42004. * @param scene The scene the material will be use in.
  42005. */
  42006. function PBRBaseSimpleMaterial(name, scene) {
  42007. var _this = _super.call(this, name, scene) || this;
  42008. /**
  42009. * Number of Simultaneous lights allowed on the material.
  42010. */
  42011. _this.maxSimultaneousLights = 4;
  42012. /**
  42013. * If sets to true, disables all the lights affecting the material.
  42014. */
  42015. _this.disableLighting = false;
  42016. /**
  42017. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42018. */
  42019. _this.invertNormalMapX = false;
  42020. /**
  42021. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42022. */
  42023. _this.invertNormalMapY = false;
  42024. /**
  42025. * Emissivie color used to self-illuminate the model.
  42026. */
  42027. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42028. /**
  42029. * Occlusion Channel Strenght.
  42030. */
  42031. _this.occlusionStrength = 1.0;
  42032. _this.useLightmapAsShadowmap = false;
  42033. _this._useAlphaFromAlbedoTexture = true;
  42034. _this._useAmbientInGrayScale = true;
  42035. return _this;
  42036. }
  42037. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  42038. /**
  42039. * Gets the current double sided mode.
  42040. */
  42041. get: function () {
  42042. return this._twoSidedLighting;
  42043. },
  42044. /**
  42045. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42046. */
  42047. set: function (value) {
  42048. if (this._twoSidedLighting === value) {
  42049. return;
  42050. }
  42051. this._twoSidedLighting = value;
  42052. this.backFaceCulling = !value;
  42053. this._markAllSubMeshesAsTexturesDirty();
  42054. },
  42055. enumerable: true,
  42056. configurable: true
  42057. });
  42058. /**
  42059. * Return the active textures of the material.
  42060. */
  42061. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  42062. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42063. if (this.environmentTexture) {
  42064. activeTextures.push(this.environmentTexture);
  42065. }
  42066. if (this.normalTexture) {
  42067. activeTextures.push(this.normalTexture);
  42068. }
  42069. if (this.emissiveTexture) {
  42070. activeTextures.push(this.emissiveTexture);
  42071. }
  42072. if (this.occlusionTexture) {
  42073. activeTextures.push(this.occlusionTexture);
  42074. }
  42075. if (this.lightmapTexture) {
  42076. activeTextures.push(this.lightmapTexture);
  42077. }
  42078. return activeTextures;
  42079. };
  42080. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  42081. if (_super.prototype.hasTexture.call(this, texture)) {
  42082. return true;
  42083. }
  42084. if (this.lightmapTexture === texture) {
  42085. return true;
  42086. }
  42087. return false;
  42088. };
  42089. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  42090. return "PBRBaseSimpleMaterial";
  42091. };
  42092. __decorate([
  42093. BABYLON.serialize(),
  42094. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42095. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  42096. __decorate([
  42097. BABYLON.serialize(),
  42098. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42099. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  42100. __decorate([
  42101. BABYLON.serializeAsTexture(),
  42102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  42103. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  42104. __decorate([
  42105. BABYLON.serialize(),
  42106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42107. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  42108. __decorate([
  42109. BABYLON.serialize(),
  42110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42111. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  42112. __decorate([
  42113. BABYLON.serializeAsTexture(),
  42114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  42115. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  42116. __decorate([
  42117. BABYLON.serializeAsColor3("emissive"),
  42118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42119. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  42120. __decorate([
  42121. BABYLON.serializeAsTexture(),
  42122. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42123. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  42124. __decorate([
  42125. BABYLON.serialize(),
  42126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  42127. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  42128. __decorate([
  42129. BABYLON.serializeAsTexture(),
  42130. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  42131. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  42132. __decorate([
  42133. BABYLON.serialize(),
  42134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  42135. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  42136. __decorate([
  42137. BABYLON.serialize()
  42138. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  42139. __decorate([
  42140. BABYLON.serializeAsTexture(),
  42141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42142. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  42143. __decorate([
  42144. BABYLON.serialize(),
  42145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42146. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42147. return PBRBaseSimpleMaterial;
  42148. }(BABYLON.PBRBaseMaterial));
  42149. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  42150. })(BABYLON || (BABYLON = {}));
  42151. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  42152. var BABYLON;
  42153. (function (BABYLON) {
  42154. /**
  42155. * The Physically based material of BJS.
  42156. *
  42157. * This offers the main features of a standard PBR material.
  42158. * For more information, please refer to the documentation :
  42159. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42160. */
  42161. var PBRMaterial = /** @class */ (function (_super) {
  42162. __extends(PBRMaterial, _super);
  42163. /**
  42164. * Instantiates a new PBRMaterial instance.
  42165. *
  42166. * @param name The material name
  42167. * @param scene The scene the material will be use in.
  42168. */
  42169. function PBRMaterial(name, scene) {
  42170. var _this = _super.call(this, name, scene) || this;
  42171. /**
  42172. * Intensity of the direct lights e.g. the four lights available in your scene.
  42173. * This impacts both the direct diffuse and specular highlights.
  42174. */
  42175. _this.directIntensity = 1.0;
  42176. /**
  42177. * Intensity of the emissive part of the material.
  42178. * This helps controlling the emissive effect without modifying the emissive color.
  42179. */
  42180. _this.emissiveIntensity = 1.0;
  42181. /**
  42182. * Intensity of the environment e.g. how much the environment will light the object
  42183. * either through harmonics for rough material or through the refelction for shiny ones.
  42184. */
  42185. _this.environmentIntensity = 1.0;
  42186. /**
  42187. * This is a special control allowing the reduction of the specular highlights coming from the
  42188. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42189. */
  42190. _this.specularIntensity = 1.0;
  42191. /**
  42192. * Debug Control allowing disabling the bump map on this material.
  42193. */
  42194. _this.disableBumpMap = false;
  42195. /**
  42196. * AKA Occlusion Texture Intensity in other nomenclature.
  42197. */
  42198. _this.ambientTextureStrength = 1.0;
  42199. /**
  42200. * The color of a material in ambient lighting.
  42201. */
  42202. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42203. /**
  42204. * AKA Diffuse Color in other nomenclature.
  42205. */
  42206. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42207. /**
  42208. * AKA Specular Color in other nomenclature.
  42209. */
  42210. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42211. /**
  42212. * The color reflected from the material.
  42213. */
  42214. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42215. /**
  42216. * The color emitted from the material.
  42217. */
  42218. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42219. /**
  42220. * AKA Glossiness in other nomenclature.
  42221. */
  42222. _this.microSurface = 1.0;
  42223. /**
  42224. * source material index of refraction (IOR)' / 'destination material IOR.
  42225. */
  42226. _this.indexOfRefraction = 0.66;
  42227. /**
  42228. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42229. */
  42230. _this.invertRefractionY = false;
  42231. /**
  42232. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42233. * Materials half opaque for instance using refraction could benefit from this control.
  42234. */
  42235. _this.linkRefractionWithTransparency = false;
  42236. _this.useLightmapAsShadowmap = false;
  42237. /**
  42238. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42239. */
  42240. _this.useAlphaFromAlbedoTexture = false;
  42241. /**
  42242. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42243. */
  42244. _this.forceAlphaTest = false;
  42245. /**
  42246. * Defines the alpha limits in alpha test mode.
  42247. */
  42248. _this.alphaCutOff = 0.4;
  42249. /**
  42250. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42251. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42252. */
  42253. _this.useSpecularOverAlpha = true;
  42254. /**
  42255. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42256. */
  42257. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42258. /**
  42259. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42260. */
  42261. _this.useRoughnessFromMetallicTextureAlpha = true;
  42262. /**
  42263. * Specifies if the metallic texture contains the roughness information in its green channel.
  42264. */
  42265. _this.useRoughnessFromMetallicTextureGreen = false;
  42266. /**
  42267. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42268. */
  42269. _this.useMetallnessFromMetallicTextureBlue = false;
  42270. /**
  42271. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42272. */
  42273. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42274. /**
  42275. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42276. */
  42277. _this.useAmbientInGrayScale = false;
  42278. /**
  42279. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42280. * The material will try to infer what glossiness each pixel should be.
  42281. */
  42282. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42283. /**
  42284. * BJS is using an harcoded light falloff based on a manually sets up range.
  42285. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42286. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42287. */
  42288. _this.usePhysicalLightFalloff = true;
  42289. /**
  42290. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42291. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42292. */
  42293. _this.useRadianceOverAlpha = true;
  42294. /**
  42295. * Allows using an object space normal map (instead of tangent space).
  42296. */
  42297. _this.useObjectSpaceNormalMap = false;
  42298. /**
  42299. * Allows using the bump map in parallax mode.
  42300. */
  42301. _this.useParallax = false;
  42302. /**
  42303. * Allows using the bump map in parallax occlusion mode.
  42304. */
  42305. _this.useParallaxOcclusion = false;
  42306. /**
  42307. * Controls the scale bias of the parallax mode.
  42308. */
  42309. _this.parallaxScaleBias = 0.05;
  42310. /**
  42311. * If sets to true, disables all the lights affecting the material.
  42312. */
  42313. _this.disableLighting = false;
  42314. /**
  42315. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42316. */
  42317. _this.forceIrradianceInFragment = false;
  42318. /**
  42319. * Number of Simultaneous lights allowed on the material.
  42320. */
  42321. _this.maxSimultaneousLights = 4;
  42322. /**
  42323. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42324. */
  42325. _this.invertNormalMapX = false;
  42326. /**
  42327. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42328. */
  42329. _this.invertNormalMapY = false;
  42330. /**
  42331. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42332. */
  42333. _this.twoSidedLighting = false;
  42334. /**
  42335. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42336. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42337. */
  42338. _this.useAlphaFresnel = false;
  42339. /**
  42340. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42341. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42342. */
  42343. _this.useLinearAlphaFresnel = false;
  42344. /**
  42345. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42346. * And/Or occlude the blended part.
  42347. */
  42348. _this.environmentBRDFTexture = null;
  42349. /**
  42350. * Force normal to face away from face.
  42351. */
  42352. _this.forceNormalForward = false;
  42353. /**
  42354. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42355. * makes the reflect vector face the model (under horizon).
  42356. */
  42357. _this.useHorizonOcclusion = true;
  42358. /**
  42359. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42360. * too much the area relying on ambient texture to define their ambient occlusion.
  42361. */
  42362. _this.useRadianceOcclusion = true;
  42363. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42364. return _this;
  42365. }
  42366. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42367. /**
  42368. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42369. */
  42370. get: function () {
  42371. return this._PBRMATERIAL_OPAQUE;
  42372. },
  42373. enumerable: true,
  42374. configurable: true
  42375. });
  42376. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42377. /**
  42378. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42379. */
  42380. get: function () {
  42381. return this._PBRMATERIAL_ALPHATEST;
  42382. },
  42383. enumerable: true,
  42384. configurable: true
  42385. });
  42386. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42387. /**
  42388. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42389. */
  42390. get: function () {
  42391. return this._PBRMATERIAL_ALPHABLEND;
  42392. },
  42393. enumerable: true,
  42394. configurable: true
  42395. });
  42396. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42397. /**
  42398. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42399. * They are also discarded below the alpha cutoff threshold to improve performances.
  42400. */
  42401. get: function () {
  42402. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42403. },
  42404. enumerable: true,
  42405. configurable: true
  42406. });
  42407. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42408. /**
  42409. * Gets the image processing configuration used either in this material.
  42410. */
  42411. get: function () {
  42412. return this._imageProcessingConfiguration;
  42413. },
  42414. /**
  42415. * Sets the Default image processing configuration used either in the this material.
  42416. *
  42417. * If sets to null, the scene one is in use.
  42418. */
  42419. set: function (value) {
  42420. this._attachImageProcessingConfiguration(value);
  42421. // Ensure the effect will be rebuilt.
  42422. this._markAllSubMeshesAsTexturesDirty();
  42423. },
  42424. enumerable: true,
  42425. configurable: true
  42426. });
  42427. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42428. /**
  42429. * Gets wether the color curves effect is enabled.
  42430. */
  42431. get: function () {
  42432. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42433. },
  42434. /**
  42435. * Sets wether the color curves effect is enabled.
  42436. */
  42437. set: function (value) {
  42438. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42439. },
  42440. enumerable: true,
  42441. configurable: true
  42442. });
  42443. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42444. /**
  42445. * Gets wether the color grading effect is enabled.
  42446. */
  42447. get: function () {
  42448. return this.imageProcessingConfiguration.colorGradingEnabled;
  42449. },
  42450. /**
  42451. * Gets wether the color grading effect is enabled.
  42452. */
  42453. set: function (value) {
  42454. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42455. },
  42456. enumerable: true,
  42457. configurable: true
  42458. });
  42459. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42460. /**
  42461. * Gets wether tonemapping is enabled or not.
  42462. */
  42463. get: function () {
  42464. return this._imageProcessingConfiguration.toneMappingEnabled;
  42465. },
  42466. /**
  42467. * Sets wether tonemapping is enabled or not
  42468. */
  42469. set: function (value) {
  42470. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42471. },
  42472. enumerable: true,
  42473. configurable: true
  42474. });
  42475. ;
  42476. ;
  42477. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42478. /**
  42479. * The camera exposure used on this material.
  42480. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42481. * This corresponds to a photographic exposure.
  42482. */
  42483. get: function () {
  42484. return this._imageProcessingConfiguration.exposure;
  42485. },
  42486. /**
  42487. * The camera exposure used on this material.
  42488. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42489. * This corresponds to a photographic exposure.
  42490. */
  42491. set: function (value) {
  42492. this._imageProcessingConfiguration.exposure = value;
  42493. },
  42494. enumerable: true,
  42495. configurable: true
  42496. });
  42497. ;
  42498. ;
  42499. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42500. /**
  42501. * Gets The camera contrast used on this material.
  42502. */
  42503. get: function () {
  42504. return this._imageProcessingConfiguration.contrast;
  42505. },
  42506. /**
  42507. * Sets The camera contrast used on this material.
  42508. */
  42509. set: function (value) {
  42510. this._imageProcessingConfiguration.contrast = value;
  42511. },
  42512. enumerable: true,
  42513. configurable: true
  42514. });
  42515. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42516. /**
  42517. * Gets the Color Grading 2D Lookup Texture.
  42518. */
  42519. get: function () {
  42520. return this._imageProcessingConfiguration.colorGradingTexture;
  42521. },
  42522. /**
  42523. * Sets the Color Grading 2D Lookup Texture.
  42524. */
  42525. set: function (value) {
  42526. this._imageProcessingConfiguration.colorGradingTexture = value;
  42527. },
  42528. enumerable: true,
  42529. configurable: true
  42530. });
  42531. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42532. /**
  42533. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42534. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42535. * 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;
  42536. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42537. */
  42538. get: function () {
  42539. return this._imageProcessingConfiguration.colorCurves;
  42540. },
  42541. /**
  42542. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42543. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42544. * 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;
  42545. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42546. */
  42547. set: function (value) {
  42548. this._imageProcessingConfiguration.colorCurves = value;
  42549. },
  42550. enumerable: true,
  42551. configurable: true
  42552. });
  42553. /**
  42554. * Returns the name of this material class.
  42555. */
  42556. PBRMaterial.prototype.getClassName = function () {
  42557. return "PBRMaterial";
  42558. };
  42559. /**
  42560. * Returns an array of the actively used textures.
  42561. * @returns - Array of BaseTextures
  42562. */
  42563. PBRMaterial.prototype.getActiveTextures = function () {
  42564. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42565. if (this._albedoTexture) {
  42566. activeTextures.push(this._albedoTexture);
  42567. }
  42568. if (this._ambientTexture) {
  42569. activeTextures.push(this._ambientTexture);
  42570. }
  42571. if (this._opacityTexture) {
  42572. activeTextures.push(this._opacityTexture);
  42573. }
  42574. if (this._reflectionTexture) {
  42575. activeTextures.push(this._reflectionTexture);
  42576. }
  42577. if (this._emissiveTexture) {
  42578. activeTextures.push(this._emissiveTexture);
  42579. }
  42580. if (this._reflectivityTexture) {
  42581. activeTextures.push(this._reflectivityTexture);
  42582. }
  42583. if (this._metallicTexture) {
  42584. activeTextures.push(this._metallicTexture);
  42585. }
  42586. if (this._microSurfaceTexture) {
  42587. activeTextures.push(this._microSurfaceTexture);
  42588. }
  42589. if (this._bumpTexture) {
  42590. activeTextures.push(this._bumpTexture);
  42591. }
  42592. if (this._lightmapTexture) {
  42593. activeTextures.push(this._lightmapTexture);
  42594. }
  42595. if (this._refractionTexture) {
  42596. activeTextures.push(this._refractionTexture);
  42597. }
  42598. return activeTextures;
  42599. };
  42600. /**
  42601. * Checks to see if a texture is used in the material.
  42602. * @param texture - Base texture to use.
  42603. * @returns - Boolean specifying if a texture is used in the material.
  42604. */
  42605. PBRMaterial.prototype.hasTexture = function (texture) {
  42606. if (_super.prototype.hasTexture.call(this, texture)) {
  42607. return true;
  42608. }
  42609. if (this._albedoTexture === texture) {
  42610. return true;
  42611. }
  42612. if (this._ambientTexture === texture) {
  42613. return true;
  42614. }
  42615. if (this._opacityTexture === texture) {
  42616. return true;
  42617. }
  42618. if (this._reflectionTexture === texture) {
  42619. return true;
  42620. }
  42621. if (this._reflectivityTexture === texture) {
  42622. return true;
  42623. }
  42624. if (this._metallicTexture === texture) {
  42625. return true;
  42626. }
  42627. if (this._microSurfaceTexture === texture) {
  42628. return true;
  42629. }
  42630. if (this._bumpTexture === texture) {
  42631. return true;
  42632. }
  42633. if (this._lightmapTexture === texture) {
  42634. return true;
  42635. }
  42636. if (this._refractionTexture === texture) {
  42637. return true;
  42638. }
  42639. return false;
  42640. };
  42641. /**
  42642. * Makes a duplicate of the current material.
  42643. * @param name - name to use for the new material.
  42644. */
  42645. PBRMaterial.prototype.clone = function (name) {
  42646. var _this = this;
  42647. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42648. clone.id = name;
  42649. clone.name = name;
  42650. return clone;
  42651. };
  42652. /**
  42653. * Serializes this PBR Material.
  42654. * @returns - An object with the serialized material.
  42655. */
  42656. PBRMaterial.prototype.serialize = function () {
  42657. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42658. serializationObject.customType = "BABYLON.PBRMaterial";
  42659. return serializationObject;
  42660. };
  42661. // Statics
  42662. /**
  42663. * Parses a PBR Material from a serialized object.
  42664. * @param source - Serialized object.
  42665. * @param scene - BJS scene instance.
  42666. * @param rootUrl - url for the scene object
  42667. * @returns - PBRMaterial
  42668. */
  42669. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42670. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42671. };
  42672. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42673. /**
  42674. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42675. */
  42676. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42677. /**
  42678. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42679. */
  42680. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42681. /**
  42682. * 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.
  42683. * They are also discarded below the alpha cutoff threshold to improve performances.
  42684. */
  42685. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42686. __decorate([
  42687. BABYLON.serialize(),
  42688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42689. ], PBRMaterial.prototype, "directIntensity", void 0);
  42690. __decorate([
  42691. BABYLON.serialize(),
  42692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42693. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42694. __decorate([
  42695. BABYLON.serialize(),
  42696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42697. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42698. __decorate([
  42699. BABYLON.serialize(),
  42700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42701. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42702. __decorate([
  42703. BABYLON.serialize(),
  42704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42705. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42706. __decorate([
  42707. BABYLON.serializeAsTexture(),
  42708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42709. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42710. __decorate([
  42711. BABYLON.serializeAsTexture(),
  42712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42713. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42714. __decorate([
  42715. BABYLON.serialize(),
  42716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42717. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42718. __decorate([
  42719. BABYLON.serializeAsTexture(),
  42720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42721. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42722. __decorate([
  42723. BABYLON.serializeAsTexture(),
  42724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42725. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42726. __decorate([
  42727. BABYLON.serializeAsTexture(),
  42728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42729. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42730. __decorate([
  42731. BABYLON.serializeAsTexture(),
  42732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42733. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42734. __decorate([
  42735. BABYLON.serializeAsTexture(),
  42736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42737. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42738. __decorate([
  42739. BABYLON.serialize(),
  42740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42741. ], PBRMaterial.prototype, "metallic", void 0);
  42742. __decorate([
  42743. BABYLON.serialize(),
  42744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42745. ], PBRMaterial.prototype, "roughness", void 0);
  42746. __decorate([
  42747. BABYLON.serializeAsTexture(),
  42748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42749. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42750. __decorate([
  42751. BABYLON.serializeAsTexture(),
  42752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42753. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42754. __decorate([
  42755. BABYLON.serializeAsTexture(),
  42756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42757. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42758. __decorate([
  42759. BABYLON.serializeAsTexture(),
  42760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42761. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42762. __decorate([
  42763. BABYLON.serializeAsColor3("ambient"),
  42764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42765. ], PBRMaterial.prototype, "ambientColor", void 0);
  42766. __decorate([
  42767. BABYLON.serializeAsColor3("albedo"),
  42768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42769. ], PBRMaterial.prototype, "albedoColor", void 0);
  42770. __decorate([
  42771. BABYLON.serializeAsColor3("reflectivity"),
  42772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42773. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42774. __decorate([
  42775. BABYLON.serializeAsColor3("reflection"),
  42776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42777. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42778. __decorate([
  42779. BABYLON.serializeAsColor3("emissive"),
  42780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42781. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42782. __decorate([
  42783. BABYLON.serialize(),
  42784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42785. ], PBRMaterial.prototype, "microSurface", void 0);
  42786. __decorate([
  42787. BABYLON.serialize(),
  42788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42789. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42790. __decorate([
  42791. BABYLON.serialize(),
  42792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42793. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42794. __decorate([
  42795. BABYLON.serialize(),
  42796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42797. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42798. __decorate([
  42799. BABYLON.serialize(),
  42800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42801. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42802. __decorate([
  42803. BABYLON.serialize(),
  42804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42805. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42806. __decorate([
  42807. BABYLON.serialize(),
  42808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42809. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42810. __decorate([
  42811. BABYLON.serialize(),
  42812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42813. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42814. __decorate([
  42815. BABYLON.serialize(),
  42816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42817. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42818. __decorate([
  42819. BABYLON.serialize(),
  42820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42821. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42822. __decorate([
  42823. BABYLON.serialize(),
  42824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42825. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42826. __decorate([
  42827. BABYLON.serialize(),
  42828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42829. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42830. __decorate([
  42831. BABYLON.serialize(),
  42832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42833. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42834. __decorate([
  42835. BABYLON.serialize(),
  42836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42837. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42838. __decorate([
  42839. BABYLON.serialize(),
  42840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42841. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42842. __decorate([
  42843. BABYLON.serialize(),
  42844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42845. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42846. __decorate([
  42847. BABYLON.serialize(),
  42848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42849. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42850. __decorate([
  42851. BABYLON.serialize(),
  42852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42853. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42854. __decorate([
  42855. BABYLON.serialize(),
  42856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42857. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42858. __decorate([
  42859. BABYLON.serialize(),
  42860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42861. ], PBRMaterial.prototype, "useParallax", void 0);
  42862. __decorate([
  42863. BABYLON.serialize(),
  42864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42865. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42866. __decorate([
  42867. BABYLON.serialize(),
  42868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42869. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42870. __decorate([
  42871. BABYLON.serialize(),
  42872. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42873. ], PBRMaterial.prototype, "disableLighting", void 0);
  42874. __decorate([
  42875. BABYLON.serialize(),
  42876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42877. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42878. __decorate([
  42879. BABYLON.serialize(),
  42880. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42881. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42882. __decorate([
  42883. BABYLON.serialize(),
  42884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42885. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42886. __decorate([
  42887. BABYLON.serialize(),
  42888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42889. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42890. __decorate([
  42891. BABYLON.serialize(),
  42892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42893. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42894. __decorate([
  42895. BABYLON.serialize(),
  42896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42897. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42898. __decorate([
  42899. BABYLON.serialize(),
  42900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42901. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42902. __decorate([
  42903. BABYLON.serializeAsTexture(),
  42904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42905. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42906. __decorate([
  42907. BABYLON.serialize(),
  42908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42909. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42910. __decorate([
  42911. BABYLON.serialize(),
  42912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42913. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42914. __decorate([
  42915. BABYLON.serialize(),
  42916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42917. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42918. return PBRMaterial;
  42919. }(BABYLON.PBRBaseMaterial));
  42920. BABYLON.PBRMaterial = PBRMaterial;
  42921. })(BABYLON || (BABYLON = {}));
  42922. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42923. var BABYLON;
  42924. (function (BABYLON) {
  42925. /**
  42926. * The PBR material of BJS following the metal roughness convention.
  42927. *
  42928. * This fits to the PBR convention in the GLTF definition:
  42929. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42930. */
  42931. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42932. __extends(PBRMetallicRoughnessMaterial, _super);
  42933. /**
  42934. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42935. *
  42936. * @param name The material name
  42937. * @param scene The scene the material will be use in.
  42938. */
  42939. function PBRMetallicRoughnessMaterial(name, scene) {
  42940. var _this = _super.call(this, name, scene) || this;
  42941. _this._useRoughnessFromMetallicTextureAlpha = false;
  42942. _this._useRoughnessFromMetallicTextureGreen = true;
  42943. _this._useMetallnessFromMetallicTextureBlue = true;
  42944. _this.metallic = 1.0;
  42945. _this.roughness = 1.0;
  42946. return _this;
  42947. }
  42948. /**
  42949. * Return the currrent class name of the material.
  42950. */
  42951. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42952. return "PBRMetallicRoughnessMaterial";
  42953. };
  42954. /**
  42955. * Return the active textures of the material.
  42956. */
  42957. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42958. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42959. if (this.baseTexture) {
  42960. activeTextures.push(this.baseTexture);
  42961. }
  42962. if (this.metallicRoughnessTexture) {
  42963. activeTextures.push(this.metallicRoughnessTexture);
  42964. }
  42965. return activeTextures;
  42966. };
  42967. /**
  42968. * Checks to see if a texture is used in the material.
  42969. * @param texture - Base texture to use.
  42970. * @returns - Boolean specifying if a texture is used in the material.
  42971. */
  42972. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42973. if (_super.prototype.hasTexture.call(this, texture)) {
  42974. return true;
  42975. }
  42976. if (this.baseTexture === texture) {
  42977. return true;
  42978. }
  42979. if (this.metallicRoughnessTexture === texture) {
  42980. return true;
  42981. }
  42982. return false;
  42983. };
  42984. /**
  42985. * Makes a duplicate of the current material.
  42986. * @param name - name to use for the new material.
  42987. */
  42988. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42989. var _this = this;
  42990. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42991. clone.id = name;
  42992. clone.name = name;
  42993. return clone;
  42994. };
  42995. /**
  42996. * Serialize the material to a parsable JSON object.
  42997. */
  42998. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42999. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43000. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  43001. return serializationObject;
  43002. };
  43003. /**
  43004. * Parses a JSON object correponding to the serialize function.
  43005. */
  43006. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  43007. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  43008. };
  43009. __decorate([
  43010. BABYLON.serializeAsColor3(),
  43011. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43012. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  43013. __decorate([
  43014. BABYLON.serializeAsTexture(),
  43015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43016. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  43017. __decorate([
  43018. BABYLON.serialize(),
  43019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43020. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  43021. __decorate([
  43022. BABYLON.serialize(),
  43023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43024. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  43025. __decorate([
  43026. BABYLON.serializeAsTexture(),
  43027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  43028. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  43029. return PBRMetallicRoughnessMaterial;
  43030. }(BABYLON.PBRBaseSimpleMaterial));
  43031. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  43032. })(BABYLON || (BABYLON = {}));
  43033. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  43034. var BABYLON;
  43035. (function (BABYLON) {
  43036. /**
  43037. * The PBR material of BJS following the specular glossiness convention.
  43038. *
  43039. * This fits to the PBR convention in the GLTF definition:
  43040. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  43041. */
  43042. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  43043. __extends(PBRSpecularGlossinessMaterial, _super);
  43044. /**
  43045. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  43046. *
  43047. * @param name The material name
  43048. * @param scene The scene the material will be use in.
  43049. */
  43050. function PBRSpecularGlossinessMaterial(name, scene) {
  43051. var _this = _super.call(this, name, scene) || this;
  43052. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  43053. return _this;
  43054. }
  43055. /**
  43056. * Return the currrent class name of the material.
  43057. */
  43058. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  43059. return "PBRSpecularGlossinessMaterial";
  43060. };
  43061. /**
  43062. * Return the active textures of the material.
  43063. */
  43064. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  43065. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43066. if (this.diffuseTexture) {
  43067. activeTextures.push(this.diffuseTexture);
  43068. }
  43069. if (this.specularGlossinessTexture) {
  43070. activeTextures.push(this.specularGlossinessTexture);
  43071. }
  43072. return activeTextures;
  43073. };
  43074. /**
  43075. * Checks to see if a texture is used in the material.
  43076. * @param texture - Base texture to use.
  43077. * @returns - Boolean specifying if a texture is used in the material.
  43078. */
  43079. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  43080. if (_super.prototype.hasTexture.call(this, texture)) {
  43081. return true;
  43082. }
  43083. if (this.diffuseTexture === texture) {
  43084. return true;
  43085. }
  43086. if (this.specularGlossinessTexture === texture) {
  43087. return true;
  43088. }
  43089. return false;
  43090. };
  43091. /**
  43092. * Makes a duplicate of the current material.
  43093. * @param name - name to use for the new material.
  43094. */
  43095. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  43096. var _this = this;
  43097. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  43098. clone.id = name;
  43099. clone.name = name;
  43100. return clone;
  43101. };
  43102. /**
  43103. * Serialize the material to a parsable JSON object.
  43104. */
  43105. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  43106. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43107. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  43108. return serializationObject;
  43109. };
  43110. /**
  43111. * Parses a JSON object correponding to the serialize function.
  43112. */
  43113. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  43114. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  43115. };
  43116. __decorate([
  43117. BABYLON.serializeAsColor3("diffuse"),
  43118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43119. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  43120. __decorate([
  43121. BABYLON.serializeAsTexture(),
  43122. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43123. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  43124. __decorate([
  43125. BABYLON.serializeAsColor3("specular"),
  43126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  43127. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  43128. __decorate([
  43129. BABYLON.serialize(),
  43130. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  43131. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  43132. __decorate([
  43133. BABYLON.serializeAsTexture(),
  43134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  43135. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  43136. return PBRSpecularGlossinessMaterial;
  43137. }(BABYLON.PBRBaseSimpleMaterial));
  43138. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  43139. })(BABYLON || (BABYLON = {}));
  43140. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  43141. var BABYLON;
  43142. (function (BABYLON) {
  43143. BABYLON.CameraInputTypes = {};
  43144. var CameraInputsManager = /** @class */ (function () {
  43145. function CameraInputsManager(camera) {
  43146. this.attached = {};
  43147. this.camera = camera;
  43148. this.checkInputs = function () { };
  43149. }
  43150. /**
  43151. * Add an input method to a camera.
  43152. * builtin inputs example: camera.inputs.addGamepad();
  43153. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  43154. * @param input camera input method
  43155. */
  43156. CameraInputsManager.prototype.add = function (input) {
  43157. var type = input.getSimpleName();
  43158. if (this.attached[type]) {
  43159. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  43160. return;
  43161. }
  43162. this.attached[type] = input;
  43163. input.camera = this.camera;
  43164. //for checkInputs, we are dynamically creating a function
  43165. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  43166. if (input.checkInputs) {
  43167. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43168. }
  43169. if (this.attachedElement) {
  43170. input.attachControl(this.attachedElement);
  43171. }
  43172. };
  43173. /**
  43174. * Remove a specific input method from a camera
  43175. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43176. * @param inputToRemove camera input method
  43177. */
  43178. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43179. for (var cam in this.attached) {
  43180. var input = this.attached[cam];
  43181. if (input === inputToRemove) {
  43182. input.detachControl(this.attachedElement);
  43183. input.camera = null;
  43184. delete this.attached[cam];
  43185. this.rebuildInputCheck();
  43186. }
  43187. }
  43188. };
  43189. CameraInputsManager.prototype.removeByType = function (inputType) {
  43190. for (var cam in this.attached) {
  43191. var input = this.attached[cam];
  43192. if (input.getClassName() === inputType) {
  43193. input.detachControl(this.attachedElement);
  43194. input.camera = null;
  43195. delete this.attached[cam];
  43196. this.rebuildInputCheck();
  43197. }
  43198. }
  43199. };
  43200. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43201. var current = this.checkInputs;
  43202. return function () {
  43203. current();
  43204. fn();
  43205. };
  43206. };
  43207. CameraInputsManager.prototype.attachInput = function (input) {
  43208. if (this.attachedElement) {
  43209. input.attachControl(this.attachedElement, this.noPreventDefault);
  43210. }
  43211. };
  43212. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43213. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43214. if (this.attachedElement) {
  43215. return;
  43216. }
  43217. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43218. this.attachedElement = element;
  43219. this.noPreventDefault = noPreventDefault;
  43220. for (var cam in this.attached) {
  43221. this.attached[cam].attachControl(element, noPreventDefault);
  43222. }
  43223. };
  43224. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43225. if (disconnect === void 0) { disconnect = false; }
  43226. if (this.attachedElement !== element) {
  43227. return;
  43228. }
  43229. for (var cam in this.attached) {
  43230. this.attached[cam].detachControl(element);
  43231. if (disconnect) {
  43232. this.attached[cam].camera = null;
  43233. }
  43234. }
  43235. this.attachedElement = null;
  43236. };
  43237. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43238. this.checkInputs = function () { };
  43239. for (var cam in this.attached) {
  43240. var input = this.attached[cam];
  43241. if (input.checkInputs) {
  43242. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43243. }
  43244. }
  43245. };
  43246. /**
  43247. * Remove all attached input methods from a camera
  43248. */
  43249. CameraInputsManager.prototype.clear = function () {
  43250. if (this.attachedElement) {
  43251. this.detachElement(this.attachedElement, true);
  43252. }
  43253. this.attached = {};
  43254. this.attachedElement = null;
  43255. this.checkInputs = function () { };
  43256. };
  43257. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43258. var inputs = {};
  43259. for (var cam in this.attached) {
  43260. var input = this.attached[cam];
  43261. var res = BABYLON.SerializationHelper.Serialize(input);
  43262. inputs[input.getClassName()] = res;
  43263. }
  43264. serializedCamera.inputsmgr = inputs;
  43265. };
  43266. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43267. var parsedInputs = parsedCamera.inputsmgr;
  43268. if (parsedInputs) {
  43269. this.clear();
  43270. for (var n in parsedInputs) {
  43271. var construct = BABYLON.CameraInputTypes[n];
  43272. if (construct) {
  43273. var parsedinput = parsedInputs[n];
  43274. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43275. this.add(input);
  43276. }
  43277. }
  43278. }
  43279. else {
  43280. //2016-03-08 this part is for managing backward compatibility
  43281. for (var n in this.attached) {
  43282. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43283. if (construct) {
  43284. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43285. this.remove(this.attached[n]);
  43286. this.add(input);
  43287. }
  43288. }
  43289. }
  43290. };
  43291. return CameraInputsManager;
  43292. }());
  43293. BABYLON.CameraInputsManager = CameraInputsManager;
  43294. })(BABYLON || (BABYLON = {}));
  43295. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43296. var BABYLON;
  43297. (function (BABYLON) {
  43298. var TargetCamera = /** @class */ (function (_super) {
  43299. __extends(TargetCamera, _super);
  43300. function TargetCamera(name, position, scene) {
  43301. var _this = _super.call(this, name, position, scene) || this;
  43302. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43303. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43304. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43305. _this.speed = 2.0;
  43306. _this.noRotationConstraint = false;
  43307. _this.lockedTarget = null;
  43308. _this._currentTarget = BABYLON.Vector3.Zero();
  43309. _this._viewMatrix = BABYLON.Matrix.Zero();
  43310. _this._camMatrix = BABYLON.Matrix.Zero();
  43311. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43312. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43313. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43314. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43315. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43316. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43317. _this._tempMatrix = BABYLON.Matrix.Zero();
  43318. return _this;
  43319. }
  43320. TargetCamera.prototype.getFrontPosition = function (distance) {
  43321. this.getWorldMatrix();
  43322. var direction = this.getTarget().subtract(this.position);
  43323. direction.normalize();
  43324. direction.scaleInPlace(distance);
  43325. return this.globalPosition.add(direction);
  43326. };
  43327. TargetCamera.prototype._getLockedTargetPosition = function () {
  43328. if (!this.lockedTarget) {
  43329. return null;
  43330. }
  43331. if (this.lockedTarget.absolutePosition) {
  43332. this.lockedTarget.computeWorldMatrix();
  43333. }
  43334. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43335. };
  43336. TargetCamera.prototype.storeState = function () {
  43337. this._storedPosition = this.position.clone();
  43338. this._storedRotation = this.rotation.clone();
  43339. if (this.rotationQuaternion) {
  43340. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43341. }
  43342. return _super.prototype.storeState.call(this);
  43343. };
  43344. /**
  43345. * Restored camera state. You must call storeState() first
  43346. */
  43347. TargetCamera.prototype._restoreStateValues = function () {
  43348. if (!_super.prototype._restoreStateValues.call(this)) {
  43349. return false;
  43350. }
  43351. this.position = this._storedPosition.clone();
  43352. this.rotation = this._storedRotation.clone();
  43353. if (this.rotationQuaternion) {
  43354. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43355. }
  43356. this.cameraDirection.copyFromFloats(0, 0, 0);
  43357. this.cameraRotation.copyFromFloats(0, 0);
  43358. return true;
  43359. };
  43360. // Cache
  43361. TargetCamera.prototype._initCache = function () {
  43362. _super.prototype._initCache.call(this);
  43363. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43364. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43365. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43366. };
  43367. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43368. if (!ignoreParentClass) {
  43369. _super.prototype._updateCache.call(this);
  43370. }
  43371. var lockedTargetPosition = this._getLockedTargetPosition();
  43372. if (!lockedTargetPosition) {
  43373. this._cache.lockedTarget = null;
  43374. }
  43375. else {
  43376. if (!this._cache.lockedTarget) {
  43377. this._cache.lockedTarget = lockedTargetPosition.clone();
  43378. }
  43379. else {
  43380. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43381. }
  43382. }
  43383. this._cache.rotation.copyFrom(this.rotation);
  43384. if (this.rotationQuaternion)
  43385. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43386. };
  43387. // Synchronized
  43388. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43389. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43390. return false;
  43391. }
  43392. var lockedTargetPosition = this._getLockedTargetPosition();
  43393. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43394. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43395. };
  43396. // Methods
  43397. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43398. var engine = this.getEngine();
  43399. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43400. };
  43401. // Target
  43402. TargetCamera.prototype.setTarget = function (target) {
  43403. this.upVector.normalize();
  43404. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43405. this._camMatrix.invert();
  43406. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43407. var vDir = target.subtract(this.position);
  43408. if (vDir.x >= 0.0) {
  43409. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43410. }
  43411. else {
  43412. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43413. }
  43414. this.rotation.z = 0;
  43415. if (isNaN(this.rotation.x)) {
  43416. this.rotation.x = 0;
  43417. }
  43418. if (isNaN(this.rotation.y)) {
  43419. this.rotation.y = 0;
  43420. }
  43421. if (isNaN(this.rotation.z)) {
  43422. this.rotation.z = 0;
  43423. }
  43424. if (this.rotationQuaternion) {
  43425. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43426. }
  43427. };
  43428. /**
  43429. * Return the current target position of the camera. This value is expressed in local space.
  43430. */
  43431. TargetCamera.prototype.getTarget = function () {
  43432. return this._currentTarget;
  43433. };
  43434. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43435. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43436. };
  43437. TargetCamera.prototype._updatePosition = function () {
  43438. if (this.parent) {
  43439. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43440. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43441. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43442. return;
  43443. }
  43444. this.position.addInPlace(this.cameraDirection);
  43445. };
  43446. TargetCamera.prototype._checkInputs = function () {
  43447. var needToMove = this._decideIfNeedsToMove();
  43448. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43449. // Move
  43450. if (needToMove) {
  43451. this._updatePosition();
  43452. }
  43453. // Rotate
  43454. if (needToRotate) {
  43455. this.rotation.x += this.cameraRotation.x;
  43456. this.rotation.y += this.cameraRotation.y;
  43457. //rotate, if quaternion is set and rotation was used
  43458. if (this.rotationQuaternion) {
  43459. var len = this.rotation.lengthSquared();
  43460. if (len) {
  43461. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43462. }
  43463. }
  43464. if (!this.noRotationConstraint) {
  43465. var limit = (Math.PI / 2) * 0.95;
  43466. if (this.rotation.x > limit)
  43467. this.rotation.x = limit;
  43468. if (this.rotation.x < -limit)
  43469. this.rotation.x = -limit;
  43470. }
  43471. }
  43472. // Inertia
  43473. if (needToMove) {
  43474. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43475. this.cameraDirection.x = 0;
  43476. }
  43477. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43478. this.cameraDirection.y = 0;
  43479. }
  43480. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43481. this.cameraDirection.z = 0;
  43482. }
  43483. this.cameraDirection.scaleInPlace(this.inertia);
  43484. }
  43485. if (needToRotate) {
  43486. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43487. this.cameraRotation.x = 0;
  43488. }
  43489. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43490. this.cameraRotation.y = 0;
  43491. }
  43492. this.cameraRotation.scaleInPlace(this.inertia);
  43493. }
  43494. _super.prototype._checkInputs.call(this);
  43495. };
  43496. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43497. if (this.rotationQuaternion) {
  43498. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43499. }
  43500. else {
  43501. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43502. }
  43503. //update the up vector!
  43504. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43505. };
  43506. TargetCamera.prototype._getViewMatrix = function () {
  43507. if (this.lockedTarget) {
  43508. this.setTarget(this._getLockedTargetPosition());
  43509. }
  43510. // Compute
  43511. this._updateCameraRotationMatrix();
  43512. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43513. // Computing target and final matrix
  43514. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43515. if (this.getScene().useRightHandedSystem) {
  43516. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43517. }
  43518. else {
  43519. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43520. }
  43521. return this._viewMatrix;
  43522. };
  43523. /**
  43524. * @override
  43525. * Override Camera.createRigCamera
  43526. */
  43527. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43528. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43529. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43530. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43531. if (!this.rotationQuaternion) {
  43532. this.rotationQuaternion = new BABYLON.Quaternion();
  43533. }
  43534. rigCamera._cameraRigParams = {};
  43535. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43536. }
  43537. return rigCamera;
  43538. }
  43539. return null;
  43540. };
  43541. /**
  43542. * @override
  43543. * Override Camera._updateRigCameras
  43544. */
  43545. TargetCamera.prototype._updateRigCameras = function () {
  43546. var camLeft = this._rigCameras[0];
  43547. var camRight = this._rigCameras[1];
  43548. switch (this.cameraRigMode) {
  43549. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43550. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43551. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43552. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43553. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43554. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43555. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43556. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43557. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43558. camLeft.setTarget(this.getTarget());
  43559. camRight.setTarget(this.getTarget());
  43560. break;
  43561. case BABYLON.Camera.RIG_MODE_VR:
  43562. if (camLeft.rotationQuaternion) {
  43563. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43564. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43565. }
  43566. else {
  43567. camLeft.rotation.copyFrom(this.rotation);
  43568. camRight.rotation.copyFrom(this.rotation);
  43569. }
  43570. camLeft.position.copyFrom(this.position);
  43571. camRight.position.copyFrom(this.position);
  43572. break;
  43573. }
  43574. _super.prototype._updateRigCameras.call(this);
  43575. };
  43576. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43577. if (!this._rigCamTransformMatrix) {
  43578. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43579. }
  43580. var target = this.getTarget();
  43581. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43582. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43583. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43584. };
  43585. TargetCamera.prototype.getClassName = function () {
  43586. return "TargetCamera";
  43587. };
  43588. __decorate([
  43589. BABYLON.serializeAsVector3()
  43590. ], TargetCamera.prototype, "rotation", void 0);
  43591. __decorate([
  43592. BABYLON.serialize()
  43593. ], TargetCamera.prototype, "speed", void 0);
  43594. __decorate([
  43595. BABYLON.serializeAsMeshReference("lockedTargetId")
  43596. ], TargetCamera.prototype, "lockedTarget", void 0);
  43597. return TargetCamera;
  43598. }(BABYLON.Camera));
  43599. BABYLON.TargetCamera = TargetCamera;
  43600. })(BABYLON || (BABYLON = {}));
  43601. //# sourceMappingURL=babylon.targetCamera.js.map
  43602. var BABYLON;
  43603. (function (BABYLON) {
  43604. var FreeCameraMouseInput = /** @class */ (function () {
  43605. function FreeCameraMouseInput(touchEnabled) {
  43606. if (touchEnabled === void 0) { touchEnabled = true; }
  43607. this.touchEnabled = touchEnabled;
  43608. this.buttons = [0, 1, 2];
  43609. this.angularSensibility = 2000.0;
  43610. this.previousPosition = null;
  43611. }
  43612. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43613. var _this = this;
  43614. var engine = this.camera.getEngine();
  43615. if (!this._pointerInput) {
  43616. this._pointerInput = function (p, s) {
  43617. var evt = p.event;
  43618. if (engine.isInVRExclusivePointerMode) {
  43619. return;
  43620. }
  43621. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43622. return;
  43623. }
  43624. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43625. return;
  43626. }
  43627. var srcElement = (evt.srcElement || evt.target);
  43628. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43629. try {
  43630. srcElement.setPointerCapture(evt.pointerId);
  43631. }
  43632. catch (e) {
  43633. //Nothing to do with the error. Execution will continue.
  43634. }
  43635. _this.previousPosition = {
  43636. x: evt.clientX,
  43637. y: evt.clientY
  43638. };
  43639. if (!noPreventDefault) {
  43640. evt.preventDefault();
  43641. element.focus();
  43642. }
  43643. }
  43644. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43645. try {
  43646. srcElement.releasePointerCapture(evt.pointerId);
  43647. }
  43648. catch (e) {
  43649. //Nothing to do with the error.
  43650. }
  43651. _this.previousPosition = null;
  43652. if (!noPreventDefault) {
  43653. evt.preventDefault();
  43654. }
  43655. }
  43656. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43657. if (!_this.previousPosition || engine.isPointerLock) {
  43658. return;
  43659. }
  43660. var offsetX = evt.clientX - _this.previousPosition.x;
  43661. var offsetY = evt.clientY - _this.previousPosition.y;
  43662. if (_this.camera.getScene().useRightHandedSystem) {
  43663. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43664. }
  43665. else {
  43666. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43667. }
  43668. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43669. _this.previousPosition = {
  43670. x: evt.clientX,
  43671. y: evt.clientY
  43672. };
  43673. if (!noPreventDefault) {
  43674. evt.preventDefault();
  43675. }
  43676. }
  43677. };
  43678. }
  43679. this._onMouseMove = function (evt) {
  43680. if (!engine.isPointerLock) {
  43681. return;
  43682. }
  43683. if (engine.isInVRExclusivePointerMode) {
  43684. return;
  43685. }
  43686. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43687. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43688. if (_this.camera.getScene().useRightHandedSystem) {
  43689. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43690. }
  43691. else {
  43692. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43693. }
  43694. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43695. _this.previousPosition = null;
  43696. if (!noPreventDefault) {
  43697. evt.preventDefault();
  43698. }
  43699. };
  43700. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43701. element.addEventListener("mousemove", this._onMouseMove, false);
  43702. };
  43703. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43704. if (this._observer && element) {
  43705. this.camera.getScene().onPointerObservable.remove(this._observer);
  43706. if (this._onMouseMove) {
  43707. element.removeEventListener("mousemove", this._onMouseMove);
  43708. }
  43709. this._observer = null;
  43710. this._onMouseMove = null;
  43711. this.previousPosition = null;
  43712. }
  43713. };
  43714. FreeCameraMouseInput.prototype.getClassName = function () {
  43715. return "FreeCameraMouseInput";
  43716. };
  43717. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43718. return "mouse";
  43719. };
  43720. __decorate([
  43721. BABYLON.serialize()
  43722. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43723. __decorate([
  43724. BABYLON.serialize()
  43725. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43726. return FreeCameraMouseInput;
  43727. }());
  43728. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43729. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43730. })(BABYLON || (BABYLON = {}));
  43731. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43732. var BABYLON;
  43733. (function (BABYLON) {
  43734. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43735. function FreeCameraKeyboardMoveInput() {
  43736. this._keys = new Array();
  43737. this.keysUp = [38];
  43738. this.keysDown = [40];
  43739. this.keysLeft = [37];
  43740. this.keysRight = [39];
  43741. }
  43742. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43743. var _this = this;
  43744. if (this._onCanvasBlurObserver) {
  43745. return;
  43746. }
  43747. this._scene = this.camera.getScene();
  43748. this._engine = this._scene.getEngine();
  43749. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43750. _this._keys = [];
  43751. });
  43752. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43753. var evt = info.event;
  43754. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43755. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43756. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43757. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43758. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43759. var index = _this._keys.indexOf(evt.keyCode);
  43760. if (index === -1) {
  43761. _this._keys.push(evt.keyCode);
  43762. }
  43763. if (!noPreventDefault) {
  43764. evt.preventDefault();
  43765. }
  43766. }
  43767. }
  43768. else {
  43769. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43770. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43771. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43772. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43773. var index = _this._keys.indexOf(evt.keyCode);
  43774. if (index >= 0) {
  43775. _this._keys.splice(index, 1);
  43776. }
  43777. if (!noPreventDefault) {
  43778. evt.preventDefault();
  43779. }
  43780. }
  43781. }
  43782. });
  43783. };
  43784. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43785. if (this._scene) {
  43786. if (this._onKeyboardObserver) {
  43787. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43788. }
  43789. if (this._onCanvasBlurObserver) {
  43790. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43791. }
  43792. this._onKeyboardObserver = null;
  43793. this._onCanvasBlurObserver = null;
  43794. }
  43795. this._keys = [];
  43796. };
  43797. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43798. if (this._onKeyboardObserver) {
  43799. var camera = this.camera;
  43800. // Keyboard
  43801. for (var index = 0; index < this._keys.length; index++) {
  43802. var keyCode = this._keys[index];
  43803. var speed = camera._computeLocalCameraSpeed();
  43804. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43805. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43806. }
  43807. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43808. camera._localDirection.copyFromFloats(0, 0, speed);
  43809. }
  43810. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43811. camera._localDirection.copyFromFloats(speed, 0, 0);
  43812. }
  43813. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43814. camera._localDirection.copyFromFloats(0, 0, -speed);
  43815. }
  43816. if (camera.getScene().useRightHandedSystem) {
  43817. camera._localDirection.z *= -1;
  43818. }
  43819. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43820. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43821. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43822. }
  43823. }
  43824. };
  43825. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43826. return "FreeCameraKeyboardMoveInput";
  43827. };
  43828. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43829. this._keys = [];
  43830. };
  43831. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43832. return "keyboard";
  43833. };
  43834. __decorate([
  43835. BABYLON.serialize()
  43836. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43837. __decorate([
  43838. BABYLON.serialize()
  43839. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43840. __decorate([
  43841. BABYLON.serialize()
  43842. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43843. __decorate([
  43844. BABYLON.serialize()
  43845. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43846. return FreeCameraKeyboardMoveInput;
  43847. }());
  43848. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43849. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43850. })(BABYLON || (BABYLON = {}));
  43851. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43852. var BABYLON;
  43853. (function (BABYLON) {
  43854. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43855. __extends(FreeCameraInputsManager, _super);
  43856. function FreeCameraInputsManager(camera) {
  43857. return _super.call(this, camera) || this;
  43858. }
  43859. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43860. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43861. return this;
  43862. };
  43863. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43864. if (touchEnabled === void 0) { touchEnabled = true; }
  43865. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43866. return this;
  43867. };
  43868. FreeCameraInputsManager.prototype.addGamepad = function () {
  43869. this.add(new BABYLON.FreeCameraGamepadInput());
  43870. return this;
  43871. };
  43872. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43873. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43874. return this;
  43875. };
  43876. FreeCameraInputsManager.prototype.addTouch = function () {
  43877. this.add(new BABYLON.FreeCameraTouchInput());
  43878. return this;
  43879. };
  43880. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43881. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43882. return this;
  43883. };
  43884. return FreeCameraInputsManager;
  43885. }(BABYLON.CameraInputsManager));
  43886. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43887. })(BABYLON || (BABYLON = {}));
  43888. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43889. var BABYLON;
  43890. (function (BABYLON) {
  43891. var FreeCamera = /** @class */ (function (_super) {
  43892. __extends(FreeCamera, _super);
  43893. function FreeCamera(name, position, scene) {
  43894. var _this = _super.call(this, name, position, scene) || this;
  43895. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43896. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43897. _this.checkCollisions = false;
  43898. _this.applyGravity = false;
  43899. _this._needMoveForGravity = false;
  43900. _this._oldPosition = BABYLON.Vector3.Zero();
  43901. _this._diffPosition = BABYLON.Vector3.Zero();
  43902. _this._newPosition = BABYLON.Vector3.Zero();
  43903. // Collisions
  43904. _this._collisionMask = -1;
  43905. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43906. if (collidedMesh === void 0) { collidedMesh = null; }
  43907. //TODO move this to the collision coordinator!
  43908. if (_this.getScene().workerCollisions)
  43909. newPosition.multiplyInPlace(_this._collider._radius);
  43910. var updatePosition = function (newPos) {
  43911. _this._newPosition.copyFrom(newPos);
  43912. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43913. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43914. _this.position.addInPlace(_this._diffPosition);
  43915. if (_this.onCollide && collidedMesh) {
  43916. _this.onCollide(collidedMesh);
  43917. }
  43918. }
  43919. };
  43920. updatePosition(newPosition);
  43921. };
  43922. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43923. _this.inputs.addKeyboard().addMouse();
  43924. return _this;
  43925. }
  43926. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43927. //-- begin properties for backward compatibility for inputs
  43928. /**
  43929. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43930. * Higher values reduce sensitivity.
  43931. */
  43932. get: function () {
  43933. var mouse = this.inputs.attached["mouse"];
  43934. if (mouse)
  43935. return mouse.angularSensibility;
  43936. return 0;
  43937. },
  43938. /**
  43939. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43940. * Higher values reduce sensitivity.
  43941. */
  43942. set: function (value) {
  43943. var mouse = this.inputs.attached["mouse"];
  43944. if (mouse)
  43945. mouse.angularSensibility = value;
  43946. },
  43947. enumerable: true,
  43948. configurable: true
  43949. });
  43950. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43951. get: function () {
  43952. var keyboard = this.inputs.attached["keyboard"];
  43953. if (keyboard)
  43954. return keyboard.keysUp;
  43955. return [];
  43956. },
  43957. set: function (value) {
  43958. var keyboard = this.inputs.attached["keyboard"];
  43959. if (keyboard)
  43960. keyboard.keysUp = value;
  43961. },
  43962. enumerable: true,
  43963. configurable: true
  43964. });
  43965. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43966. get: function () {
  43967. var keyboard = this.inputs.attached["keyboard"];
  43968. if (keyboard)
  43969. return keyboard.keysDown;
  43970. return [];
  43971. },
  43972. set: function (value) {
  43973. var keyboard = this.inputs.attached["keyboard"];
  43974. if (keyboard)
  43975. keyboard.keysDown = value;
  43976. },
  43977. enumerable: true,
  43978. configurable: true
  43979. });
  43980. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43981. get: function () {
  43982. var keyboard = this.inputs.attached["keyboard"];
  43983. if (keyboard)
  43984. return keyboard.keysLeft;
  43985. return [];
  43986. },
  43987. set: function (value) {
  43988. var keyboard = this.inputs.attached["keyboard"];
  43989. if (keyboard)
  43990. keyboard.keysLeft = value;
  43991. },
  43992. enumerable: true,
  43993. configurable: true
  43994. });
  43995. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43996. get: function () {
  43997. var keyboard = this.inputs.attached["keyboard"];
  43998. if (keyboard)
  43999. return keyboard.keysRight;
  44000. return [];
  44001. },
  44002. set: function (value) {
  44003. var keyboard = this.inputs.attached["keyboard"];
  44004. if (keyboard)
  44005. keyboard.keysRight = value;
  44006. },
  44007. enumerable: true,
  44008. configurable: true
  44009. });
  44010. // Controls
  44011. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44012. this.inputs.attachElement(element, noPreventDefault);
  44013. };
  44014. FreeCamera.prototype.detachControl = function (element) {
  44015. this.inputs.detachElement(element);
  44016. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  44017. this.cameraRotation = new BABYLON.Vector2(0, 0);
  44018. };
  44019. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  44020. get: function () {
  44021. return this._collisionMask;
  44022. },
  44023. set: function (mask) {
  44024. this._collisionMask = !isNaN(mask) ? mask : -1;
  44025. },
  44026. enumerable: true,
  44027. configurable: true
  44028. });
  44029. FreeCamera.prototype._collideWithWorld = function (displacement) {
  44030. var globalPosition;
  44031. if (this.parent) {
  44032. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  44033. }
  44034. else {
  44035. globalPosition = this.position;
  44036. }
  44037. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  44038. this._oldPosition.addInPlace(this.ellipsoidOffset);
  44039. if (!this._collider) {
  44040. this._collider = new BABYLON.Collider();
  44041. }
  44042. this._collider._radius = this.ellipsoid;
  44043. this._collider.collisionMask = this._collisionMask;
  44044. //no need for clone, as long as gravity is not on.
  44045. var actualDisplacement = displacement;
  44046. //add gravity to the direction to prevent the dual-collision checking
  44047. if (this.applyGravity) {
  44048. //this prevents mending with cameraDirection, a global variable of the free camera class.
  44049. actualDisplacement = displacement.add(this.getScene().gravity);
  44050. }
  44051. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44052. };
  44053. FreeCamera.prototype._checkInputs = function () {
  44054. if (!this._localDirection) {
  44055. this._localDirection = BABYLON.Vector3.Zero();
  44056. this._transformedDirection = BABYLON.Vector3.Zero();
  44057. }
  44058. this.inputs.checkInputs();
  44059. _super.prototype._checkInputs.call(this);
  44060. };
  44061. FreeCamera.prototype._decideIfNeedsToMove = function () {
  44062. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  44063. };
  44064. FreeCamera.prototype._updatePosition = function () {
  44065. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  44066. this._collideWithWorld(this.cameraDirection);
  44067. }
  44068. else {
  44069. _super.prototype._updatePosition.call(this);
  44070. }
  44071. };
  44072. FreeCamera.prototype.dispose = function () {
  44073. this.inputs.clear();
  44074. _super.prototype.dispose.call(this);
  44075. };
  44076. FreeCamera.prototype.getClassName = function () {
  44077. return "FreeCamera";
  44078. };
  44079. __decorate([
  44080. BABYLON.serializeAsVector3()
  44081. ], FreeCamera.prototype, "ellipsoid", void 0);
  44082. __decorate([
  44083. BABYLON.serializeAsVector3()
  44084. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  44085. __decorate([
  44086. BABYLON.serialize()
  44087. ], FreeCamera.prototype, "checkCollisions", void 0);
  44088. __decorate([
  44089. BABYLON.serialize()
  44090. ], FreeCamera.prototype, "applyGravity", void 0);
  44091. return FreeCamera;
  44092. }(BABYLON.TargetCamera));
  44093. BABYLON.FreeCamera = FreeCamera;
  44094. })(BABYLON || (BABYLON = {}));
  44095. //# sourceMappingURL=babylon.freeCamera.js.map
  44096. var BABYLON;
  44097. (function (BABYLON) {
  44098. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  44099. function ArcRotateCameraKeyboardMoveInput() {
  44100. this._keys = new Array();
  44101. this.keysUp = [38];
  44102. this.keysDown = [40];
  44103. this.keysLeft = [37];
  44104. this.keysRight = [39];
  44105. this.keysReset = [220];
  44106. this.panningSensibility = 50.0;
  44107. this.zoomingSensibility = 25.0;
  44108. this.useAltToZoom = true;
  44109. }
  44110. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44111. var _this = this;
  44112. if (this._onCanvasBlurObserver) {
  44113. return;
  44114. }
  44115. this._scene = this.camera.getScene();
  44116. this._engine = this._scene.getEngine();
  44117. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44118. _this._keys = [];
  44119. });
  44120. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44121. var evt = info.event;
  44122. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44123. _this._ctrlPressed = evt.ctrlKey;
  44124. _this._altPressed = evt.altKey;
  44125. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44126. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44127. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44128. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44129. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44130. var index = _this._keys.indexOf(evt.keyCode);
  44131. if (index === -1) {
  44132. _this._keys.push(evt.keyCode);
  44133. }
  44134. if (evt.preventDefault) {
  44135. if (!noPreventDefault) {
  44136. evt.preventDefault();
  44137. }
  44138. }
  44139. }
  44140. }
  44141. else {
  44142. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44143. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44144. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44145. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44146. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44147. var index = _this._keys.indexOf(evt.keyCode);
  44148. if (index >= 0) {
  44149. _this._keys.splice(index, 1);
  44150. }
  44151. if (evt.preventDefault) {
  44152. if (!noPreventDefault) {
  44153. evt.preventDefault();
  44154. }
  44155. }
  44156. }
  44157. }
  44158. });
  44159. };
  44160. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44161. if (this._scene) {
  44162. if (this._onKeyboardObserver) {
  44163. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44164. }
  44165. if (this._onCanvasBlurObserver) {
  44166. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44167. }
  44168. this._onKeyboardObserver = null;
  44169. this._onCanvasBlurObserver = null;
  44170. }
  44171. this._keys = [];
  44172. };
  44173. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44174. if (this._onKeyboardObserver) {
  44175. var camera = this.camera;
  44176. for (var index = 0; index < this._keys.length; index++) {
  44177. var keyCode = this._keys[index];
  44178. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44179. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44180. camera.inertialPanningX -= 1 / this.panningSensibility;
  44181. }
  44182. else {
  44183. camera.inertialAlphaOffset -= 0.01;
  44184. }
  44185. }
  44186. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44187. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44188. camera.inertialPanningY += 1 / this.panningSensibility;
  44189. }
  44190. else if (this._altPressed && this.useAltToZoom) {
  44191. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44192. }
  44193. else {
  44194. camera.inertialBetaOffset -= 0.01;
  44195. }
  44196. }
  44197. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44198. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44199. camera.inertialPanningX += 1 / this.panningSensibility;
  44200. }
  44201. else {
  44202. camera.inertialAlphaOffset += 0.01;
  44203. }
  44204. }
  44205. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44206. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44207. camera.inertialPanningY -= 1 / this.panningSensibility;
  44208. }
  44209. else if (this._altPressed && this.useAltToZoom) {
  44210. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44211. }
  44212. else {
  44213. camera.inertialBetaOffset += 0.01;
  44214. }
  44215. }
  44216. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44217. camera.restoreState();
  44218. }
  44219. }
  44220. }
  44221. };
  44222. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44223. return "ArcRotateCameraKeyboardMoveInput";
  44224. };
  44225. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44226. return "keyboard";
  44227. };
  44228. __decorate([
  44229. BABYLON.serialize()
  44230. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44231. __decorate([
  44232. BABYLON.serialize()
  44233. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44234. __decorate([
  44235. BABYLON.serialize()
  44236. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44237. __decorate([
  44238. BABYLON.serialize()
  44239. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44240. __decorate([
  44241. BABYLON.serialize()
  44242. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44243. __decorate([
  44244. BABYLON.serialize()
  44245. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44246. __decorate([
  44247. BABYLON.serialize()
  44248. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44249. __decorate([
  44250. BABYLON.serialize()
  44251. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44252. return ArcRotateCameraKeyboardMoveInput;
  44253. }());
  44254. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44255. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44256. })(BABYLON || (BABYLON = {}));
  44257. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44258. var BABYLON;
  44259. (function (BABYLON) {
  44260. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44261. function ArcRotateCameraMouseWheelInput() {
  44262. this.wheelPrecision = 3.0;
  44263. /**
  44264. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44265. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44266. */
  44267. this.wheelDeltaPercentage = 0;
  44268. }
  44269. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44270. var _this = this;
  44271. this._wheel = function (p, s) {
  44272. //sanity check - this should be a PointerWheel event.
  44273. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44274. return;
  44275. var event = p.event;
  44276. var delta = 0;
  44277. if (event.wheelDelta) {
  44278. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  44279. }
  44280. else if (event.detail) {
  44281. delta = -event.detail / _this.wheelPrecision;
  44282. }
  44283. if (delta)
  44284. _this.camera.inertialRadiusOffset += delta;
  44285. if (event.preventDefault) {
  44286. if (!noPreventDefault) {
  44287. event.preventDefault();
  44288. }
  44289. }
  44290. };
  44291. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44292. };
  44293. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44294. if (this._observer && element) {
  44295. this.camera.getScene().onPointerObservable.remove(this._observer);
  44296. this._observer = null;
  44297. this._wheel = null;
  44298. }
  44299. };
  44300. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44301. return "ArcRotateCameraMouseWheelInput";
  44302. };
  44303. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44304. return "mousewheel";
  44305. };
  44306. __decorate([
  44307. BABYLON.serialize()
  44308. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44309. __decorate([
  44310. BABYLON.serialize()
  44311. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44312. return ArcRotateCameraMouseWheelInput;
  44313. }());
  44314. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44315. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44316. })(BABYLON || (BABYLON = {}));
  44317. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44318. var BABYLON;
  44319. (function (BABYLON) {
  44320. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44321. function ArcRotateCameraPointersInput() {
  44322. this.buttons = [0, 1, 2];
  44323. this.angularSensibilityX = 1000.0;
  44324. this.angularSensibilityY = 1000.0;
  44325. this.pinchPrecision = 12.0;
  44326. /**
  44327. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44328. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44329. */
  44330. this.pinchDeltaPercentage = 0;
  44331. this.panningSensibility = 1000.0;
  44332. this.multiTouchPanning = true;
  44333. this.multiTouchPanAndZoom = true;
  44334. this._isPanClick = false;
  44335. this.pinchInwards = true;
  44336. }
  44337. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44338. var _this = this;
  44339. var engine = this.camera.getEngine();
  44340. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44341. var pointA = null;
  44342. var pointB = null;
  44343. var previousPinchSquaredDistance = 0;
  44344. var initialDistance = 0;
  44345. var twoFingerActivityCount = 0;
  44346. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44347. this._pointerInput = function (p, s) {
  44348. var evt = p.event;
  44349. var isTouch = p.event.pointerType === "touch";
  44350. if (engine.isInVRExclusivePointerMode) {
  44351. return;
  44352. }
  44353. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44354. return;
  44355. }
  44356. var srcElement = (evt.srcElement || evt.target);
  44357. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44358. try {
  44359. srcElement.setPointerCapture(evt.pointerId);
  44360. }
  44361. catch (e) {
  44362. //Nothing to do with the error. Execution will continue.
  44363. }
  44364. // Manage panning with pan button click
  44365. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44366. // manage pointers
  44367. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44368. if (pointA === null) {
  44369. pointA = cacheSoloPointer;
  44370. }
  44371. else if (pointB === null) {
  44372. pointB = cacheSoloPointer;
  44373. }
  44374. if (!noPreventDefault) {
  44375. evt.preventDefault();
  44376. element.focus();
  44377. }
  44378. }
  44379. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44380. _this.camera.restoreState();
  44381. }
  44382. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44383. try {
  44384. srcElement.releasePointerCapture(evt.pointerId);
  44385. }
  44386. catch (e) {
  44387. //Nothing to do with the error.
  44388. }
  44389. cacheSoloPointer = null;
  44390. previousPinchSquaredDistance = 0;
  44391. previousMultiTouchPanPosition.isPaning = false;
  44392. previousMultiTouchPanPosition.isPinching = false;
  44393. twoFingerActivityCount = 0;
  44394. initialDistance = 0;
  44395. if (!isTouch) {
  44396. pointB = null; // Mouse and pen are mono pointer
  44397. }
  44398. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44399. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44400. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44401. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44402. if (engine.badOS) {
  44403. pointA = pointB = null;
  44404. }
  44405. else {
  44406. //only remove the impacted pointer in case of multitouch allowing on most
  44407. //platforms switching from rotate to zoom and pan seamlessly.
  44408. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44409. pointA = pointB;
  44410. pointB = null;
  44411. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44412. }
  44413. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44414. pointB = null;
  44415. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44416. }
  44417. else {
  44418. pointA = pointB = null;
  44419. }
  44420. }
  44421. if (!noPreventDefault) {
  44422. evt.preventDefault();
  44423. }
  44424. }
  44425. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44426. if (!noPreventDefault) {
  44427. evt.preventDefault();
  44428. }
  44429. // One button down
  44430. if (pointA && pointB === null && cacheSoloPointer) {
  44431. if (_this.panningSensibility !== 0 &&
  44432. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44433. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44434. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44435. }
  44436. else {
  44437. var offsetX = evt.clientX - cacheSoloPointer.x;
  44438. var offsetY = evt.clientY - cacheSoloPointer.y;
  44439. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44440. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44441. }
  44442. cacheSoloPointer.x = evt.clientX;
  44443. cacheSoloPointer.y = evt.clientY;
  44444. }
  44445. else if (pointA && pointB) {
  44446. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44447. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44448. ed.x = evt.clientX;
  44449. ed.y = evt.clientY;
  44450. var direction = _this.pinchInwards ? 1 : -1;
  44451. var distX = pointA.x - pointB.x;
  44452. var distY = pointA.y - pointB.y;
  44453. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44454. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44455. if (previousPinchSquaredDistance === 0) {
  44456. initialDistance = pinchDistance;
  44457. previousPinchSquaredDistance = pinchSquaredDistance;
  44458. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44459. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44460. return;
  44461. }
  44462. if (_this.multiTouchPanAndZoom) {
  44463. if (_this.pinchDeltaPercentage) {
  44464. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44465. }
  44466. else {
  44467. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44468. (_this.pinchPrecision *
  44469. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44470. direction);
  44471. }
  44472. if (_this.panningSensibility !== 0) {
  44473. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44474. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44475. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44476. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44477. previousMultiTouchPanPosition.x = pointersCenterX;
  44478. previousMultiTouchPanPosition.y = pointersCenterY;
  44479. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44480. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44481. }
  44482. }
  44483. else {
  44484. twoFingerActivityCount++;
  44485. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44486. if (_this.pinchDeltaPercentage) {
  44487. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44488. }
  44489. else {
  44490. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44491. (_this.pinchPrecision *
  44492. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44493. direction);
  44494. }
  44495. previousMultiTouchPanPosition.isPaning = false;
  44496. previousMultiTouchPanPosition.isPinching = true;
  44497. }
  44498. else {
  44499. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44500. if (!previousMultiTouchPanPosition.isPaning) {
  44501. previousMultiTouchPanPosition.isPaning = true;
  44502. previousMultiTouchPanPosition.isPinching = false;
  44503. previousMultiTouchPanPosition.x = ed.x;
  44504. previousMultiTouchPanPosition.y = ed.y;
  44505. return;
  44506. }
  44507. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44508. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44509. }
  44510. }
  44511. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44512. previousMultiTouchPanPosition.x = ed.x;
  44513. previousMultiTouchPanPosition.y = ed.y;
  44514. }
  44515. }
  44516. previousPinchSquaredDistance = pinchSquaredDistance;
  44517. }
  44518. }
  44519. };
  44520. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44521. this._onContextMenu = function (evt) {
  44522. evt.preventDefault();
  44523. };
  44524. if (!this.camera._useCtrlForPanning) {
  44525. element.addEventListener("contextmenu", this._onContextMenu, false);
  44526. }
  44527. this._onLostFocus = function () {
  44528. //this._keys = [];
  44529. pointA = pointB = null;
  44530. previousPinchSquaredDistance = 0;
  44531. previousMultiTouchPanPosition.isPaning = false;
  44532. previousMultiTouchPanPosition.isPinching = false;
  44533. twoFingerActivityCount = 0;
  44534. cacheSoloPointer = null;
  44535. initialDistance = 0;
  44536. };
  44537. this._onMouseMove = function (evt) {
  44538. if (!engine.isPointerLock) {
  44539. return;
  44540. }
  44541. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44542. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44543. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44544. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44545. if (!noPreventDefault) {
  44546. evt.preventDefault();
  44547. }
  44548. };
  44549. this._onGestureStart = function (e) {
  44550. if (window.MSGesture === undefined) {
  44551. return;
  44552. }
  44553. if (!_this._MSGestureHandler) {
  44554. _this._MSGestureHandler = new MSGesture();
  44555. _this._MSGestureHandler.target = element;
  44556. }
  44557. _this._MSGestureHandler.addPointer(e.pointerId);
  44558. };
  44559. this._onGesture = function (e) {
  44560. _this.camera.radius *= e.scale;
  44561. if (e.preventDefault) {
  44562. if (!noPreventDefault) {
  44563. e.stopPropagation();
  44564. e.preventDefault();
  44565. }
  44566. }
  44567. };
  44568. element.addEventListener("mousemove", this._onMouseMove, false);
  44569. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44570. element.addEventListener("MSGestureChange", this._onGesture, false);
  44571. BABYLON.Tools.RegisterTopRootEvents([
  44572. { name: "blur", handler: this._onLostFocus }
  44573. ]);
  44574. };
  44575. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44576. if (this._onLostFocus) {
  44577. BABYLON.Tools.UnregisterTopRootEvents([
  44578. { name: "blur", handler: this._onLostFocus }
  44579. ]);
  44580. }
  44581. if (element && this._observer) {
  44582. this.camera.getScene().onPointerObservable.remove(this._observer);
  44583. this._observer = null;
  44584. if (this._onContextMenu) {
  44585. element.removeEventListener("contextmenu", this._onContextMenu);
  44586. }
  44587. if (this._onMouseMove) {
  44588. element.removeEventListener("mousemove", this._onMouseMove);
  44589. }
  44590. if (this._onGestureStart) {
  44591. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44592. }
  44593. if (this._onGesture) {
  44594. element.removeEventListener("MSGestureChange", this._onGesture);
  44595. }
  44596. this._isPanClick = false;
  44597. this.pinchInwards = true;
  44598. this._onMouseMove = null;
  44599. this._onGestureStart = null;
  44600. this._onGesture = null;
  44601. this._MSGestureHandler = null;
  44602. this._onLostFocus = null;
  44603. this._onContextMenu = null;
  44604. }
  44605. };
  44606. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44607. return "ArcRotateCameraPointersInput";
  44608. };
  44609. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44610. return "pointers";
  44611. };
  44612. __decorate([
  44613. BABYLON.serialize()
  44614. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44615. __decorate([
  44616. BABYLON.serialize()
  44617. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44618. __decorate([
  44619. BABYLON.serialize()
  44620. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44621. __decorate([
  44622. BABYLON.serialize()
  44623. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44624. __decorate([
  44625. BABYLON.serialize()
  44626. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44627. __decorate([
  44628. BABYLON.serialize()
  44629. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44630. __decorate([
  44631. BABYLON.serialize()
  44632. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44633. __decorate([
  44634. BABYLON.serialize()
  44635. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44636. return ArcRotateCameraPointersInput;
  44637. }());
  44638. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44639. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44640. })(BABYLON || (BABYLON = {}));
  44641. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44642. var BABYLON;
  44643. (function (BABYLON) {
  44644. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44645. __extends(ArcRotateCameraInputsManager, _super);
  44646. function ArcRotateCameraInputsManager(camera) {
  44647. return _super.call(this, camera) || this;
  44648. }
  44649. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44650. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44651. return this;
  44652. };
  44653. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44654. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44655. return this;
  44656. };
  44657. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44658. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44659. return this;
  44660. };
  44661. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44662. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44663. return this;
  44664. };
  44665. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44666. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44667. return this;
  44668. };
  44669. return ArcRotateCameraInputsManager;
  44670. }(BABYLON.CameraInputsManager));
  44671. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44672. })(BABYLON || (BABYLON = {}));
  44673. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44674. var BABYLON;
  44675. (function (BABYLON) {
  44676. var ArcRotateCamera = /** @class */ (function (_super) {
  44677. __extends(ArcRotateCamera, _super);
  44678. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44679. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44680. _this.inertialAlphaOffset = 0;
  44681. _this.inertialBetaOffset = 0;
  44682. _this.inertialRadiusOffset = 0;
  44683. _this.lowerAlphaLimit = null;
  44684. _this.upperAlphaLimit = null;
  44685. _this.lowerBetaLimit = 0.01;
  44686. _this.upperBetaLimit = Math.PI;
  44687. _this.lowerRadiusLimit = null;
  44688. _this.upperRadiusLimit = null;
  44689. _this.inertialPanningX = 0;
  44690. _this.inertialPanningY = 0;
  44691. _this.pinchToPanMaxDistance = 20;
  44692. _this.panningDistanceLimit = null;
  44693. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44694. _this.panningInertia = 0.9;
  44695. //-- end properties for backward compatibility for inputs
  44696. _this.zoomOnFactor = 1;
  44697. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44698. _this.allowUpsideDown = true;
  44699. _this._viewMatrix = new BABYLON.Matrix();
  44700. // Panning
  44701. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44702. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44703. _this.checkCollisions = false;
  44704. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44705. _this._previousPosition = BABYLON.Vector3.Zero();
  44706. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44707. _this._newPosition = BABYLON.Vector3.Zero();
  44708. _this._computationVector = BABYLON.Vector3.Zero();
  44709. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44710. if (collidedMesh === void 0) { collidedMesh = null; }
  44711. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44712. newPosition.multiplyInPlace(_this._collider._radius);
  44713. }
  44714. if (!collidedMesh) {
  44715. _this._previousPosition.copyFrom(_this.position);
  44716. }
  44717. else {
  44718. _this.setPosition(newPosition);
  44719. if (_this.onCollide) {
  44720. _this.onCollide(collidedMesh);
  44721. }
  44722. }
  44723. // Recompute because of constraints
  44724. var cosa = Math.cos(_this.alpha);
  44725. var sina = Math.sin(_this.alpha);
  44726. var cosb = Math.cos(_this.beta);
  44727. var sinb = Math.sin(_this.beta);
  44728. if (sinb === 0) {
  44729. sinb = 0.0001;
  44730. }
  44731. var target = _this._getTargetPosition();
  44732. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  44733. target.addToRef(_this._computationVector, _this._newPosition);
  44734. _this.position.copyFrom(_this._newPosition);
  44735. var up = _this.upVector;
  44736. if (_this.allowUpsideDown && _this.beta < 0) {
  44737. up = up.clone();
  44738. up = up.negate();
  44739. }
  44740. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44741. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44742. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44743. _this._collisionTriggered = false;
  44744. };
  44745. _this._target = BABYLON.Vector3.Zero();
  44746. if (target) {
  44747. _this.setTarget(target);
  44748. }
  44749. _this.alpha = alpha;
  44750. _this.beta = beta;
  44751. _this.radius = radius;
  44752. _this.getViewMatrix();
  44753. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44754. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44755. return _this;
  44756. }
  44757. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44758. get: function () {
  44759. return this._target;
  44760. },
  44761. set: function (value) {
  44762. this.setTarget(value);
  44763. },
  44764. enumerable: true,
  44765. configurable: true
  44766. });
  44767. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44768. //-- begin properties for backward compatibility for inputs
  44769. get: function () {
  44770. var pointers = this.inputs.attached["pointers"];
  44771. if (pointers)
  44772. return pointers.angularSensibilityX;
  44773. return 0;
  44774. },
  44775. set: function (value) {
  44776. var pointers = this.inputs.attached["pointers"];
  44777. if (pointers) {
  44778. pointers.angularSensibilityX = value;
  44779. }
  44780. },
  44781. enumerable: true,
  44782. configurable: true
  44783. });
  44784. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44785. get: function () {
  44786. var pointers = this.inputs.attached["pointers"];
  44787. if (pointers)
  44788. return pointers.angularSensibilityY;
  44789. return 0;
  44790. },
  44791. set: function (value) {
  44792. var pointers = this.inputs.attached["pointers"];
  44793. if (pointers) {
  44794. pointers.angularSensibilityY = value;
  44795. }
  44796. },
  44797. enumerable: true,
  44798. configurable: true
  44799. });
  44800. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44801. get: function () {
  44802. var pointers = this.inputs.attached["pointers"];
  44803. if (pointers)
  44804. return pointers.pinchPrecision;
  44805. return 0;
  44806. },
  44807. set: function (value) {
  44808. var pointers = this.inputs.attached["pointers"];
  44809. if (pointers) {
  44810. pointers.pinchPrecision = value;
  44811. }
  44812. },
  44813. enumerable: true,
  44814. configurable: true
  44815. });
  44816. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44817. get: function () {
  44818. var pointers = this.inputs.attached["pointers"];
  44819. if (pointers)
  44820. return pointers.pinchDeltaPercentage;
  44821. return 0;
  44822. },
  44823. set: function (value) {
  44824. var pointers = this.inputs.attached["pointers"];
  44825. if (pointers) {
  44826. pointers.pinchDeltaPercentage = value;
  44827. }
  44828. },
  44829. enumerable: true,
  44830. configurable: true
  44831. });
  44832. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44833. get: function () {
  44834. var pointers = this.inputs.attached["pointers"];
  44835. if (pointers)
  44836. return pointers.panningSensibility;
  44837. return 0;
  44838. },
  44839. set: function (value) {
  44840. var pointers = this.inputs.attached["pointers"];
  44841. if (pointers) {
  44842. pointers.panningSensibility = value;
  44843. }
  44844. },
  44845. enumerable: true,
  44846. configurable: true
  44847. });
  44848. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44849. get: function () {
  44850. var keyboard = this.inputs.attached["keyboard"];
  44851. if (keyboard)
  44852. return keyboard.keysUp;
  44853. return [];
  44854. },
  44855. set: function (value) {
  44856. var keyboard = this.inputs.attached["keyboard"];
  44857. if (keyboard)
  44858. keyboard.keysUp = value;
  44859. },
  44860. enumerable: true,
  44861. configurable: true
  44862. });
  44863. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44864. get: function () {
  44865. var keyboard = this.inputs.attached["keyboard"];
  44866. if (keyboard)
  44867. return keyboard.keysDown;
  44868. return [];
  44869. },
  44870. set: function (value) {
  44871. var keyboard = this.inputs.attached["keyboard"];
  44872. if (keyboard)
  44873. keyboard.keysDown = value;
  44874. },
  44875. enumerable: true,
  44876. configurable: true
  44877. });
  44878. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44879. get: function () {
  44880. var keyboard = this.inputs.attached["keyboard"];
  44881. if (keyboard)
  44882. return keyboard.keysLeft;
  44883. return [];
  44884. },
  44885. set: function (value) {
  44886. var keyboard = this.inputs.attached["keyboard"];
  44887. if (keyboard)
  44888. keyboard.keysLeft = value;
  44889. },
  44890. enumerable: true,
  44891. configurable: true
  44892. });
  44893. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44894. get: function () {
  44895. var keyboard = this.inputs.attached["keyboard"];
  44896. if (keyboard)
  44897. return keyboard.keysRight;
  44898. return [];
  44899. },
  44900. set: function (value) {
  44901. var keyboard = this.inputs.attached["keyboard"];
  44902. if (keyboard)
  44903. keyboard.keysRight = value;
  44904. },
  44905. enumerable: true,
  44906. configurable: true
  44907. });
  44908. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44909. get: function () {
  44910. var mousewheel = this.inputs.attached["mousewheel"];
  44911. if (mousewheel)
  44912. return mousewheel.wheelPrecision;
  44913. return 0;
  44914. },
  44915. set: function (value) {
  44916. var mousewheel = this.inputs.attached["mousewheel"];
  44917. if (mousewheel)
  44918. mousewheel.wheelPrecision = value;
  44919. },
  44920. enumerable: true,
  44921. configurable: true
  44922. });
  44923. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44924. get: function () {
  44925. var mousewheel = this.inputs.attached["mousewheel"];
  44926. if (mousewheel)
  44927. return mousewheel.wheelDeltaPercentage;
  44928. return 0;
  44929. },
  44930. set: function (value) {
  44931. var mousewheel = this.inputs.attached["mousewheel"];
  44932. if (mousewheel)
  44933. mousewheel.wheelDeltaPercentage = value;
  44934. },
  44935. enumerable: true,
  44936. configurable: true
  44937. });
  44938. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44939. get: function () {
  44940. return this._bouncingBehavior;
  44941. },
  44942. enumerable: true,
  44943. configurable: true
  44944. });
  44945. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44946. get: function () {
  44947. return this._bouncingBehavior != null;
  44948. },
  44949. set: function (value) {
  44950. if (value === this.useBouncingBehavior) {
  44951. return;
  44952. }
  44953. if (value) {
  44954. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44955. this.addBehavior(this._bouncingBehavior);
  44956. }
  44957. else if (this._bouncingBehavior) {
  44958. this.removeBehavior(this._bouncingBehavior);
  44959. this._bouncingBehavior = null;
  44960. }
  44961. },
  44962. enumerable: true,
  44963. configurable: true
  44964. });
  44965. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44966. get: function () {
  44967. return this._framingBehavior;
  44968. },
  44969. enumerable: true,
  44970. configurable: true
  44971. });
  44972. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44973. get: function () {
  44974. return this._framingBehavior != null;
  44975. },
  44976. set: function (value) {
  44977. if (value === this.useFramingBehavior) {
  44978. return;
  44979. }
  44980. if (value) {
  44981. this._framingBehavior = new BABYLON.FramingBehavior();
  44982. this.addBehavior(this._framingBehavior);
  44983. }
  44984. else if (this._framingBehavior) {
  44985. this.removeBehavior(this._framingBehavior);
  44986. this._framingBehavior = null;
  44987. }
  44988. },
  44989. enumerable: true,
  44990. configurable: true
  44991. });
  44992. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44993. get: function () {
  44994. return this._autoRotationBehavior;
  44995. },
  44996. enumerable: true,
  44997. configurable: true
  44998. });
  44999. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  45000. get: function () {
  45001. return this._autoRotationBehavior != null;
  45002. },
  45003. set: function (value) {
  45004. if (value === this.useAutoRotationBehavior) {
  45005. return;
  45006. }
  45007. if (value) {
  45008. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  45009. this.addBehavior(this._autoRotationBehavior);
  45010. }
  45011. else if (this._autoRotationBehavior) {
  45012. this.removeBehavior(this._autoRotationBehavior);
  45013. this._autoRotationBehavior = null;
  45014. }
  45015. },
  45016. enumerable: true,
  45017. configurable: true
  45018. });
  45019. // Cache
  45020. ArcRotateCamera.prototype._initCache = function () {
  45021. _super.prototype._initCache.call(this);
  45022. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45023. this._cache.alpha = undefined;
  45024. this._cache.beta = undefined;
  45025. this._cache.radius = undefined;
  45026. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  45027. };
  45028. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  45029. if (!ignoreParentClass) {
  45030. _super.prototype._updateCache.call(this);
  45031. }
  45032. this._cache._target.copyFrom(this._getTargetPosition());
  45033. this._cache.alpha = this.alpha;
  45034. this._cache.beta = this.beta;
  45035. this._cache.radius = this.radius;
  45036. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  45037. };
  45038. ArcRotateCamera.prototype._getTargetPosition = function () {
  45039. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  45040. var pos = this._targetHost.getAbsolutePosition();
  45041. if (this._targetBoundingCenter) {
  45042. pos.addToRef(this._targetBoundingCenter, this._target);
  45043. }
  45044. else {
  45045. this._target.copyFrom(pos);
  45046. }
  45047. }
  45048. var lockedTargetPosition = this._getLockedTargetPosition();
  45049. if (lockedTargetPosition) {
  45050. return lockedTargetPosition;
  45051. }
  45052. return this._target;
  45053. };
  45054. ArcRotateCamera.prototype.storeState = function () {
  45055. this._storedAlpha = this.alpha;
  45056. this._storedBeta = this.beta;
  45057. this._storedRadius = this.radius;
  45058. this._storedTarget = this._getTargetPosition().clone();
  45059. return _super.prototype.storeState.call(this);
  45060. };
  45061. /**
  45062. * Restored camera state. You must call storeState() first
  45063. */
  45064. ArcRotateCamera.prototype._restoreStateValues = function () {
  45065. if (!_super.prototype._restoreStateValues.call(this)) {
  45066. return false;
  45067. }
  45068. this.alpha = this._storedAlpha;
  45069. this.beta = this._storedBeta;
  45070. this.radius = this._storedRadius;
  45071. this.setTarget(this._storedTarget.clone());
  45072. this.inertialAlphaOffset = 0;
  45073. this.inertialBetaOffset = 0;
  45074. this.inertialRadiusOffset = 0;
  45075. this.inertialPanningX = 0;
  45076. this.inertialPanningY = 0;
  45077. return true;
  45078. };
  45079. // Synchronized
  45080. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  45081. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  45082. return false;
  45083. return this._cache._target.equals(this._getTargetPosition())
  45084. && this._cache.alpha === this.alpha
  45085. && this._cache.beta === this.beta
  45086. && this._cache.radius === this.radius
  45087. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  45088. };
  45089. // Methods
  45090. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  45091. var _this = this;
  45092. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  45093. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  45094. this._useCtrlForPanning = useCtrlForPanning;
  45095. this._panningMouseButton = panningMouseButton;
  45096. this.inputs.attachElement(element, noPreventDefault);
  45097. this._reset = function () {
  45098. _this.inertialAlphaOffset = 0;
  45099. _this.inertialBetaOffset = 0;
  45100. _this.inertialRadiusOffset = 0;
  45101. _this.inertialPanningX = 0;
  45102. _this.inertialPanningY = 0;
  45103. };
  45104. };
  45105. ArcRotateCamera.prototype.detachControl = function (element) {
  45106. this.inputs.detachElement(element);
  45107. if (this._reset) {
  45108. this._reset();
  45109. }
  45110. };
  45111. ArcRotateCamera.prototype._checkInputs = function () {
  45112. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  45113. if (this._collisionTriggered) {
  45114. return;
  45115. }
  45116. this.inputs.checkInputs();
  45117. // Inertia
  45118. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  45119. if (this.getScene().useRightHandedSystem) {
  45120. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45121. }
  45122. else {
  45123. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45124. }
  45125. this.beta += this.inertialBetaOffset;
  45126. this.radius -= this.inertialRadiusOffset;
  45127. this.inertialAlphaOffset *= this.inertia;
  45128. this.inertialBetaOffset *= this.inertia;
  45129. this.inertialRadiusOffset *= this.inertia;
  45130. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  45131. this.inertialAlphaOffset = 0;
  45132. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  45133. this.inertialBetaOffset = 0;
  45134. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  45135. this.inertialRadiusOffset = 0;
  45136. }
  45137. // Panning inertia
  45138. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  45139. if (!this._localDirection) {
  45140. this._localDirection = BABYLON.Vector3.Zero();
  45141. this._transformedDirection = BABYLON.Vector3.Zero();
  45142. }
  45143. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  45144. this._localDirection.multiplyInPlace(this.panningAxis);
  45145. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  45146. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  45147. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  45148. if (!this.panningAxis.y) {
  45149. this._transformedDirection.y = 0;
  45150. }
  45151. if (!this._targetHost) {
  45152. if (this.panningDistanceLimit) {
  45153. this._transformedDirection.addInPlace(this._target);
  45154. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  45155. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  45156. this._target.copyFrom(this._transformedDirection);
  45157. }
  45158. }
  45159. else {
  45160. this._target.addInPlace(this._transformedDirection);
  45161. }
  45162. }
  45163. this.inertialPanningX *= this.panningInertia;
  45164. this.inertialPanningY *= this.panningInertia;
  45165. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  45166. this.inertialPanningX = 0;
  45167. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  45168. this.inertialPanningY = 0;
  45169. }
  45170. // Limits
  45171. this._checkLimits();
  45172. _super.prototype._checkInputs.call(this);
  45173. };
  45174. ArcRotateCamera.prototype._checkLimits = function () {
  45175. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45176. if (this.allowUpsideDown && this.beta > Math.PI) {
  45177. this.beta = this.beta - (2 * Math.PI);
  45178. }
  45179. }
  45180. else {
  45181. if (this.beta < this.lowerBetaLimit) {
  45182. this.beta = this.lowerBetaLimit;
  45183. }
  45184. }
  45185. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45186. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45187. this.beta = this.beta + (2 * Math.PI);
  45188. }
  45189. }
  45190. else {
  45191. if (this.beta > this.upperBetaLimit) {
  45192. this.beta = this.upperBetaLimit;
  45193. }
  45194. }
  45195. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45196. this.alpha = this.lowerAlphaLimit;
  45197. }
  45198. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45199. this.alpha = this.upperAlphaLimit;
  45200. }
  45201. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45202. this.radius = this.lowerRadiusLimit;
  45203. }
  45204. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45205. this.radius = this.upperRadiusLimit;
  45206. }
  45207. };
  45208. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45209. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45210. this.radius = this._computationVector.length();
  45211. if (this.radius === 0) {
  45212. this.radius = 0.0001; // Just to avoid division by zero
  45213. }
  45214. // Alpha
  45215. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45216. if (this._computationVector.z < 0) {
  45217. this.alpha = 2 * Math.PI - this.alpha;
  45218. }
  45219. // Beta
  45220. this.beta = Math.acos(this._computationVector.y / this.radius);
  45221. this._checkLimits();
  45222. };
  45223. ArcRotateCamera.prototype.setPosition = function (position) {
  45224. if (this.position.equals(position)) {
  45225. return;
  45226. }
  45227. this.position.copyFrom(position);
  45228. this.rebuildAnglesAndRadius();
  45229. };
  45230. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45231. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45232. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45233. if (target.getBoundingInfo) {
  45234. if (toBoundingCenter) {
  45235. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45236. }
  45237. else {
  45238. this._targetBoundingCenter = null;
  45239. }
  45240. this._targetHost = target;
  45241. this._target = this._getTargetPosition();
  45242. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45243. }
  45244. else {
  45245. var newTarget = target;
  45246. var currentTarget = this._getTargetPosition();
  45247. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45248. return;
  45249. }
  45250. this._targetHost = null;
  45251. this._target = newTarget;
  45252. this._targetBoundingCenter = null;
  45253. this.onMeshTargetChangedObservable.notifyObservers(null);
  45254. }
  45255. this.rebuildAnglesAndRadius();
  45256. };
  45257. ArcRotateCamera.prototype._getViewMatrix = function () {
  45258. // Compute
  45259. var cosa = Math.cos(this.alpha);
  45260. var sina = Math.sin(this.alpha);
  45261. var cosb = Math.cos(this.beta);
  45262. var sinb = Math.sin(this.beta);
  45263. if (sinb === 0) {
  45264. sinb = 0.0001;
  45265. }
  45266. var target = this._getTargetPosition();
  45267. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45268. target.addToRef(this._computationVector, this._newPosition);
  45269. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45270. if (!this._collider) {
  45271. this._collider = new BABYLON.Collider();
  45272. }
  45273. this._collider._radius = this.collisionRadius;
  45274. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45275. this._collisionTriggered = true;
  45276. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45277. }
  45278. else {
  45279. this.position.copyFrom(this._newPosition);
  45280. var up = this.upVector;
  45281. if (this.allowUpsideDown && sinb < 0) {
  45282. up = up.clone();
  45283. up = up.negate();
  45284. }
  45285. if (this.getScene().useRightHandedSystem) {
  45286. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45287. }
  45288. else {
  45289. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45290. }
  45291. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45292. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45293. }
  45294. this._currentTarget = target;
  45295. return this._viewMatrix;
  45296. };
  45297. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45298. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45299. meshes = meshes || this.getScene().meshes;
  45300. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45301. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45302. this.radius = distance * this.zoomOnFactor;
  45303. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45304. };
  45305. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45306. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45307. var meshesOrMinMaxVector;
  45308. var distance;
  45309. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45310. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45311. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45312. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45313. }
  45314. else {
  45315. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45316. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45317. distance = minMaxVectorAndDistance.distance;
  45318. }
  45319. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45320. if (!doNotUpdateMaxZ) {
  45321. this.maxZ = distance * 2;
  45322. }
  45323. };
  45324. /**
  45325. * @override
  45326. * Override Camera.createRigCamera
  45327. */
  45328. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45329. var alphaShift = 0;
  45330. switch (this.cameraRigMode) {
  45331. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45332. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45333. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45334. case BABYLON.Camera.RIG_MODE_VR:
  45335. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45336. break;
  45337. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45338. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45339. break;
  45340. }
  45341. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45342. rigCam._cameraRigParams = {};
  45343. return rigCam;
  45344. };
  45345. /**
  45346. * @override
  45347. * Override Camera._updateRigCameras
  45348. */
  45349. ArcRotateCamera.prototype._updateRigCameras = function () {
  45350. var camLeft = this._rigCameras[0];
  45351. var camRight = this._rigCameras[1];
  45352. camLeft.beta = camRight.beta = this.beta;
  45353. camLeft.radius = camRight.radius = this.radius;
  45354. switch (this.cameraRigMode) {
  45355. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45356. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45357. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45358. case BABYLON.Camera.RIG_MODE_VR:
  45359. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45360. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45361. break;
  45362. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45363. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45364. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45365. break;
  45366. }
  45367. _super.prototype._updateRigCameras.call(this);
  45368. };
  45369. ArcRotateCamera.prototype.dispose = function () {
  45370. this.inputs.clear();
  45371. _super.prototype.dispose.call(this);
  45372. };
  45373. ArcRotateCamera.prototype.getClassName = function () {
  45374. return "ArcRotateCamera";
  45375. };
  45376. __decorate([
  45377. BABYLON.serialize()
  45378. ], ArcRotateCamera.prototype, "alpha", void 0);
  45379. __decorate([
  45380. BABYLON.serialize()
  45381. ], ArcRotateCamera.prototype, "beta", void 0);
  45382. __decorate([
  45383. BABYLON.serialize()
  45384. ], ArcRotateCamera.prototype, "radius", void 0);
  45385. __decorate([
  45386. BABYLON.serializeAsVector3("target")
  45387. ], ArcRotateCamera.prototype, "_target", void 0);
  45388. __decorate([
  45389. BABYLON.serialize()
  45390. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45391. __decorate([
  45392. BABYLON.serialize()
  45393. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45394. __decorate([
  45395. BABYLON.serialize()
  45396. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45397. __decorate([
  45398. BABYLON.serialize()
  45399. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45400. __decorate([
  45401. BABYLON.serialize()
  45402. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45403. __decorate([
  45404. BABYLON.serialize()
  45405. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45406. __decorate([
  45407. BABYLON.serialize()
  45408. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45409. __decorate([
  45410. BABYLON.serialize()
  45411. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45412. __decorate([
  45413. BABYLON.serialize()
  45414. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45415. __decorate([
  45416. BABYLON.serialize()
  45417. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45418. __decorate([
  45419. BABYLON.serialize()
  45420. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45421. __decorate([
  45422. BABYLON.serialize()
  45423. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45424. __decorate([
  45425. BABYLON.serialize()
  45426. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45427. __decorate([
  45428. BABYLON.serializeAsVector3()
  45429. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45430. __decorate([
  45431. BABYLON.serialize()
  45432. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45433. __decorate([
  45434. BABYLON.serialize()
  45435. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45436. __decorate([
  45437. BABYLON.serialize()
  45438. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45439. return ArcRotateCamera;
  45440. }(BABYLON.TargetCamera));
  45441. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45442. })(BABYLON || (BABYLON = {}));
  45443. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45444. var BABYLON;
  45445. (function (BABYLON) {
  45446. /**
  45447. * The HemisphericLight simulates the ambient environment light,
  45448. * so the passed direction is the light reflection direction, not the incoming direction.
  45449. */
  45450. var HemisphericLight = /** @class */ (function (_super) {
  45451. __extends(HemisphericLight, _super);
  45452. /**
  45453. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45454. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45455. * The HemisphericLight can't cast shadows.
  45456. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45457. * @param name The friendly name of the light
  45458. * @param direction The direction of the light reflection
  45459. * @param scene The scene the light belongs to
  45460. */
  45461. function HemisphericLight(name, direction, scene) {
  45462. var _this = _super.call(this, name, scene) || this;
  45463. /**
  45464. * The groundColor is the light in the opposite direction to the one specified during creation.
  45465. * 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.
  45466. */
  45467. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45468. _this.direction = direction || BABYLON.Vector3.Up();
  45469. return _this;
  45470. }
  45471. HemisphericLight.prototype._buildUniformLayout = function () {
  45472. this._uniformBuffer.addUniform("vLightData", 4);
  45473. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45474. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45475. this._uniformBuffer.addUniform("vLightGround", 3);
  45476. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45477. this._uniformBuffer.addUniform("depthValues", 2);
  45478. this._uniformBuffer.create();
  45479. };
  45480. /**
  45481. * Returns the string "HemisphericLight".
  45482. * @return The class name
  45483. */
  45484. HemisphericLight.prototype.getClassName = function () {
  45485. return "HemisphericLight";
  45486. };
  45487. /**
  45488. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45489. * Returns the updated direction.
  45490. * @param target The target the direction should point to
  45491. * @return The computed direction
  45492. */
  45493. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45494. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45495. return this.direction;
  45496. };
  45497. /**
  45498. * Returns the shadow generator associated to the light.
  45499. * @returns Always null for hemispheric lights because it does not support shadows.
  45500. */
  45501. HemisphericLight.prototype.getShadowGenerator = function () {
  45502. return null;
  45503. };
  45504. /**
  45505. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45506. * @param effect The effect to update
  45507. * @param lightIndex The index of the light in the effect to update
  45508. * @returns The hemispheric light
  45509. */
  45510. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45511. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45512. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45513. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45514. return this;
  45515. };
  45516. /**
  45517. * @ignore internal use only.
  45518. */
  45519. HemisphericLight.prototype._getWorldMatrix = function () {
  45520. if (!this._worldMatrix) {
  45521. this._worldMatrix = BABYLON.Matrix.Identity();
  45522. }
  45523. return this._worldMatrix;
  45524. };
  45525. /**
  45526. * Returns the integer 3.
  45527. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45528. */
  45529. HemisphericLight.prototype.getTypeID = function () {
  45530. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45531. };
  45532. __decorate([
  45533. BABYLON.serializeAsColor3()
  45534. ], HemisphericLight.prototype, "groundColor", void 0);
  45535. __decorate([
  45536. BABYLON.serializeAsVector3()
  45537. ], HemisphericLight.prototype, "direction", void 0);
  45538. return HemisphericLight;
  45539. }(BABYLON.Light));
  45540. BABYLON.HemisphericLight = HemisphericLight;
  45541. })(BABYLON || (BABYLON = {}));
  45542. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45543. var BABYLON;
  45544. (function (BABYLON) {
  45545. /**
  45546. * Base implementation of @see IShadowLight
  45547. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45548. */
  45549. var ShadowLight = /** @class */ (function (_super) {
  45550. __extends(ShadowLight, _super);
  45551. function ShadowLight() {
  45552. var _this = _super !== null && _super.apply(this, arguments) || this;
  45553. _this._needProjectionMatrixCompute = true;
  45554. return _this;
  45555. }
  45556. ShadowLight.prototype._setPosition = function (value) {
  45557. this._position = value;
  45558. };
  45559. Object.defineProperty(ShadowLight.prototype, "position", {
  45560. /**
  45561. * Sets the position the shadow will be casted from. Also use as the light position for both
  45562. * point and spot lights.
  45563. */
  45564. get: function () {
  45565. return this._position;
  45566. },
  45567. /**
  45568. * Sets the position the shadow will be casted from. Also use as the light position for both
  45569. * point and spot lights.
  45570. */
  45571. set: function (value) {
  45572. this._setPosition(value);
  45573. },
  45574. enumerable: true,
  45575. configurable: true
  45576. });
  45577. ShadowLight.prototype._setDirection = function (value) {
  45578. this._direction = value;
  45579. };
  45580. Object.defineProperty(ShadowLight.prototype, "direction", {
  45581. /**
  45582. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45583. * Also use as the light direction on spot and directional lights.
  45584. */
  45585. get: function () {
  45586. return this._direction;
  45587. },
  45588. /**
  45589. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45590. * Also use as the light direction on spot and directional lights.
  45591. */
  45592. set: function (value) {
  45593. this._setDirection(value);
  45594. },
  45595. enumerable: true,
  45596. configurable: true
  45597. });
  45598. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45599. /**
  45600. * Gets the shadow projection clipping minimum z value.
  45601. */
  45602. get: function () {
  45603. return this._shadowMinZ;
  45604. },
  45605. /**
  45606. * Sets the shadow projection clipping minimum z value.
  45607. */
  45608. set: function (value) {
  45609. this._shadowMinZ = value;
  45610. this.forceProjectionMatrixCompute();
  45611. },
  45612. enumerable: true,
  45613. configurable: true
  45614. });
  45615. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45616. /**
  45617. * Sets the shadow projection clipping maximum z value.
  45618. */
  45619. get: function () {
  45620. return this._shadowMaxZ;
  45621. },
  45622. /**
  45623. * Gets the shadow projection clipping maximum z value.
  45624. */
  45625. set: function (value) {
  45626. this._shadowMaxZ = value;
  45627. this.forceProjectionMatrixCompute();
  45628. },
  45629. enumerable: true,
  45630. configurable: true
  45631. });
  45632. /**
  45633. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45634. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45635. */
  45636. ShadowLight.prototype.computeTransformedInformation = function () {
  45637. if (this.parent && this.parent.getWorldMatrix) {
  45638. if (!this.transformedPosition) {
  45639. this.transformedPosition = BABYLON.Vector3.Zero();
  45640. }
  45641. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45642. // In case the direction is present.
  45643. if (this.direction) {
  45644. if (!this.transformedDirection) {
  45645. this.transformedDirection = BABYLON.Vector3.Zero();
  45646. }
  45647. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45648. }
  45649. return true;
  45650. }
  45651. return false;
  45652. };
  45653. /**
  45654. * Return the depth scale used for the shadow map.
  45655. * @returns the depth scale.
  45656. */
  45657. ShadowLight.prototype.getDepthScale = function () {
  45658. return 50.0;
  45659. };
  45660. /**
  45661. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45662. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45663. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45664. */
  45665. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45666. return this.transformedDirection ? this.transformedDirection : this.direction;
  45667. };
  45668. /**
  45669. * Returns the ShadowLight absolute position in the World.
  45670. * @returns the position vector in world space
  45671. */
  45672. ShadowLight.prototype.getAbsolutePosition = function () {
  45673. return this.transformedPosition ? this.transformedPosition : this.position;
  45674. };
  45675. /**
  45676. * Sets the ShadowLight direction toward the passed target.
  45677. * @param target The point tot target in local space
  45678. * @returns the updated ShadowLight direction
  45679. */
  45680. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45681. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45682. return this.direction;
  45683. };
  45684. /**
  45685. * Returns the light rotation in euler definition.
  45686. * @returns the x y z rotation in local space.
  45687. */
  45688. ShadowLight.prototype.getRotation = function () {
  45689. this.direction.normalize();
  45690. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45691. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45692. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45693. };
  45694. /**
  45695. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45696. * @returns true if a cube texture needs to be use
  45697. */
  45698. ShadowLight.prototype.needCube = function () {
  45699. return false;
  45700. };
  45701. /**
  45702. * Detects if the projection matrix requires to be recomputed this frame.
  45703. * @returns true if it requires to be recomputed otherwise, false.
  45704. */
  45705. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45706. return this._needProjectionMatrixCompute;
  45707. };
  45708. /**
  45709. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45710. */
  45711. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45712. this._needProjectionMatrixCompute = true;
  45713. };
  45714. /**
  45715. * Get the world matrix of the sahdow lights.
  45716. * @ignore Internal Use Only
  45717. */
  45718. ShadowLight.prototype._getWorldMatrix = function () {
  45719. if (!this._worldMatrix) {
  45720. this._worldMatrix = BABYLON.Matrix.Identity();
  45721. }
  45722. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45723. return this._worldMatrix;
  45724. };
  45725. /**
  45726. * Gets the minZ used for shadow according to both the scene and the light.
  45727. * @param activeCamera The camera we are returning the min for
  45728. * @returns the depth min z
  45729. */
  45730. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45731. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45732. };
  45733. /**
  45734. * Gets the maxZ used for shadow according to both the scene and the light.
  45735. * @param activeCamera The camera we are returning the max for
  45736. * @returns the depth max z
  45737. */
  45738. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45739. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45740. };
  45741. /**
  45742. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45743. * @param matrix The materix to updated with the projection information
  45744. * @param viewMatrix The transform matrix of the light
  45745. * @param renderList The list of mesh to render in the map
  45746. * @returns The current light
  45747. */
  45748. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45749. if (this.customProjectionMatrixBuilder) {
  45750. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45751. }
  45752. else {
  45753. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45754. }
  45755. return this;
  45756. };
  45757. __decorate([
  45758. BABYLON.serializeAsVector3()
  45759. ], ShadowLight.prototype, "position", null);
  45760. __decorate([
  45761. BABYLON.serializeAsVector3()
  45762. ], ShadowLight.prototype, "direction", null);
  45763. __decorate([
  45764. BABYLON.serialize()
  45765. ], ShadowLight.prototype, "shadowMinZ", null);
  45766. __decorate([
  45767. BABYLON.serialize()
  45768. ], ShadowLight.prototype, "shadowMaxZ", null);
  45769. return ShadowLight;
  45770. }(BABYLON.Light));
  45771. BABYLON.ShadowLight = ShadowLight;
  45772. })(BABYLON || (BABYLON = {}));
  45773. //# sourceMappingURL=babylon.shadowLight.js.map
  45774. var BABYLON;
  45775. (function (BABYLON) {
  45776. /**
  45777. * A point light is a light defined by an unique point in world space.
  45778. * The light is emitted in every direction from this point.
  45779. * A good example of a point light is a standard light bulb.
  45780. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45781. */
  45782. var PointLight = /** @class */ (function (_super) {
  45783. __extends(PointLight, _super);
  45784. /**
  45785. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45786. * A PointLight emits the light in every direction.
  45787. * It can cast shadows.
  45788. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45789. * ```javascript
  45790. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45791. * ```
  45792. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45793. * @param name The light friendly name
  45794. * @param position The position of the point light in the scene
  45795. * @param scene The scene the lights belongs to
  45796. */
  45797. function PointLight(name, position, scene) {
  45798. var _this = _super.call(this, name, scene) || this;
  45799. _this._shadowAngle = Math.PI / 2;
  45800. _this.position = position;
  45801. return _this;
  45802. }
  45803. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45804. /**
  45805. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45806. * This specifies what angle the shadow will use to be created.
  45807. *
  45808. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45809. */
  45810. get: function () {
  45811. return this._shadowAngle;
  45812. },
  45813. /**
  45814. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45815. * This specifies what angle the shadow will use to be created.
  45816. *
  45817. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45818. */
  45819. set: function (value) {
  45820. this._shadowAngle = value;
  45821. this.forceProjectionMatrixCompute();
  45822. },
  45823. enumerable: true,
  45824. configurable: true
  45825. });
  45826. Object.defineProperty(PointLight.prototype, "direction", {
  45827. /**
  45828. * Gets the direction if it has been set.
  45829. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45830. */
  45831. get: function () {
  45832. return this._direction;
  45833. },
  45834. /**
  45835. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45836. */
  45837. set: function (value) {
  45838. var previousNeedCube = this.needCube();
  45839. this._direction = value;
  45840. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45841. this._shadowGenerator.recreateShadowMap();
  45842. }
  45843. },
  45844. enumerable: true,
  45845. configurable: true
  45846. });
  45847. /**
  45848. * Returns the string "PointLight"
  45849. * @returns the class name
  45850. */
  45851. PointLight.prototype.getClassName = function () {
  45852. return "PointLight";
  45853. };
  45854. /**
  45855. * Returns the integer 0.
  45856. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45857. */
  45858. PointLight.prototype.getTypeID = function () {
  45859. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45860. };
  45861. /**
  45862. * Specifies wether or not the shadowmap should be a cube texture.
  45863. * @returns true if the shadowmap needs to be a cube texture.
  45864. */
  45865. PointLight.prototype.needCube = function () {
  45866. return !this.direction;
  45867. };
  45868. /**
  45869. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45870. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45871. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45872. */
  45873. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45874. if (this.direction) {
  45875. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45876. }
  45877. else {
  45878. switch (faceIndex) {
  45879. case 0:
  45880. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45881. case 1:
  45882. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45883. case 2:
  45884. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45885. case 3:
  45886. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45887. case 4:
  45888. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45889. case 5:
  45890. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45891. }
  45892. }
  45893. return BABYLON.Vector3.Zero();
  45894. };
  45895. /**
  45896. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45897. * - fov = PI / 2
  45898. * - aspect ratio : 1.0
  45899. * - z-near and far equal to the active camera minZ and maxZ.
  45900. * Returns the PointLight.
  45901. */
  45902. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45903. var activeCamera = this.getScene().activeCamera;
  45904. if (!activeCamera) {
  45905. return;
  45906. }
  45907. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45908. };
  45909. PointLight.prototype._buildUniformLayout = function () {
  45910. this._uniformBuffer.addUniform("vLightData", 4);
  45911. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45912. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45913. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45914. this._uniformBuffer.addUniform("depthValues", 2);
  45915. this._uniformBuffer.create();
  45916. };
  45917. /**
  45918. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45919. * @param effect The effect to update
  45920. * @param lightIndex The index of the light in the effect to update
  45921. * @returns The point light
  45922. */
  45923. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45924. if (this.computeTransformedInformation()) {
  45925. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45926. return this;
  45927. }
  45928. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45929. return this;
  45930. };
  45931. __decorate([
  45932. BABYLON.serialize()
  45933. ], PointLight.prototype, "shadowAngle", null);
  45934. return PointLight;
  45935. }(BABYLON.ShadowLight));
  45936. BABYLON.PointLight = PointLight;
  45937. })(BABYLON || (BABYLON = {}));
  45938. //# sourceMappingURL=babylon.pointLight.js.map
  45939. var BABYLON;
  45940. (function (BABYLON) {
  45941. /**
  45942. * A directional light is defined by a direction (what a surprise!).
  45943. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45944. * 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.
  45945. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45946. */
  45947. var DirectionalLight = /** @class */ (function (_super) {
  45948. __extends(DirectionalLight, _super);
  45949. /**
  45950. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45951. * The directional light is emitted from everywhere in the given direction.
  45952. * It can cast shawdows.
  45953. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45954. * @param name The friendly name of the light
  45955. * @param direction The direction of the light
  45956. * @param scene The scene the light belongs to
  45957. */
  45958. function DirectionalLight(name, direction, scene) {
  45959. var _this = _super.call(this, name, scene) || this;
  45960. _this._shadowFrustumSize = 0;
  45961. _this._shadowOrthoScale = 0.5;
  45962. /**
  45963. * Automatically compute the projection matrix to best fit (including all the casters)
  45964. * on each frame.
  45965. */
  45966. _this.autoUpdateExtends = true;
  45967. // Cache
  45968. _this._orthoLeft = Number.MAX_VALUE;
  45969. _this._orthoRight = Number.MIN_VALUE;
  45970. _this._orthoTop = Number.MIN_VALUE;
  45971. _this._orthoBottom = Number.MAX_VALUE;
  45972. _this.position = direction.scale(-1.0);
  45973. _this.direction = direction;
  45974. return _this;
  45975. }
  45976. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45977. /**
  45978. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45979. */
  45980. get: function () {
  45981. return this._shadowFrustumSize;
  45982. },
  45983. /**
  45984. * Specifies a fix frustum size for the shadow generation.
  45985. */
  45986. set: function (value) {
  45987. this._shadowFrustumSize = value;
  45988. this.forceProjectionMatrixCompute();
  45989. },
  45990. enumerable: true,
  45991. configurable: true
  45992. });
  45993. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45994. /**
  45995. * Gets the shadow projection scale against the optimal computed one.
  45996. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45997. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45998. */
  45999. get: function () {
  46000. return this._shadowOrthoScale;
  46001. },
  46002. /**
  46003. * Sets the shadow projection scale against the optimal computed one.
  46004. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46005. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46006. */
  46007. set: function (value) {
  46008. this._shadowOrthoScale = value;
  46009. this.forceProjectionMatrixCompute();
  46010. },
  46011. enumerable: true,
  46012. configurable: true
  46013. });
  46014. /**
  46015. * Returns the string "DirectionalLight".
  46016. * @return The class name
  46017. */
  46018. DirectionalLight.prototype.getClassName = function () {
  46019. return "DirectionalLight";
  46020. };
  46021. /**
  46022. * Returns the integer 1.
  46023. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46024. */
  46025. DirectionalLight.prototype.getTypeID = function () {
  46026. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  46027. };
  46028. /**
  46029. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  46030. * Returns the DirectionalLight Shadow projection matrix.
  46031. */
  46032. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46033. if (this.shadowFrustumSize > 0) {
  46034. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  46035. }
  46036. else {
  46037. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46038. }
  46039. };
  46040. /**
  46041. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  46042. * Returns the DirectionalLight Shadow projection matrix.
  46043. */
  46044. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  46045. var activeCamera = this.getScene().activeCamera;
  46046. if (!activeCamera) {
  46047. return;
  46048. }
  46049. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  46050. };
  46051. /**
  46052. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  46053. * Returns the DirectionalLight Shadow projection matrix.
  46054. */
  46055. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46056. var activeCamera = this.getScene().activeCamera;
  46057. if (!activeCamera) {
  46058. return;
  46059. }
  46060. // Check extends
  46061. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  46062. var tempVector3 = BABYLON.Vector3.Zero();
  46063. this._orthoLeft = Number.MAX_VALUE;
  46064. this._orthoRight = Number.MIN_VALUE;
  46065. this._orthoTop = Number.MIN_VALUE;
  46066. this._orthoBottom = Number.MAX_VALUE;
  46067. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  46068. var mesh = renderList[meshIndex];
  46069. if (!mesh) {
  46070. continue;
  46071. }
  46072. var boundingInfo = mesh.getBoundingInfo();
  46073. var boundingBox = boundingInfo.boundingBox;
  46074. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  46075. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  46076. if (tempVector3.x < this._orthoLeft)
  46077. this._orthoLeft = tempVector3.x;
  46078. if (tempVector3.y < this._orthoBottom)
  46079. this._orthoBottom = tempVector3.y;
  46080. if (tempVector3.x > this._orthoRight)
  46081. this._orthoRight = tempVector3.x;
  46082. if (tempVector3.y > this._orthoTop)
  46083. this._orthoTop = tempVector3.y;
  46084. }
  46085. }
  46086. }
  46087. var xOffset = this._orthoRight - this._orthoLeft;
  46088. var yOffset = this._orthoTop - this._orthoBottom;
  46089. 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);
  46090. };
  46091. DirectionalLight.prototype._buildUniformLayout = function () {
  46092. this._uniformBuffer.addUniform("vLightData", 4);
  46093. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46094. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46095. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46096. this._uniformBuffer.addUniform("depthValues", 2);
  46097. this._uniformBuffer.create();
  46098. };
  46099. /**
  46100. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  46101. * @param effect The effect to update
  46102. * @param lightIndex The index of the light in the effect to update
  46103. * @returns The directional light
  46104. */
  46105. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  46106. if (this.computeTransformedInformation()) {
  46107. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  46108. return this;
  46109. }
  46110. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  46111. return this;
  46112. };
  46113. /**
  46114. * Gets the minZ used for shadow according to both the scene and the light.
  46115. *
  46116. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46117. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46118. * @param activeCamera The camera we are returning the min for
  46119. * @returns the depth min z
  46120. */
  46121. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  46122. return 1;
  46123. };
  46124. /**
  46125. * Gets the maxZ used for shadow according to both the scene and the light.
  46126. *
  46127. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46128. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46129. * @param activeCamera The camera we are returning the max for
  46130. * @returns the depth max z
  46131. */
  46132. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  46133. return 1;
  46134. };
  46135. __decorate([
  46136. BABYLON.serialize()
  46137. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  46138. __decorate([
  46139. BABYLON.serialize()
  46140. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  46141. __decorate([
  46142. BABYLON.serialize()
  46143. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  46144. return DirectionalLight;
  46145. }(BABYLON.ShadowLight));
  46146. BABYLON.DirectionalLight = DirectionalLight;
  46147. })(BABYLON || (BABYLON = {}));
  46148. //# sourceMappingURL=babylon.directionalLight.js.map
  46149. var BABYLON;
  46150. (function (BABYLON) {
  46151. /**
  46152. * A spot light is defined by a position, a direction, an angle, and an exponent.
  46153. * These values define a cone of light starting from the position, emitting toward the direction.
  46154. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  46155. * and the exponent defines the speed of the decay of the light with distance (reach).
  46156. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46157. */
  46158. var SpotLight = /** @class */ (function (_super) {
  46159. __extends(SpotLight, _super);
  46160. /**
  46161. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  46162. * It can cast shadows.
  46163. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46164. * @param name The light friendly name
  46165. * @param position The position of the spot light in the scene
  46166. * @param direction The direction of the light in the scene
  46167. * @param angle The cone angle of the light in Radians
  46168. * @param exponent The light decay speed with the distance from the emission spot
  46169. * @param scene The scene the lights belongs to
  46170. */
  46171. function SpotLight(name, position, direction, angle, exponent, scene) {
  46172. var _this = _super.call(this, name, scene) || this;
  46173. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46174. _this._projectionTextureLightNear = 1e-6;
  46175. _this._projectionTextureLightFar = 1000.0;
  46176. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46177. _this._projectionTextureViewLightDirty = true;
  46178. _this._projectionTextureProjectionLightDirty = true;
  46179. _this._projectionTextureDirty = true;
  46180. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46181. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46182. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46183. _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);
  46184. _this.position = position;
  46185. _this.direction = direction;
  46186. _this.angle = angle;
  46187. _this.exponent = exponent;
  46188. return _this;
  46189. }
  46190. Object.defineProperty(SpotLight.prototype, "angle", {
  46191. /**
  46192. * Gets the cone angle of the spot light in Radians.
  46193. */
  46194. get: function () {
  46195. return this._angle;
  46196. },
  46197. /**
  46198. * Sets the cone angle of the spot light in Radians.
  46199. */
  46200. set: function (value) {
  46201. this._angle = value;
  46202. this._projectionTextureProjectionLightDirty = true;
  46203. this.forceProjectionMatrixCompute();
  46204. },
  46205. enumerable: true,
  46206. configurable: true
  46207. });
  46208. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46209. /**
  46210. * Allows scaling the angle of the light for shadow generation only.
  46211. */
  46212. get: function () {
  46213. return this._shadowAngleScale;
  46214. },
  46215. /**
  46216. * Allows scaling the angle of the light for shadow generation only.
  46217. */
  46218. set: function (value) {
  46219. this._shadowAngleScale = value;
  46220. this.forceProjectionMatrixCompute();
  46221. },
  46222. enumerable: true,
  46223. configurable: true
  46224. });
  46225. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46226. /**
  46227. * Allows reading the projecton texture
  46228. */
  46229. get: function () {
  46230. return this._projectionTextureMatrix;
  46231. },
  46232. enumerable: true,
  46233. configurable: true
  46234. });
  46235. ;
  46236. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46237. /**
  46238. * Gets the near clip of the Spotlight for texture projection.
  46239. */
  46240. get: function () {
  46241. return this._projectionTextureLightNear;
  46242. },
  46243. /**
  46244. * Sets the near clip of the Spotlight for texture projection.
  46245. */
  46246. set: function (value) {
  46247. this._projectionTextureLightNear = value;
  46248. this._projectionTextureProjectionLightDirty = true;
  46249. },
  46250. enumerable: true,
  46251. configurable: true
  46252. });
  46253. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46254. /**
  46255. * Gets the far clip of the Spotlight for texture projection.
  46256. */
  46257. get: function () {
  46258. return this._projectionTextureLightFar;
  46259. },
  46260. /**
  46261. * Sets the far clip of the Spotlight for texture projection.
  46262. */
  46263. set: function (value) {
  46264. this._projectionTextureLightFar = value;
  46265. this._projectionTextureProjectionLightDirty = true;
  46266. },
  46267. enumerable: true,
  46268. configurable: true
  46269. });
  46270. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46271. /**
  46272. * Gets the Up vector of the Spotlight for texture projection.
  46273. */
  46274. get: function () {
  46275. return this._projectionTextureUpDirection;
  46276. },
  46277. /**
  46278. * Sets the Up vector of the Spotlight for texture projection.
  46279. */
  46280. set: function (value) {
  46281. this._projectionTextureUpDirection = value;
  46282. this._projectionTextureProjectionLightDirty = true;
  46283. },
  46284. enumerable: true,
  46285. configurable: true
  46286. });
  46287. ;
  46288. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46289. /**
  46290. * Gets the projection texture of the light.
  46291. */
  46292. get: function () {
  46293. return this._projectionTexture;
  46294. },
  46295. /**
  46296. * Sets the projection texture of the light.
  46297. */
  46298. set: function (value) {
  46299. this._projectionTexture = value;
  46300. this._projectionTextureDirty = true;
  46301. },
  46302. enumerable: true,
  46303. configurable: true
  46304. });
  46305. /**
  46306. * Returns the string "SpotLight".
  46307. * @returns the class name
  46308. */
  46309. SpotLight.prototype.getClassName = function () {
  46310. return "SpotLight";
  46311. };
  46312. /**
  46313. * Returns the integer 2.
  46314. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46315. */
  46316. SpotLight.prototype.getTypeID = function () {
  46317. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46318. };
  46319. /**
  46320. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46321. */
  46322. SpotLight.prototype._setDirection = function (value) {
  46323. _super.prototype._setDirection.call(this, value);
  46324. this._projectionTextureViewLightDirty = true;
  46325. };
  46326. /**
  46327. * Overrides the position setter to recompute the projection texture view light Matrix.
  46328. */
  46329. SpotLight.prototype._setPosition = function (value) {
  46330. _super.prototype._setPosition.call(this, value);
  46331. this._projectionTextureViewLightDirty = true;
  46332. };
  46333. /**
  46334. * 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.
  46335. * Returns the SpotLight.
  46336. */
  46337. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46338. var activeCamera = this.getScene().activeCamera;
  46339. if (!activeCamera) {
  46340. return;
  46341. }
  46342. this._shadowAngleScale = this._shadowAngleScale || 1;
  46343. var angle = this._shadowAngleScale * this._angle;
  46344. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46345. };
  46346. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46347. this._projectionTextureViewLightDirty = false;
  46348. this._projectionTextureDirty = true;
  46349. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46350. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46351. };
  46352. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46353. this._projectionTextureProjectionLightDirty = false;
  46354. this._projectionTextureDirty = true;
  46355. var light_far = this.projectionTextureLightFar;
  46356. var light_near = this.projectionTextureLightNear;
  46357. var P = light_far / (light_far - light_near);
  46358. var Q = -P * light_near;
  46359. var S = 1.0 / Math.tan(this._angle / 2.0);
  46360. var A = 1.0;
  46361. 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);
  46362. };
  46363. /**
  46364. * Main function for light texture projection matrix computing.
  46365. */
  46366. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46367. this._projectionTextureDirty = false;
  46368. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46369. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46370. };
  46371. SpotLight.prototype._buildUniformLayout = function () {
  46372. this._uniformBuffer.addUniform("vLightData", 4);
  46373. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46374. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46375. this._uniformBuffer.addUniform("vLightDirection", 3);
  46376. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46377. this._uniformBuffer.addUniform("depthValues", 2);
  46378. this._uniformBuffer.create();
  46379. };
  46380. /**
  46381. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46382. * @param effect The effect to update
  46383. * @param lightIndex The index of the light in the effect to update
  46384. * @returns The spot light
  46385. */
  46386. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46387. var normalizeDirection;
  46388. if (this.computeTransformedInformation()) {
  46389. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46390. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46391. }
  46392. else {
  46393. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46394. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46395. }
  46396. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46397. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46398. if (this._projectionTextureViewLightDirty) {
  46399. this._computeProjectionTextureViewLightMatrix();
  46400. }
  46401. if (this._projectionTextureProjectionLightDirty) {
  46402. this._computeProjectionTextureProjectionLightMatrix();
  46403. }
  46404. if (this._projectionTextureDirty) {
  46405. this._computeProjectionTextureMatrix();
  46406. }
  46407. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46408. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46409. }
  46410. return this;
  46411. };
  46412. /**
  46413. * Disposes the light and the associated resources.
  46414. */
  46415. SpotLight.prototype.dispose = function () {
  46416. _super.prototype.dispose.call(this);
  46417. if (this._projectionTexture) {
  46418. this._projectionTexture.dispose();
  46419. }
  46420. };
  46421. __decorate([
  46422. BABYLON.serialize()
  46423. ], SpotLight.prototype, "angle", null);
  46424. __decorate([
  46425. BABYLON.serialize()
  46426. ], SpotLight.prototype, "shadowAngleScale", null);
  46427. __decorate([
  46428. BABYLON.serialize()
  46429. ], SpotLight.prototype, "exponent", void 0);
  46430. __decorate([
  46431. BABYLON.serialize()
  46432. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46433. __decorate([
  46434. BABYLON.serialize()
  46435. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46436. __decorate([
  46437. BABYLON.serialize()
  46438. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46439. __decorate([
  46440. BABYLON.serializeAsTexture("projectedLightTexture")
  46441. ], SpotLight.prototype, "_projectionTexture", void 0);
  46442. return SpotLight;
  46443. }(BABYLON.ShadowLight));
  46444. BABYLON.SpotLight = SpotLight;
  46445. })(BABYLON || (BABYLON = {}));
  46446. //# sourceMappingURL=babylon.spotLight.js.map
  46447. var BABYLON;
  46448. (function (BABYLON) {
  46449. /**
  46450. * Class used to override all child animations of a given target
  46451. */
  46452. var AnimationPropertiesOverride = /** @class */ (function () {
  46453. function AnimationPropertiesOverride() {
  46454. /**
  46455. * Gets or sets a value indicating if animation blending must be used
  46456. */
  46457. this.enableBlending = false;
  46458. /**
  46459. * Gets or sets the blending speed to use when enableBlending is true
  46460. */
  46461. this.blendingSpeed = 0.01;
  46462. /**
  46463. * Gets or sets the default loop mode to use
  46464. */
  46465. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46466. }
  46467. return AnimationPropertiesOverride;
  46468. }());
  46469. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46470. })(BABYLON || (BABYLON = {}));
  46471. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46472. var BABYLON;
  46473. (function (BABYLON) {
  46474. var AnimationRange = /** @class */ (function () {
  46475. function AnimationRange(name, from, to) {
  46476. this.name = name;
  46477. this.from = from;
  46478. this.to = to;
  46479. }
  46480. AnimationRange.prototype.clone = function () {
  46481. return new AnimationRange(this.name, this.from, this.to);
  46482. };
  46483. return AnimationRange;
  46484. }());
  46485. BABYLON.AnimationRange = AnimationRange;
  46486. /**
  46487. * Composed of a frame, and an action function
  46488. */
  46489. var AnimationEvent = /** @class */ (function () {
  46490. function AnimationEvent(frame, action, onlyOnce) {
  46491. this.frame = frame;
  46492. this.action = action;
  46493. this.onlyOnce = onlyOnce;
  46494. this.isDone = false;
  46495. }
  46496. return AnimationEvent;
  46497. }());
  46498. BABYLON.AnimationEvent = AnimationEvent;
  46499. var PathCursor = /** @class */ (function () {
  46500. function PathCursor(path) {
  46501. this.path = path;
  46502. this._onchange = new Array();
  46503. this.value = 0;
  46504. this.animations = new Array();
  46505. }
  46506. PathCursor.prototype.getPoint = function () {
  46507. var point = this.path.getPointAtLengthPosition(this.value);
  46508. return new BABYLON.Vector3(point.x, 0, point.y);
  46509. };
  46510. PathCursor.prototype.moveAhead = function (step) {
  46511. if (step === void 0) { step = 0.002; }
  46512. this.move(step);
  46513. return this;
  46514. };
  46515. PathCursor.prototype.moveBack = function (step) {
  46516. if (step === void 0) { step = 0.002; }
  46517. this.move(-step);
  46518. return this;
  46519. };
  46520. PathCursor.prototype.move = function (step) {
  46521. if (Math.abs(step) > 1) {
  46522. throw "step size should be less than 1.";
  46523. }
  46524. this.value += step;
  46525. this.ensureLimits();
  46526. this.raiseOnChange();
  46527. return this;
  46528. };
  46529. PathCursor.prototype.ensureLimits = function () {
  46530. while (this.value > 1) {
  46531. this.value -= 1;
  46532. }
  46533. while (this.value < 0) {
  46534. this.value += 1;
  46535. }
  46536. return this;
  46537. };
  46538. // used by animation engine
  46539. PathCursor.prototype.raiseOnChange = function () {
  46540. var _this = this;
  46541. this._onchange.forEach(function (f) { return f(_this); });
  46542. return this;
  46543. };
  46544. PathCursor.prototype.onchange = function (f) {
  46545. this._onchange.push(f);
  46546. return this;
  46547. };
  46548. return PathCursor;
  46549. }());
  46550. BABYLON.PathCursor = PathCursor;
  46551. var AnimationKeyInterpolation;
  46552. (function (AnimationKeyInterpolation) {
  46553. /**
  46554. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46555. */
  46556. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46557. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46558. var Animation = /** @class */ (function () {
  46559. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46560. this.name = name;
  46561. this.targetProperty = targetProperty;
  46562. this.framePerSecond = framePerSecond;
  46563. this.dataType = dataType;
  46564. this.loopMode = loopMode;
  46565. this.enableBlending = enableBlending;
  46566. this._runtimeAnimations = new Array();
  46567. // The set of event that will be linked to this animation
  46568. this._events = new Array();
  46569. this.blendingSpeed = 0.01;
  46570. this._ranges = {};
  46571. this.targetPropertyPath = targetProperty.split(".");
  46572. this.dataType = dataType;
  46573. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46574. }
  46575. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46576. var dataType = undefined;
  46577. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46578. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46579. }
  46580. else if (from instanceof BABYLON.Quaternion) {
  46581. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46582. }
  46583. else if (from instanceof BABYLON.Vector3) {
  46584. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46585. }
  46586. else if (from instanceof BABYLON.Vector2) {
  46587. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46588. }
  46589. else if (from instanceof BABYLON.Color3) {
  46590. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46591. }
  46592. else if (from instanceof BABYLON.Size) {
  46593. dataType = Animation.ANIMATIONTYPE_SIZE;
  46594. }
  46595. if (dataType == undefined) {
  46596. return null;
  46597. }
  46598. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46599. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46600. animation.setKeys(keys);
  46601. if (easingFunction !== undefined) {
  46602. animation.setEasingFunction(easingFunction);
  46603. }
  46604. return animation;
  46605. };
  46606. /**
  46607. * Sets up an animation.
  46608. * @param property the property to animate
  46609. * @param animationType the animation type to apply
  46610. * @param easingFunction the easing function used in the animation
  46611. * @returns The created animation
  46612. */
  46613. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46614. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46615. animation.setEasingFunction(easingFunction);
  46616. return animation;
  46617. };
  46618. /**
  46619. * Create and start an animation on a node
  46620. * @param {string} name defines the name of the global animation that will be run on all nodes
  46621. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46622. * @param {string} targetProperty defines property to animate
  46623. * @param {number} framePerSecond defines the number of frame per second yo use
  46624. * @param {number} totalFrame defines the number of frames in total
  46625. * @param {any} from defines the initial value
  46626. * @param {any} to defines the final value
  46627. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46628. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46629. * @param onAnimationEnd defines the callback to call when animation end
  46630. * @returns the animatable created for this animation
  46631. */
  46632. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46633. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46634. if (!animation) {
  46635. return null;
  46636. }
  46637. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46638. };
  46639. /**
  46640. * Create and start an animation on a node and its descendants
  46641. * @param {string} name defines the name of the global animation that will be run on all nodes
  46642. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46643. * @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.
  46644. * @param {string} targetProperty defines property to animate
  46645. * @param {number} framePerSecond defines the number of frame per second yo use
  46646. * @param {number} totalFrame defines the number of frames in total
  46647. * @param {any} from defines the initial value
  46648. * @param {any} to defines the final value
  46649. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46650. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46651. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46652. * @returns the list of animatables created for all nodes
  46653. * @example https://www.babylonjs-playground.com/#MH0VLI
  46654. */
  46655. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46656. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46657. if (!animation) {
  46658. return null;
  46659. }
  46660. var scene = node.getScene();
  46661. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46662. };
  46663. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46664. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46665. if (!animation) {
  46666. return null;
  46667. }
  46668. node.animations.push(animation);
  46669. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46670. };
  46671. /**
  46672. * Transition property of the Camera to the target Value.
  46673. * @param property The property to transition
  46674. * @param targetValue The target Value of the property
  46675. * @param host The object where the property to animate belongs
  46676. * @param scene Scene used to run the animation
  46677. * @param frameRate Framerate (in frame/s) to use
  46678. * @param transition The transition type we want to use
  46679. * @param duration The duration of the animation, in milliseconds
  46680. * @param onAnimationEnd Call back trigger at the end of the animation.
  46681. */
  46682. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46683. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46684. if (duration <= 0) {
  46685. host[property] = targetValue;
  46686. if (onAnimationEnd) {
  46687. onAnimationEnd();
  46688. }
  46689. return null;
  46690. }
  46691. var endFrame = frameRate * (duration / 1000);
  46692. transition.setKeys([{
  46693. frame: 0,
  46694. value: host[property].clone ? host[property].clone() : host[property]
  46695. },
  46696. {
  46697. frame: endFrame,
  46698. value: targetValue
  46699. }]);
  46700. if (!host.animations) {
  46701. host.animations = [];
  46702. }
  46703. host.animations.push(transition);
  46704. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46705. animation.onAnimationEnd = onAnimationEnd;
  46706. return animation;
  46707. };
  46708. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46709. /**
  46710. * Return the array of runtime animations currently using this animation
  46711. */
  46712. get: function () {
  46713. return this._runtimeAnimations;
  46714. },
  46715. enumerable: true,
  46716. configurable: true
  46717. });
  46718. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  46719. get: function () {
  46720. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46721. var runtimeAnimation = _a[_i];
  46722. if (!runtimeAnimation.isStopped) {
  46723. return true;
  46724. }
  46725. }
  46726. return false;
  46727. },
  46728. enumerable: true,
  46729. configurable: true
  46730. });
  46731. // Methods
  46732. /**
  46733. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46734. */
  46735. Animation.prototype.toString = function (fullDetails) {
  46736. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46737. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46738. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46739. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46740. if (fullDetails) {
  46741. ret += ", Ranges: {";
  46742. var first = true;
  46743. for (var name in this._ranges) {
  46744. if (first) {
  46745. ret += ", ";
  46746. first = false;
  46747. }
  46748. ret += name;
  46749. }
  46750. ret += "}";
  46751. }
  46752. return ret;
  46753. };
  46754. /**
  46755. * Add an event to this animation.
  46756. */
  46757. Animation.prototype.addEvent = function (event) {
  46758. this._events.push(event);
  46759. };
  46760. /**
  46761. * Remove all events found at the given frame
  46762. * @param frame
  46763. */
  46764. Animation.prototype.removeEvents = function (frame) {
  46765. for (var index = 0; index < this._events.length; index++) {
  46766. if (this._events[index].frame === frame) {
  46767. this._events.splice(index, 1);
  46768. index--;
  46769. }
  46770. }
  46771. };
  46772. Animation.prototype.getEvents = function () {
  46773. return this._events;
  46774. };
  46775. Animation.prototype.createRange = function (name, from, to) {
  46776. // check name not already in use; could happen for bones after serialized
  46777. if (!this._ranges[name]) {
  46778. this._ranges[name] = new AnimationRange(name, from, to);
  46779. }
  46780. };
  46781. Animation.prototype.deleteRange = function (name, deleteFrames) {
  46782. if (deleteFrames === void 0) { deleteFrames = true; }
  46783. var range = this._ranges[name];
  46784. if (!range) {
  46785. return;
  46786. }
  46787. if (deleteFrames) {
  46788. var from = range.from;
  46789. var to = range.to;
  46790. // this loop MUST go high to low for multiple splices to work
  46791. for (var key = this._keys.length - 1; key >= 0; key--) {
  46792. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46793. this._keys.splice(key, 1);
  46794. }
  46795. }
  46796. }
  46797. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46798. };
  46799. Animation.prototype.getRange = function (name) {
  46800. return this._ranges[name];
  46801. };
  46802. Animation.prototype.getKeys = function () {
  46803. return this._keys;
  46804. };
  46805. Animation.prototype.getHighestFrame = function () {
  46806. var ret = 0;
  46807. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46808. if (ret < this._keys[key].frame) {
  46809. ret = this._keys[key].frame;
  46810. }
  46811. }
  46812. return ret;
  46813. };
  46814. Animation.prototype.getEasingFunction = function () {
  46815. return this._easingFunction;
  46816. };
  46817. Animation.prototype.setEasingFunction = function (easingFunction) {
  46818. this._easingFunction = easingFunction;
  46819. };
  46820. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46821. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46822. };
  46823. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46824. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46825. };
  46826. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46827. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46828. };
  46829. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46830. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46831. };
  46832. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46833. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46834. };
  46835. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46836. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46837. };
  46838. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46839. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46840. };
  46841. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46842. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46843. };
  46844. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46845. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46846. };
  46847. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46848. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46849. };
  46850. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46851. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46852. };
  46853. Animation.prototype.clone = function () {
  46854. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46855. clone.enableBlending = this.enableBlending;
  46856. clone.blendingSpeed = this.blendingSpeed;
  46857. if (this._keys) {
  46858. clone.setKeys(this._keys);
  46859. }
  46860. if (this._ranges) {
  46861. clone._ranges = {};
  46862. for (var name in this._ranges) {
  46863. var range = this._ranges[name];
  46864. if (!range) {
  46865. continue;
  46866. }
  46867. clone._ranges[name] = range.clone();
  46868. }
  46869. }
  46870. return clone;
  46871. };
  46872. Animation.prototype.setKeys = function (values) {
  46873. this._keys = values.slice(0);
  46874. };
  46875. Animation.prototype.serialize = function () {
  46876. var serializationObject = {};
  46877. serializationObject.name = this.name;
  46878. serializationObject.property = this.targetProperty;
  46879. serializationObject.framePerSecond = this.framePerSecond;
  46880. serializationObject.dataType = this.dataType;
  46881. serializationObject.loopBehavior = this.loopMode;
  46882. serializationObject.enableBlending = this.enableBlending;
  46883. serializationObject.blendingSpeed = this.blendingSpeed;
  46884. var dataType = this.dataType;
  46885. serializationObject.keys = [];
  46886. var keys = this.getKeys();
  46887. for (var index = 0; index < keys.length; index++) {
  46888. var animationKey = keys[index];
  46889. var key = {};
  46890. key.frame = animationKey.frame;
  46891. switch (dataType) {
  46892. case Animation.ANIMATIONTYPE_FLOAT:
  46893. key.values = [animationKey.value];
  46894. break;
  46895. case Animation.ANIMATIONTYPE_QUATERNION:
  46896. case Animation.ANIMATIONTYPE_MATRIX:
  46897. case Animation.ANIMATIONTYPE_VECTOR3:
  46898. case Animation.ANIMATIONTYPE_COLOR3:
  46899. key.values = animationKey.value.asArray();
  46900. break;
  46901. }
  46902. serializationObject.keys.push(key);
  46903. }
  46904. serializationObject.ranges = [];
  46905. for (var name in this._ranges) {
  46906. var source = this._ranges[name];
  46907. if (!source) {
  46908. continue;
  46909. }
  46910. var range = {};
  46911. range.name = name;
  46912. range.from = source.from;
  46913. range.to = source.to;
  46914. serializationObject.ranges.push(range);
  46915. }
  46916. return serializationObject;
  46917. };
  46918. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46919. get: function () {
  46920. return Animation._ANIMATIONTYPE_FLOAT;
  46921. },
  46922. enumerable: true,
  46923. configurable: true
  46924. });
  46925. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46926. get: function () {
  46927. return Animation._ANIMATIONTYPE_VECTOR3;
  46928. },
  46929. enumerable: true,
  46930. configurable: true
  46931. });
  46932. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46933. get: function () {
  46934. return Animation._ANIMATIONTYPE_VECTOR2;
  46935. },
  46936. enumerable: true,
  46937. configurable: true
  46938. });
  46939. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46940. get: function () {
  46941. return Animation._ANIMATIONTYPE_SIZE;
  46942. },
  46943. enumerable: true,
  46944. configurable: true
  46945. });
  46946. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46947. get: function () {
  46948. return Animation._ANIMATIONTYPE_QUATERNION;
  46949. },
  46950. enumerable: true,
  46951. configurable: true
  46952. });
  46953. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46954. get: function () {
  46955. return Animation._ANIMATIONTYPE_MATRIX;
  46956. },
  46957. enumerable: true,
  46958. configurable: true
  46959. });
  46960. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46961. get: function () {
  46962. return Animation._ANIMATIONTYPE_COLOR3;
  46963. },
  46964. enumerable: true,
  46965. configurable: true
  46966. });
  46967. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46968. get: function () {
  46969. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46970. },
  46971. enumerable: true,
  46972. configurable: true
  46973. });
  46974. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46975. get: function () {
  46976. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46977. },
  46978. enumerable: true,
  46979. configurable: true
  46980. });
  46981. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46982. get: function () {
  46983. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46984. },
  46985. enumerable: true,
  46986. configurable: true
  46987. });
  46988. Animation.Parse = function (parsedAnimation) {
  46989. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46990. var dataType = parsedAnimation.dataType;
  46991. var keys = [];
  46992. var data;
  46993. var index;
  46994. if (parsedAnimation.enableBlending) {
  46995. animation.enableBlending = parsedAnimation.enableBlending;
  46996. }
  46997. if (parsedAnimation.blendingSpeed) {
  46998. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46999. }
  47000. for (index = 0; index < parsedAnimation.keys.length; index++) {
  47001. var key = parsedAnimation.keys[index];
  47002. var inTangent;
  47003. var outTangent;
  47004. switch (dataType) {
  47005. case Animation.ANIMATIONTYPE_FLOAT:
  47006. data = key.values[0];
  47007. if (key.values.length >= 1) {
  47008. inTangent = key.values[1];
  47009. }
  47010. if (key.values.length >= 2) {
  47011. outTangent = key.values[2];
  47012. }
  47013. break;
  47014. case Animation.ANIMATIONTYPE_QUATERNION:
  47015. data = BABYLON.Quaternion.FromArray(key.values);
  47016. if (key.values.length >= 8) {
  47017. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  47018. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  47019. inTangent = _inTangent;
  47020. }
  47021. }
  47022. if (key.values.length >= 12) {
  47023. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  47024. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  47025. outTangent = _outTangent;
  47026. }
  47027. }
  47028. break;
  47029. case Animation.ANIMATIONTYPE_MATRIX:
  47030. data = BABYLON.Matrix.FromArray(key.values);
  47031. break;
  47032. case Animation.ANIMATIONTYPE_COLOR3:
  47033. data = BABYLON.Color3.FromArray(key.values);
  47034. break;
  47035. case Animation.ANIMATIONTYPE_VECTOR3:
  47036. default:
  47037. data = BABYLON.Vector3.FromArray(key.values);
  47038. break;
  47039. }
  47040. var keyData = {};
  47041. keyData.frame = key.frame;
  47042. keyData.value = data;
  47043. if (inTangent != undefined) {
  47044. keyData.inTangent = inTangent;
  47045. }
  47046. if (outTangent != undefined) {
  47047. keyData.outTangent = outTangent;
  47048. }
  47049. keys.push(keyData);
  47050. }
  47051. animation.setKeys(keys);
  47052. if (parsedAnimation.ranges) {
  47053. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  47054. data = parsedAnimation.ranges[index];
  47055. animation.createRange(data.name, data.from, data.to);
  47056. }
  47057. }
  47058. return animation;
  47059. };
  47060. Animation.AppendSerializedAnimations = function (source, destination) {
  47061. if (source.animations) {
  47062. destination.animations = [];
  47063. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  47064. var animation = source.animations[animationIndex];
  47065. destination.animations.push(animation.serialize());
  47066. }
  47067. }
  47068. };
  47069. Animation.AllowMatricesInterpolation = false;
  47070. // Statics
  47071. Animation._ANIMATIONTYPE_FLOAT = 0;
  47072. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  47073. Animation._ANIMATIONTYPE_QUATERNION = 2;
  47074. Animation._ANIMATIONTYPE_MATRIX = 3;
  47075. Animation._ANIMATIONTYPE_COLOR3 = 4;
  47076. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  47077. Animation._ANIMATIONTYPE_SIZE = 6;
  47078. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  47079. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  47080. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  47081. return Animation;
  47082. }());
  47083. BABYLON.Animation = Animation;
  47084. })(BABYLON || (BABYLON = {}));
  47085. //# sourceMappingURL=babylon.animation.js.map
  47086. var BABYLON;
  47087. (function (BABYLON) {
  47088. /**
  47089. * This class defines the direct association between an animation and a target
  47090. */
  47091. var TargetedAnimation = /** @class */ (function () {
  47092. function TargetedAnimation() {
  47093. }
  47094. return TargetedAnimation;
  47095. }());
  47096. BABYLON.TargetedAnimation = TargetedAnimation;
  47097. /**
  47098. * Use this class to create coordinated animations on multiple targets
  47099. */
  47100. var AnimationGroup = /** @class */ (function () {
  47101. function AnimationGroup(name, scene) {
  47102. if (scene === void 0) { scene = null; }
  47103. this.name = name;
  47104. this._targetedAnimations = new Array();
  47105. this._animatables = new Array();
  47106. this._from = Number.MAX_VALUE;
  47107. this._to = -Number.MAX_VALUE;
  47108. this._speedRatio = 1;
  47109. this.onAnimationEndObservable = new BABYLON.Observable();
  47110. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47111. this._scene.animationGroups.push(this);
  47112. }
  47113. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  47114. /**
  47115. * Define if the animations are started
  47116. */
  47117. get: function () {
  47118. return this._isStarted;
  47119. },
  47120. enumerable: true,
  47121. configurable: true
  47122. });
  47123. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  47124. /**
  47125. * Gets or sets the speed ratio to use for all animations
  47126. */
  47127. get: function () {
  47128. return this._speedRatio;
  47129. },
  47130. /**
  47131. * Gets or sets the speed ratio to use for all animations
  47132. */
  47133. set: function (value) {
  47134. if (this._speedRatio === value) {
  47135. return;
  47136. }
  47137. this._speedRatio = value;
  47138. for (var index = 0; index < this._animatables.length; index++) {
  47139. var animatable = this._animatables[index];
  47140. animatable.speedRatio = this._speedRatio;
  47141. }
  47142. },
  47143. enumerable: true,
  47144. configurable: true
  47145. });
  47146. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  47147. /**
  47148. * Gets the targeted animations for this animation group
  47149. */
  47150. get: function () {
  47151. return this._targetedAnimations;
  47152. },
  47153. enumerable: true,
  47154. configurable: true
  47155. });
  47156. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  47157. /**
  47158. * returning the list of animatables controlled by this animation group.
  47159. */
  47160. get: function () {
  47161. return this._animatables;
  47162. },
  47163. enumerable: true,
  47164. configurable: true
  47165. });
  47166. /**
  47167. * Add an animation (with its target) in the group
  47168. * @param animation defines the animation we want to add
  47169. * @param target defines the target of the animation
  47170. * @returns the {BABYLON.TargetedAnimation} object
  47171. */
  47172. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47173. var targetedAnimation = {
  47174. animation: animation,
  47175. target: target
  47176. };
  47177. var keys = animation.getKeys();
  47178. if (this._from > keys[0].frame) {
  47179. this._from = keys[0].frame;
  47180. }
  47181. if (this._to < keys[keys.length - 1].frame) {
  47182. this._to = keys[keys.length - 1].frame;
  47183. }
  47184. this._targetedAnimations.push(targetedAnimation);
  47185. return targetedAnimation;
  47186. };
  47187. /**
  47188. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47189. * It can add constant keys at begin or end
  47190. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47191. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47192. */
  47193. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47194. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47195. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47196. beginFrame = Math.max(beginFrame, this._from);
  47197. endFrame = Math.min(endFrame, this._to);
  47198. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47199. var targetedAnimation = this._targetedAnimations[index];
  47200. var keys = targetedAnimation.animation.getKeys();
  47201. var startKey = keys[0];
  47202. var endKey = keys[keys.length - 1];
  47203. if (startKey.frame > beginFrame) {
  47204. var newKey = {
  47205. frame: beginFrame,
  47206. value: startKey.value,
  47207. inTangent: startKey.inTangent,
  47208. outTangent: startKey.outTangent,
  47209. interpolation: startKey.interpolation
  47210. };
  47211. keys.splice(0, 0, newKey);
  47212. }
  47213. if (endKey.frame < endFrame) {
  47214. var newKey = {
  47215. frame: endFrame,
  47216. value: endKey.value,
  47217. inTangent: endKey.outTangent,
  47218. outTangent: endKey.outTangent,
  47219. interpolation: endKey.interpolation
  47220. };
  47221. keys.push(newKey);
  47222. }
  47223. }
  47224. return this;
  47225. };
  47226. /**
  47227. * Start all animations on given targets
  47228. * @param loop defines if animations must loop
  47229. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47230. */
  47231. AnimationGroup.prototype.start = function (loop, speedRatio) {
  47232. var _this = this;
  47233. if (loop === void 0) { loop = false; }
  47234. if (speedRatio === void 0) { speedRatio = 1; }
  47235. if (this._isStarted || this._targetedAnimations.length === 0) {
  47236. return this;
  47237. }
  47238. var _loop_1 = function () {
  47239. var targetedAnimation = this_1._targetedAnimations[index];
  47240. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  47241. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47242. }));
  47243. };
  47244. var this_1 = this;
  47245. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47246. _loop_1();
  47247. }
  47248. this._speedRatio = speedRatio;
  47249. this._isStarted = true;
  47250. return this;
  47251. };
  47252. /**
  47253. * Pause all animations
  47254. */
  47255. AnimationGroup.prototype.pause = function () {
  47256. if (!this._isStarted) {
  47257. return this;
  47258. }
  47259. for (var index = 0; index < this._animatables.length; index++) {
  47260. var animatable = this._animatables[index];
  47261. animatable.pause();
  47262. }
  47263. return this;
  47264. };
  47265. /**
  47266. * Play all animations to initial state
  47267. * This function will start() the animations if they were not started or will restart() them if they were paused
  47268. * @param loop defines if animations must loop
  47269. */
  47270. AnimationGroup.prototype.play = function (loop) {
  47271. if (this.isStarted) {
  47272. if (loop !== undefined) {
  47273. for (var index = 0; index < this._animatables.length; index++) {
  47274. var animatable = this._animatables[index];
  47275. animatable.loopAnimation = loop;
  47276. }
  47277. }
  47278. this.restart();
  47279. }
  47280. else {
  47281. this.start(loop, this._speedRatio);
  47282. }
  47283. return this;
  47284. };
  47285. /**
  47286. * Reset all animations to initial state
  47287. */
  47288. AnimationGroup.prototype.reset = function () {
  47289. if (!this._isStarted) {
  47290. return this;
  47291. }
  47292. for (var index = 0; index < this._animatables.length; index++) {
  47293. var animatable = this._animatables[index];
  47294. animatable.reset();
  47295. }
  47296. return this;
  47297. };
  47298. /**
  47299. * Restart animations from key 0
  47300. */
  47301. AnimationGroup.prototype.restart = function () {
  47302. if (!this._isStarted) {
  47303. return this;
  47304. }
  47305. for (var index = 0; index < this._animatables.length; index++) {
  47306. var animatable = this._animatables[index];
  47307. animatable.restart();
  47308. }
  47309. return this;
  47310. };
  47311. /**
  47312. * Stop all animations
  47313. */
  47314. AnimationGroup.prototype.stop = function () {
  47315. if (!this._isStarted) {
  47316. return this;
  47317. }
  47318. for (var index = 0; index < this._animatables.length; index++) {
  47319. var animatable = this._animatables[index];
  47320. animatable.stop();
  47321. }
  47322. this._isStarted = false;
  47323. return this;
  47324. };
  47325. /**
  47326. * Goes to a specific frame in this animation group
  47327. *
  47328. * @param frame the frame number to go to
  47329. * @return the animationGroup
  47330. */
  47331. AnimationGroup.prototype.goToFrame = function (frame) {
  47332. if (!this._isStarted) {
  47333. return this;
  47334. }
  47335. for (var index = 0; index < this._animatables.length; index++) {
  47336. var animatable = this._animatables[index];
  47337. animatable.goToFrame(frame);
  47338. }
  47339. return this;
  47340. };
  47341. /**
  47342. * Dispose all associated resources
  47343. */
  47344. AnimationGroup.prototype.dispose = function () {
  47345. this._targetedAnimations = [];
  47346. this._animatables = [];
  47347. var index = this._scene.animationGroups.indexOf(this);
  47348. if (index > -1) {
  47349. this._scene.animationGroups.splice(index, 1);
  47350. }
  47351. };
  47352. return AnimationGroup;
  47353. }());
  47354. BABYLON.AnimationGroup = AnimationGroup;
  47355. })(BABYLON || (BABYLON = {}));
  47356. //# sourceMappingURL=babylon.animationGroup.js.map
  47357. var BABYLON;
  47358. (function (BABYLON) {
  47359. var RuntimeAnimation = /** @class */ (function () {
  47360. function RuntimeAnimation(target, animation) {
  47361. this._offsetsCache = {};
  47362. this._highLimitsCache = {};
  47363. this._stopped = false;
  47364. this._blendingFactor = 0;
  47365. this._ratioOffset = 0;
  47366. this._animation = animation;
  47367. this._target = target;
  47368. animation._runtimeAnimations.push(this);
  47369. }
  47370. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47371. get: function () {
  47372. return this._animation;
  47373. },
  47374. enumerable: true,
  47375. configurable: true
  47376. });
  47377. RuntimeAnimation.prototype.reset = function () {
  47378. this._offsetsCache = {};
  47379. this._highLimitsCache = {};
  47380. this.currentFrame = 0;
  47381. this._blendingFactor = 0;
  47382. this._originalBlendValue = null;
  47383. };
  47384. RuntimeAnimation.prototype.isStopped = function () {
  47385. return this._stopped;
  47386. };
  47387. RuntimeAnimation.prototype.dispose = function () {
  47388. var index = this._animation.runtimeAnimations.indexOf(this);
  47389. if (index > -1) {
  47390. this._animation.runtimeAnimations.splice(index, 1);
  47391. }
  47392. };
  47393. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47394. if (typeof value === "function") {
  47395. return value();
  47396. }
  47397. return value;
  47398. };
  47399. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47400. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47401. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47402. }
  47403. this.currentFrame = currentFrame;
  47404. var keys = this._animation.getKeys();
  47405. // Try to get a hash to find the right key
  47406. 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));
  47407. if (keys[startKeyIndex].frame >= currentFrame) {
  47408. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47409. startKeyIndex--;
  47410. }
  47411. }
  47412. for (var key = startKeyIndex; key < keys.length; key++) {
  47413. var endKey = keys[key + 1];
  47414. if (endKey.frame >= currentFrame) {
  47415. var startKey = keys[key];
  47416. var startValue = this._getKeyValue(startKey.value);
  47417. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47418. return startValue;
  47419. }
  47420. var endValue = this._getKeyValue(endKey.value);
  47421. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47422. var frameDelta = endKey.frame - startKey.frame;
  47423. // gradient : percent of currentFrame between the frame inf and the frame sup
  47424. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47425. // check for easingFunction and correction of gradient
  47426. var easingFunction = this._animation.getEasingFunction();
  47427. if (easingFunction != null) {
  47428. gradient = easingFunction.ease(gradient);
  47429. }
  47430. switch (this._animation.dataType) {
  47431. // Float
  47432. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47433. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47434. switch (loopMode) {
  47435. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47436. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47437. return floatValue;
  47438. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47439. return offsetValue * repeatCount + floatValue;
  47440. }
  47441. break;
  47442. // Quaternion
  47443. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47444. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47445. switch (loopMode) {
  47446. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47447. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47448. return quatValue;
  47449. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47450. return quatValue.add(offsetValue.scale(repeatCount));
  47451. }
  47452. return quatValue;
  47453. // Vector3
  47454. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47455. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47456. switch (loopMode) {
  47457. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47458. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47459. return vec3Value;
  47460. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47461. return vec3Value.add(offsetValue.scale(repeatCount));
  47462. }
  47463. // Vector2
  47464. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47465. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47466. switch (loopMode) {
  47467. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47468. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47469. return vec2Value;
  47470. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47471. return vec2Value.add(offsetValue.scale(repeatCount));
  47472. }
  47473. // Size
  47474. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47475. switch (loopMode) {
  47476. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47477. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47478. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47479. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47480. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47481. }
  47482. // Color3
  47483. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47484. switch (loopMode) {
  47485. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47486. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47487. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47488. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47489. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47490. }
  47491. // Matrix
  47492. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47493. switch (loopMode) {
  47494. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47495. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47496. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47497. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47498. }
  47499. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47500. return startValue;
  47501. }
  47502. default:
  47503. break;
  47504. }
  47505. break;
  47506. }
  47507. }
  47508. return this._getKeyValue(keys[keys.length - 1].value);
  47509. };
  47510. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  47511. if (blend === void 0) { blend = false; }
  47512. // Set value
  47513. var path;
  47514. var destination;
  47515. var targetPropertyPath = this._animation.targetPropertyPath;
  47516. if (targetPropertyPath.length > 1) {
  47517. var property = this._target[targetPropertyPath[0]];
  47518. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47519. property = property[targetPropertyPath[index]];
  47520. }
  47521. path = targetPropertyPath[targetPropertyPath.length - 1];
  47522. destination = property;
  47523. }
  47524. else {
  47525. path = targetPropertyPath[0];
  47526. destination = this._target;
  47527. }
  47528. // Blending
  47529. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47530. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47531. if (enableBlending && this._blendingFactor <= 1.0) {
  47532. if (!this._originalBlendValue) {
  47533. if (destination[path].clone) {
  47534. this._originalBlendValue = destination[path].clone();
  47535. }
  47536. else {
  47537. this._originalBlendValue = destination[path];
  47538. }
  47539. }
  47540. if (this._originalBlendValue.prototype) {
  47541. if (this._originalBlendValue.prototype.Lerp) {
  47542. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47543. }
  47544. else {
  47545. destination[path] = currentValue;
  47546. }
  47547. }
  47548. else if (this._originalBlendValue.m) {
  47549. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47550. }
  47551. else {
  47552. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47553. }
  47554. this._blendingFactor += blendingSpeed;
  47555. }
  47556. else {
  47557. destination[path] = currentValue;
  47558. }
  47559. if (this._target.markAsDirty) {
  47560. this._target.markAsDirty(this._animation.targetProperty);
  47561. }
  47562. };
  47563. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47564. if (this._target && this._target.animationPropertiesOverride) {
  47565. return this._target.animationPropertiesOverride.loopMode;
  47566. }
  47567. return this._animation.loopMode;
  47568. };
  47569. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47570. var keys = this._animation.getKeys();
  47571. if (frame < keys[0].frame) {
  47572. frame = keys[0].frame;
  47573. }
  47574. else if (frame > keys[keys.length - 1].frame) {
  47575. frame = keys[keys.length - 1].frame;
  47576. }
  47577. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  47578. this.setValue(currentValue);
  47579. };
  47580. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47581. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47582. this._ratioOffset = this._previousRatio - newRatio;
  47583. };
  47584. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  47585. if (blend === void 0) { blend = false; }
  47586. var targetPropertyPath = this._animation.targetPropertyPath;
  47587. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47588. this._stopped = true;
  47589. return false;
  47590. }
  47591. var returnValue = true;
  47592. var keys = this._animation.getKeys();
  47593. // Adding a start key at frame 0 if missing
  47594. if (keys[0].frame !== 0) {
  47595. var newKey = { frame: 0, value: keys[0].value };
  47596. keys.splice(0, 0, newKey);
  47597. }
  47598. // Check limits
  47599. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  47600. from = keys[0].frame;
  47601. }
  47602. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  47603. to = keys[keys.length - 1].frame;
  47604. }
  47605. //to and from cannot be the same key
  47606. if (from === to) {
  47607. if (from > keys[0].frame) {
  47608. from--;
  47609. }
  47610. else if (to < keys[keys.length - 1].frame) {
  47611. to++;
  47612. }
  47613. }
  47614. // Compute ratio
  47615. var range = to - from;
  47616. var offsetValue;
  47617. // ratio represents the frame delta between from and to
  47618. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  47619. var highLimitValue = 0;
  47620. this._previousDelay = delay;
  47621. this._previousRatio = ratio;
  47622. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  47623. returnValue = false;
  47624. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  47625. }
  47626. else {
  47627. // Get max value if required
  47628. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  47629. var keyOffset = to.toString() + from.toString();
  47630. if (!this._offsetsCache[keyOffset]) {
  47631. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47632. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47633. switch (this._animation.dataType) {
  47634. // Float
  47635. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47636. this._offsetsCache[keyOffset] = toValue - fromValue;
  47637. break;
  47638. // Quaternion
  47639. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47640. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47641. break;
  47642. // Vector3
  47643. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47644. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47645. // Vector2
  47646. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47647. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47648. // Size
  47649. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47650. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47651. // Color3
  47652. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47653. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47654. default:
  47655. break;
  47656. }
  47657. this._highLimitsCache[keyOffset] = toValue;
  47658. }
  47659. highLimitValue = this._highLimitsCache[keyOffset];
  47660. offsetValue = this._offsetsCache[keyOffset];
  47661. }
  47662. }
  47663. if (offsetValue === undefined) {
  47664. switch (this._animation.dataType) {
  47665. // Float
  47666. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47667. offsetValue = 0;
  47668. break;
  47669. // Quaternion
  47670. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47671. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  47672. break;
  47673. // Vector3
  47674. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47675. offsetValue = BABYLON.Vector3.Zero();
  47676. break;
  47677. // Vector2
  47678. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47679. offsetValue = BABYLON.Vector2.Zero();
  47680. break;
  47681. // Size
  47682. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47683. offsetValue = BABYLON.Size.Zero();
  47684. break;
  47685. // Color3
  47686. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47687. offsetValue = BABYLON.Color3.Black();
  47688. }
  47689. }
  47690. // Compute value
  47691. var repeatCount = (ratio / range) >> 0;
  47692. var currentFrame = returnValue ? from + ratio % range : to;
  47693. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  47694. // Set value
  47695. this.setValue(currentValue);
  47696. // Check events
  47697. var events = this._animation.getEvents();
  47698. for (var index = 0; index < events.length; index++) {
  47699. // Make sure current frame has passed event frame and that event frame is within the current range
  47700. // Also, handle both forward and reverse animations
  47701. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  47702. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  47703. var event = events[index];
  47704. if (!event.isDone) {
  47705. // If event should be done only once, remove it.
  47706. if (event.onlyOnce) {
  47707. events.splice(index, 1);
  47708. index--;
  47709. }
  47710. event.isDone = true;
  47711. event.action();
  47712. } // Don't do anything if the event has already be done.
  47713. }
  47714. else if (events[index].isDone && !events[index].onlyOnce) {
  47715. // reset event, the animation is looping
  47716. events[index].isDone = false;
  47717. }
  47718. }
  47719. if (!returnValue) {
  47720. this._stopped = true;
  47721. }
  47722. return returnValue;
  47723. };
  47724. return RuntimeAnimation;
  47725. }());
  47726. BABYLON.RuntimeAnimation = RuntimeAnimation;
  47727. })(BABYLON || (BABYLON = {}));
  47728. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  47729. var BABYLON;
  47730. (function (BABYLON) {
  47731. var Animatable = /** @class */ (function () {
  47732. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  47733. if (fromFrame === void 0) { fromFrame = 0; }
  47734. if (toFrame === void 0) { toFrame = 100; }
  47735. if (loopAnimation === void 0) { loopAnimation = false; }
  47736. if (speedRatio === void 0) { speedRatio = 1.0; }
  47737. this.target = target;
  47738. this.fromFrame = fromFrame;
  47739. this.toFrame = toFrame;
  47740. this.loopAnimation = loopAnimation;
  47741. this.onAnimationEnd = onAnimationEnd;
  47742. this._localDelayOffset = null;
  47743. this._pausedDelay = null;
  47744. this._runtimeAnimations = new Array();
  47745. this._paused = false;
  47746. this._speedRatio = 1;
  47747. this.animationStarted = false;
  47748. if (animations) {
  47749. this.appendAnimations(target, animations);
  47750. }
  47751. this._speedRatio = speedRatio;
  47752. this._scene = scene;
  47753. scene._activeAnimatables.push(this);
  47754. }
  47755. Object.defineProperty(Animatable.prototype, "speedRatio", {
  47756. get: function () {
  47757. return this._speedRatio;
  47758. },
  47759. set: function (value) {
  47760. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  47761. var animation = this._runtimeAnimations[index];
  47762. animation._prepareForSpeedRatioChange(value);
  47763. }
  47764. this._speedRatio = value;
  47765. },
  47766. enumerable: true,
  47767. configurable: true
  47768. });
  47769. // Methods
  47770. Animatable.prototype.getAnimations = function () {
  47771. return this._runtimeAnimations;
  47772. };
  47773. Animatable.prototype.appendAnimations = function (target, animations) {
  47774. for (var index = 0; index < animations.length; index++) {
  47775. var animation = animations[index];
  47776. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  47777. }
  47778. };
  47779. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  47780. var runtimeAnimations = this._runtimeAnimations;
  47781. for (var index = 0; index < runtimeAnimations.length; index++) {
  47782. if (runtimeAnimations[index].animation.targetProperty === property) {
  47783. return runtimeAnimations[index].animation;
  47784. }
  47785. }
  47786. return null;
  47787. };
  47788. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  47789. var runtimeAnimations = this._runtimeAnimations;
  47790. for (var index = 0; index < runtimeAnimations.length; index++) {
  47791. if (runtimeAnimations[index].animation.targetProperty === property) {
  47792. return runtimeAnimations[index];
  47793. }
  47794. }
  47795. return null;
  47796. };
  47797. Animatable.prototype.reset = function () {
  47798. var runtimeAnimations = this._runtimeAnimations;
  47799. for (var index = 0; index < runtimeAnimations.length; index++) {
  47800. runtimeAnimations[index].reset();
  47801. }
  47802. // Reset to original value
  47803. for (index = 0; index < runtimeAnimations.length; index++) {
  47804. var animation = runtimeAnimations[index];
  47805. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  47806. }
  47807. this._localDelayOffset = null;
  47808. this._pausedDelay = null;
  47809. };
  47810. Animatable.prototype.enableBlending = function (blendingSpeed) {
  47811. var runtimeAnimations = this._runtimeAnimations;
  47812. for (var index = 0; index < runtimeAnimations.length; index++) {
  47813. runtimeAnimations[index].animation.enableBlending = true;
  47814. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  47815. }
  47816. };
  47817. Animatable.prototype.disableBlending = function () {
  47818. var runtimeAnimations = this._runtimeAnimations;
  47819. for (var index = 0; index < runtimeAnimations.length; index++) {
  47820. runtimeAnimations[index].animation.enableBlending = false;
  47821. }
  47822. };
  47823. Animatable.prototype.goToFrame = function (frame) {
  47824. var runtimeAnimations = this._runtimeAnimations;
  47825. if (runtimeAnimations[0]) {
  47826. var fps = runtimeAnimations[0].animation.framePerSecond;
  47827. var currentFrame = runtimeAnimations[0].currentFrame;
  47828. var adjustTime = frame - currentFrame;
  47829. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  47830. if (this._localDelayOffset === null) {
  47831. this._localDelayOffset = 0;
  47832. }
  47833. this._localDelayOffset -= delay;
  47834. }
  47835. for (var index = 0; index < runtimeAnimations.length; index++) {
  47836. runtimeAnimations[index].goToFrame(frame);
  47837. }
  47838. };
  47839. Animatable.prototype.pause = function () {
  47840. if (this._paused) {
  47841. return;
  47842. }
  47843. this._paused = true;
  47844. };
  47845. Animatable.prototype.restart = function () {
  47846. this._paused = false;
  47847. };
  47848. Animatable.prototype.stop = function (animationName) {
  47849. if (animationName) {
  47850. var idx = this._scene._activeAnimatables.indexOf(this);
  47851. if (idx > -1) {
  47852. var runtimeAnimations = this._runtimeAnimations;
  47853. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47854. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47855. continue;
  47856. }
  47857. runtimeAnimations[index].dispose();
  47858. runtimeAnimations.splice(index, 1);
  47859. }
  47860. if (runtimeAnimations.length == 0) {
  47861. this._scene._activeAnimatables.splice(idx, 1);
  47862. if (this.onAnimationEnd) {
  47863. this.onAnimationEnd();
  47864. }
  47865. }
  47866. }
  47867. }
  47868. else {
  47869. var index = this._scene._activeAnimatables.indexOf(this);
  47870. if (index > -1) {
  47871. this._scene._activeAnimatables.splice(index, 1);
  47872. var runtimeAnimations = this._runtimeAnimations;
  47873. for (var index = 0; index < runtimeAnimations.length; index++) {
  47874. runtimeAnimations[index].dispose();
  47875. }
  47876. if (this.onAnimationEnd) {
  47877. this.onAnimationEnd();
  47878. }
  47879. }
  47880. }
  47881. };
  47882. Animatable.prototype._animate = function (delay) {
  47883. if (this._paused) {
  47884. this.animationStarted = false;
  47885. if (this._pausedDelay === null) {
  47886. this._pausedDelay = delay;
  47887. }
  47888. return true;
  47889. }
  47890. if (this._localDelayOffset === null) {
  47891. this._localDelayOffset = delay;
  47892. this._pausedDelay = null;
  47893. }
  47894. else if (this._pausedDelay !== null) {
  47895. this._localDelayOffset += delay - this._pausedDelay;
  47896. this._pausedDelay = null;
  47897. }
  47898. // Animating
  47899. var running = false;
  47900. var runtimeAnimations = this._runtimeAnimations;
  47901. var index;
  47902. for (index = 0; index < runtimeAnimations.length; index++) {
  47903. var animation = runtimeAnimations[index];
  47904. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47905. running = running || isRunning;
  47906. }
  47907. this.animationStarted = running;
  47908. if (!running) {
  47909. // Remove from active animatables
  47910. index = this._scene._activeAnimatables.indexOf(this);
  47911. this._scene._activeAnimatables.splice(index, 1);
  47912. // Dispose all runtime animations
  47913. for (index = 0; index < runtimeAnimations.length; index++) {
  47914. runtimeAnimations[index].dispose();
  47915. }
  47916. }
  47917. if (!running && this.onAnimationEnd) {
  47918. this.onAnimationEnd();
  47919. this.onAnimationEnd = null;
  47920. }
  47921. return running;
  47922. };
  47923. return Animatable;
  47924. }());
  47925. BABYLON.Animatable = Animatable;
  47926. })(BABYLON || (BABYLON = {}));
  47927. //# sourceMappingURL=babylon.animatable.js.map
  47928. var BABYLON;
  47929. (function (BABYLON) {
  47930. var EasingFunction = /** @class */ (function () {
  47931. function EasingFunction() {
  47932. // Properties
  47933. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47934. }
  47935. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47936. get: function () {
  47937. return EasingFunction._EASINGMODE_EASEIN;
  47938. },
  47939. enumerable: true,
  47940. configurable: true
  47941. });
  47942. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47943. get: function () {
  47944. return EasingFunction._EASINGMODE_EASEOUT;
  47945. },
  47946. enumerable: true,
  47947. configurable: true
  47948. });
  47949. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47950. get: function () {
  47951. return EasingFunction._EASINGMODE_EASEINOUT;
  47952. },
  47953. enumerable: true,
  47954. configurable: true
  47955. });
  47956. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47957. var n = Math.min(Math.max(easingMode, 0), 2);
  47958. this._easingMode = n;
  47959. };
  47960. EasingFunction.prototype.getEasingMode = function () {
  47961. return this._easingMode;
  47962. };
  47963. EasingFunction.prototype.easeInCore = function (gradient) {
  47964. throw new Error('You must implement this method');
  47965. };
  47966. EasingFunction.prototype.ease = function (gradient) {
  47967. switch (this._easingMode) {
  47968. case EasingFunction.EASINGMODE_EASEIN:
  47969. return this.easeInCore(gradient);
  47970. case EasingFunction.EASINGMODE_EASEOUT:
  47971. return (1 - this.easeInCore(1 - gradient));
  47972. }
  47973. if (gradient >= 0.5) {
  47974. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47975. }
  47976. return (this.easeInCore(gradient * 2) * 0.5);
  47977. };
  47978. //Statics
  47979. EasingFunction._EASINGMODE_EASEIN = 0;
  47980. EasingFunction._EASINGMODE_EASEOUT = 1;
  47981. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47982. return EasingFunction;
  47983. }());
  47984. BABYLON.EasingFunction = EasingFunction;
  47985. var CircleEase = /** @class */ (function (_super) {
  47986. __extends(CircleEase, _super);
  47987. function CircleEase() {
  47988. return _super !== null && _super.apply(this, arguments) || this;
  47989. }
  47990. CircleEase.prototype.easeInCore = function (gradient) {
  47991. gradient = Math.max(0, Math.min(1, gradient));
  47992. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47993. };
  47994. return CircleEase;
  47995. }(EasingFunction));
  47996. BABYLON.CircleEase = CircleEase;
  47997. var BackEase = /** @class */ (function (_super) {
  47998. __extends(BackEase, _super);
  47999. function BackEase(amplitude) {
  48000. if (amplitude === void 0) { amplitude = 1; }
  48001. var _this = _super.call(this) || this;
  48002. _this.amplitude = amplitude;
  48003. return _this;
  48004. }
  48005. BackEase.prototype.easeInCore = function (gradient) {
  48006. var num = Math.max(0, this.amplitude);
  48007. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  48008. };
  48009. return BackEase;
  48010. }(EasingFunction));
  48011. BABYLON.BackEase = BackEase;
  48012. var BounceEase = /** @class */ (function (_super) {
  48013. __extends(BounceEase, _super);
  48014. function BounceEase(bounces, bounciness) {
  48015. if (bounces === void 0) { bounces = 3; }
  48016. if (bounciness === void 0) { bounciness = 2; }
  48017. var _this = _super.call(this) || this;
  48018. _this.bounces = bounces;
  48019. _this.bounciness = bounciness;
  48020. return _this;
  48021. }
  48022. BounceEase.prototype.easeInCore = function (gradient) {
  48023. var y = Math.max(0.0, this.bounces);
  48024. var bounciness = this.bounciness;
  48025. if (bounciness <= 1.0) {
  48026. bounciness = 1.001;
  48027. }
  48028. var num9 = Math.pow(bounciness, y);
  48029. var num5 = 1.0 - bounciness;
  48030. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  48031. var num15 = gradient * num4;
  48032. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  48033. var num3 = Math.floor(num65);
  48034. var num13 = num3 + 1.0;
  48035. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  48036. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  48037. var num7 = (num8 + num12) * 0.5;
  48038. var num6 = gradient - num7;
  48039. var num2 = num7 - num8;
  48040. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  48041. };
  48042. return BounceEase;
  48043. }(EasingFunction));
  48044. BABYLON.BounceEase = BounceEase;
  48045. var CubicEase = /** @class */ (function (_super) {
  48046. __extends(CubicEase, _super);
  48047. function CubicEase() {
  48048. return _super !== null && _super.apply(this, arguments) || this;
  48049. }
  48050. CubicEase.prototype.easeInCore = function (gradient) {
  48051. return (gradient * gradient * gradient);
  48052. };
  48053. return CubicEase;
  48054. }(EasingFunction));
  48055. BABYLON.CubicEase = CubicEase;
  48056. var ElasticEase = /** @class */ (function (_super) {
  48057. __extends(ElasticEase, _super);
  48058. function ElasticEase(oscillations, springiness) {
  48059. if (oscillations === void 0) { oscillations = 3; }
  48060. if (springiness === void 0) { springiness = 3; }
  48061. var _this = _super.call(this) || this;
  48062. _this.oscillations = oscillations;
  48063. _this.springiness = springiness;
  48064. return _this;
  48065. }
  48066. ElasticEase.prototype.easeInCore = function (gradient) {
  48067. var num2;
  48068. var num3 = Math.max(0.0, this.oscillations);
  48069. var num = Math.max(0.0, this.springiness);
  48070. if (num == 0) {
  48071. num2 = gradient;
  48072. }
  48073. else {
  48074. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  48075. }
  48076. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  48077. };
  48078. return ElasticEase;
  48079. }(EasingFunction));
  48080. BABYLON.ElasticEase = ElasticEase;
  48081. var ExponentialEase = /** @class */ (function (_super) {
  48082. __extends(ExponentialEase, _super);
  48083. function ExponentialEase(exponent) {
  48084. if (exponent === void 0) { exponent = 2; }
  48085. var _this = _super.call(this) || this;
  48086. _this.exponent = exponent;
  48087. return _this;
  48088. }
  48089. ExponentialEase.prototype.easeInCore = function (gradient) {
  48090. if (this.exponent <= 0) {
  48091. return gradient;
  48092. }
  48093. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  48094. };
  48095. return ExponentialEase;
  48096. }(EasingFunction));
  48097. BABYLON.ExponentialEase = ExponentialEase;
  48098. var PowerEase = /** @class */ (function (_super) {
  48099. __extends(PowerEase, _super);
  48100. function PowerEase(power) {
  48101. if (power === void 0) { power = 2; }
  48102. var _this = _super.call(this) || this;
  48103. _this.power = power;
  48104. return _this;
  48105. }
  48106. PowerEase.prototype.easeInCore = function (gradient) {
  48107. var y = Math.max(0.0, this.power);
  48108. return Math.pow(gradient, y);
  48109. };
  48110. return PowerEase;
  48111. }(EasingFunction));
  48112. BABYLON.PowerEase = PowerEase;
  48113. var QuadraticEase = /** @class */ (function (_super) {
  48114. __extends(QuadraticEase, _super);
  48115. function QuadraticEase() {
  48116. return _super !== null && _super.apply(this, arguments) || this;
  48117. }
  48118. QuadraticEase.prototype.easeInCore = function (gradient) {
  48119. return (gradient * gradient);
  48120. };
  48121. return QuadraticEase;
  48122. }(EasingFunction));
  48123. BABYLON.QuadraticEase = QuadraticEase;
  48124. var QuarticEase = /** @class */ (function (_super) {
  48125. __extends(QuarticEase, _super);
  48126. function QuarticEase() {
  48127. return _super !== null && _super.apply(this, arguments) || this;
  48128. }
  48129. QuarticEase.prototype.easeInCore = function (gradient) {
  48130. return (gradient * gradient * gradient * gradient);
  48131. };
  48132. return QuarticEase;
  48133. }(EasingFunction));
  48134. BABYLON.QuarticEase = QuarticEase;
  48135. var QuinticEase = /** @class */ (function (_super) {
  48136. __extends(QuinticEase, _super);
  48137. function QuinticEase() {
  48138. return _super !== null && _super.apply(this, arguments) || this;
  48139. }
  48140. QuinticEase.prototype.easeInCore = function (gradient) {
  48141. return (gradient * gradient * gradient * gradient * gradient);
  48142. };
  48143. return QuinticEase;
  48144. }(EasingFunction));
  48145. BABYLON.QuinticEase = QuinticEase;
  48146. var SineEase = /** @class */ (function (_super) {
  48147. __extends(SineEase, _super);
  48148. function SineEase() {
  48149. return _super !== null && _super.apply(this, arguments) || this;
  48150. }
  48151. SineEase.prototype.easeInCore = function (gradient) {
  48152. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  48153. };
  48154. return SineEase;
  48155. }(EasingFunction));
  48156. BABYLON.SineEase = SineEase;
  48157. var BezierCurveEase = /** @class */ (function (_super) {
  48158. __extends(BezierCurveEase, _super);
  48159. function BezierCurveEase(x1, y1, x2, y2) {
  48160. if (x1 === void 0) { x1 = 0; }
  48161. if (y1 === void 0) { y1 = 0; }
  48162. if (x2 === void 0) { x2 = 1; }
  48163. if (y2 === void 0) { y2 = 1; }
  48164. var _this = _super.call(this) || this;
  48165. _this.x1 = x1;
  48166. _this.y1 = y1;
  48167. _this.x2 = x2;
  48168. _this.y2 = y2;
  48169. return _this;
  48170. }
  48171. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48172. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48173. };
  48174. return BezierCurveEase;
  48175. }(EasingFunction));
  48176. BABYLON.BezierCurveEase = BezierCurveEase;
  48177. })(BABYLON || (BABYLON = {}));
  48178. //# sourceMappingURL=babylon.easing.js.map
  48179. var BABYLON;
  48180. (function (BABYLON) {
  48181. var Condition = /** @class */ (function () {
  48182. function Condition(actionManager) {
  48183. this._actionManager = actionManager;
  48184. }
  48185. Condition.prototype.isValid = function () {
  48186. return true;
  48187. };
  48188. Condition.prototype._getProperty = function (propertyPath) {
  48189. return this._actionManager._getProperty(propertyPath);
  48190. };
  48191. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48192. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48193. };
  48194. Condition.prototype.serialize = function () {
  48195. };
  48196. Condition.prototype._serialize = function (serializedCondition) {
  48197. return {
  48198. type: 2,
  48199. children: [],
  48200. name: serializedCondition.name,
  48201. properties: serializedCondition.properties
  48202. };
  48203. };
  48204. return Condition;
  48205. }());
  48206. BABYLON.Condition = Condition;
  48207. var ValueCondition = /** @class */ (function (_super) {
  48208. __extends(ValueCondition, _super);
  48209. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48210. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48211. var _this = _super.call(this, actionManager) || this;
  48212. _this.propertyPath = propertyPath;
  48213. _this.value = value;
  48214. _this.operator = operator;
  48215. _this._target = target;
  48216. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48217. _this._property = _this._getProperty(_this.propertyPath);
  48218. return _this;
  48219. }
  48220. Object.defineProperty(ValueCondition, "IsEqual", {
  48221. get: function () {
  48222. return ValueCondition._IsEqual;
  48223. },
  48224. enumerable: true,
  48225. configurable: true
  48226. });
  48227. Object.defineProperty(ValueCondition, "IsDifferent", {
  48228. get: function () {
  48229. return ValueCondition._IsDifferent;
  48230. },
  48231. enumerable: true,
  48232. configurable: true
  48233. });
  48234. Object.defineProperty(ValueCondition, "IsGreater", {
  48235. get: function () {
  48236. return ValueCondition._IsGreater;
  48237. },
  48238. enumerable: true,
  48239. configurable: true
  48240. });
  48241. Object.defineProperty(ValueCondition, "IsLesser", {
  48242. get: function () {
  48243. return ValueCondition._IsLesser;
  48244. },
  48245. enumerable: true,
  48246. configurable: true
  48247. });
  48248. // Methods
  48249. ValueCondition.prototype.isValid = function () {
  48250. switch (this.operator) {
  48251. case ValueCondition.IsGreater:
  48252. return this._effectiveTarget[this._property] > this.value;
  48253. case ValueCondition.IsLesser:
  48254. return this._effectiveTarget[this._property] < this.value;
  48255. case ValueCondition.IsEqual:
  48256. case ValueCondition.IsDifferent:
  48257. var check;
  48258. if (this.value.equals) {
  48259. check = this.value.equals(this._effectiveTarget[this._property]);
  48260. }
  48261. else {
  48262. check = this.value === this._effectiveTarget[this._property];
  48263. }
  48264. return this.operator === ValueCondition.IsEqual ? check : !check;
  48265. }
  48266. return false;
  48267. };
  48268. ValueCondition.prototype.serialize = function () {
  48269. return this._serialize({
  48270. name: "ValueCondition",
  48271. properties: [
  48272. BABYLON.Action._GetTargetProperty(this._target),
  48273. { name: "propertyPath", value: this.propertyPath },
  48274. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48275. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48276. ]
  48277. });
  48278. };
  48279. ValueCondition.GetOperatorName = function (operator) {
  48280. switch (operator) {
  48281. case ValueCondition._IsEqual: return "IsEqual";
  48282. case ValueCondition._IsDifferent: return "IsDifferent";
  48283. case ValueCondition._IsGreater: return "IsGreater";
  48284. case ValueCondition._IsLesser: return "IsLesser";
  48285. default: return "";
  48286. }
  48287. };
  48288. // Statics
  48289. ValueCondition._IsEqual = 0;
  48290. ValueCondition._IsDifferent = 1;
  48291. ValueCondition._IsGreater = 2;
  48292. ValueCondition._IsLesser = 3;
  48293. return ValueCondition;
  48294. }(Condition));
  48295. BABYLON.ValueCondition = ValueCondition;
  48296. var PredicateCondition = /** @class */ (function (_super) {
  48297. __extends(PredicateCondition, _super);
  48298. function PredicateCondition(actionManager, predicate) {
  48299. var _this = _super.call(this, actionManager) || this;
  48300. _this.predicate = predicate;
  48301. return _this;
  48302. }
  48303. PredicateCondition.prototype.isValid = function () {
  48304. return this.predicate();
  48305. };
  48306. return PredicateCondition;
  48307. }(Condition));
  48308. BABYLON.PredicateCondition = PredicateCondition;
  48309. var StateCondition = /** @class */ (function (_super) {
  48310. __extends(StateCondition, _super);
  48311. function StateCondition(actionManager, target, value) {
  48312. var _this = _super.call(this, actionManager) || this;
  48313. _this.value = value;
  48314. _this._target = target;
  48315. return _this;
  48316. }
  48317. // Methods
  48318. StateCondition.prototype.isValid = function () {
  48319. return this._target.state === this.value;
  48320. };
  48321. StateCondition.prototype.serialize = function () {
  48322. return this._serialize({
  48323. name: "StateCondition",
  48324. properties: [
  48325. BABYLON.Action._GetTargetProperty(this._target),
  48326. { name: "value", value: this.value }
  48327. ]
  48328. });
  48329. };
  48330. return StateCondition;
  48331. }(Condition));
  48332. BABYLON.StateCondition = StateCondition;
  48333. })(BABYLON || (BABYLON = {}));
  48334. //# sourceMappingURL=babylon.condition.js.map
  48335. var BABYLON;
  48336. (function (BABYLON) {
  48337. var Action = /** @class */ (function () {
  48338. function Action(triggerOptions, condition) {
  48339. this.triggerOptions = triggerOptions;
  48340. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48341. if (triggerOptions.parameter) {
  48342. this.trigger = triggerOptions.trigger;
  48343. this._triggerParameter = triggerOptions.parameter;
  48344. }
  48345. else {
  48346. this.trigger = triggerOptions;
  48347. }
  48348. this._nextActiveAction = this;
  48349. this._condition = condition;
  48350. }
  48351. // Methods
  48352. Action.prototype._prepare = function () {
  48353. };
  48354. Action.prototype.getTriggerParameter = function () {
  48355. return this._triggerParameter;
  48356. };
  48357. Action.prototype._executeCurrent = function (evt) {
  48358. if (this._nextActiveAction._condition) {
  48359. var condition = this._nextActiveAction._condition;
  48360. var currentRenderId = this._actionManager.getScene().getRenderId();
  48361. // We cache the current evaluation for the current frame
  48362. if (condition._evaluationId === currentRenderId) {
  48363. if (!condition._currentResult) {
  48364. return;
  48365. }
  48366. }
  48367. else {
  48368. condition._evaluationId = currentRenderId;
  48369. if (!condition.isValid()) {
  48370. condition._currentResult = false;
  48371. return;
  48372. }
  48373. condition._currentResult = true;
  48374. }
  48375. }
  48376. this.onBeforeExecuteObservable.notifyObservers(this);
  48377. this._nextActiveAction.execute(evt);
  48378. this.skipToNextActiveAction();
  48379. };
  48380. Action.prototype.execute = function (evt) {
  48381. };
  48382. Action.prototype.skipToNextActiveAction = function () {
  48383. if (this._nextActiveAction._child) {
  48384. if (!this._nextActiveAction._child._actionManager) {
  48385. this._nextActiveAction._child._actionManager = this._actionManager;
  48386. }
  48387. this._nextActiveAction = this._nextActiveAction._child;
  48388. }
  48389. else {
  48390. this._nextActiveAction = this;
  48391. }
  48392. };
  48393. Action.prototype.then = function (action) {
  48394. this._child = action;
  48395. action._actionManager = this._actionManager;
  48396. action._prepare();
  48397. return action;
  48398. };
  48399. Action.prototype._getProperty = function (propertyPath) {
  48400. return this._actionManager._getProperty(propertyPath);
  48401. };
  48402. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48403. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48404. };
  48405. Action.prototype.serialize = function (parent) {
  48406. };
  48407. // Called by BABYLON.Action objects in serialize(...). Internal use
  48408. Action.prototype._serialize = function (serializedAction, parent) {
  48409. var serializationObject = {
  48410. type: 1,
  48411. children: [],
  48412. name: serializedAction.name,
  48413. properties: serializedAction.properties || []
  48414. };
  48415. // Serialize child
  48416. if (this._child) {
  48417. this._child.serialize(serializationObject);
  48418. }
  48419. // Check if "this" has a condition
  48420. if (this._condition) {
  48421. var serializedCondition = this._condition.serialize();
  48422. serializedCondition.children.push(serializationObject);
  48423. if (parent) {
  48424. parent.children.push(serializedCondition);
  48425. }
  48426. return serializedCondition;
  48427. }
  48428. if (parent) {
  48429. parent.children.push(serializationObject);
  48430. }
  48431. return serializationObject;
  48432. };
  48433. Action._SerializeValueAsString = function (value) {
  48434. if (typeof value === "number") {
  48435. return value.toString();
  48436. }
  48437. if (typeof value === "boolean") {
  48438. return value ? "true" : "false";
  48439. }
  48440. if (value instanceof BABYLON.Vector2) {
  48441. return value.x + ", " + value.y;
  48442. }
  48443. if (value instanceof BABYLON.Vector3) {
  48444. return value.x + ", " + value.y + ", " + value.z;
  48445. }
  48446. if (value instanceof BABYLON.Color3) {
  48447. return value.r + ", " + value.g + ", " + value.b;
  48448. }
  48449. if (value instanceof BABYLON.Color4) {
  48450. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48451. }
  48452. return value; // string
  48453. };
  48454. Action._GetTargetProperty = function (target) {
  48455. return {
  48456. name: "target",
  48457. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48458. : target instanceof BABYLON.Light ? "LightProperties"
  48459. : target instanceof BABYLON.Camera ? "CameraProperties"
  48460. : "SceneProperties",
  48461. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48462. };
  48463. };
  48464. return Action;
  48465. }());
  48466. BABYLON.Action = Action;
  48467. })(BABYLON || (BABYLON = {}));
  48468. //# sourceMappingURL=babylon.action.js.map
  48469. var BABYLON;
  48470. (function (BABYLON) {
  48471. /**
  48472. * ActionEvent is the event beint sent when an action is triggered.
  48473. */
  48474. var ActionEvent = /** @class */ (function () {
  48475. /**
  48476. * @param source The mesh or sprite that triggered the action.
  48477. * @param pointerX The X mouse cursor position at the time of the event
  48478. * @param pointerY The Y mouse cursor position at the time of the event
  48479. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48480. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48481. */
  48482. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48483. this.source = source;
  48484. this.pointerX = pointerX;
  48485. this.pointerY = pointerY;
  48486. this.meshUnderPointer = meshUnderPointer;
  48487. this.sourceEvent = sourceEvent;
  48488. this.additionalData = additionalData;
  48489. }
  48490. /**
  48491. * Helper function to auto-create an ActionEvent from a source mesh.
  48492. * @param source The source mesh that triggered the event
  48493. * @param evt {Event} The original (browser) event
  48494. */
  48495. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48496. var scene = source.getScene();
  48497. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48498. };
  48499. /**
  48500. * Helper function to auto-create an ActionEvent from a source mesh.
  48501. * @param source The source sprite that triggered the event
  48502. * @param scene Scene associated with the sprite
  48503. * @param evt {Event} The original (browser) event
  48504. */
  48505. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48506. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48507. };
  48508. /**
  48509. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48510. * @param scene the scene where the event occurred
  48511. * @param evt {Event} The original (browser) event
  48512. */
  48513. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48514. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48515. };
  48516. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48517. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48518. };
  48519. return ActionEvent;
  48520. }());
  48521. BABYLON.ActionEvent = ActionEvent;
  48522. /**
  48523. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48524. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48525. */
  48526. var ActionManager = /** @class */ (function () {
  48527. function ActionManager(scene) {
  48528. // Members
  48529. this.actions = new Array();
  48530. this.hoverCursor = '';
  48531. this._scene = scene;
  48532. scene._actionManagers.push(this);
  48533. }
  48534. Object.defineProperty(ActionManager, "NothingTrigger", {
  48535. get: function () {
  48536. return ActionManager._NothingTrigger;
  48537. },
  48538. enumerable: true,
  48539. configurable: true
  48540. });
  48541. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48542. get: function () {
  48543. return ActionManager._OnPickTrigger;
  48544. },
  48545. enumerable: true,
  48546. configurable: true
  48547. });
  48548. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48549. get: function () {
  48550. return ActionManager._OnLeftPickTrigger;
  48551. },
  48552. enumerable: true,
  48553. configurable: true
  48554. });
  48555. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  48556. get: function () {
  48557. return ActionManager._OnRightPickTrigger;
  48558. },
  48559. enumerable: true,
  48560. configurable: true
  48561. });
  48562. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  48563. get: function () {
  48564. return ActionManager._OnCenterPickTrigger;
  48565. },
  48566. enumerable: true,
  48567. configurable: true
  48568. });
  48569. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  48570. get: function () {
  48571. return ActionManager._OnPickDownTrigger;
  48572. },
  48573. enumerable: true,
  48574. configurable: true
  48575. });
  48576. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  48577. get: function () {
  48578. return ActionManager._OnDoublePickTrigger;
  48579. },
  48580. enumerable: true,
  48581. configurable: true
  48582. });
  48583. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  48584. get: function () {
  48585. return ActionManager._OnPickUpTrigger;
  48586. },
  48587. enumerable: true,
  48588. configurable: true
  48589. });
  48590. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  48591. /// This trigger will only be raised if you also declared a OnPickDown
  48592. get: function () {
  48593. return ActionManager._OnPickOutTrigger;
  48594. },
  48595. enumerable: true,
  48596. configurable: true
  48597. });
  48598. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  48599. get: function () {
  48600. return ActionManager._OnLongPressTrigger;
  48601. },
  48602. enumerable: true,
  48603. configurable: true
  48604. });
  48605. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  48606. get: function () {
  48607. return ActionManager._OnPointerOverTrigger;
  48608. },
  48609. enumerable: true,
  48610. configurable: true
  48611. });
  48612. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  48613. get: function () {
  48614. return ActionManager._OnPointerOutTrigger;
  48615. },
  48616. enumerable: true,
  48617. configurable: true
  48618. });
  48619. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  48620. get: function () {
  48621. return ActionManager._OnEveryFrameTrigger;
  48622. },
  48623. enumerable: true,
  48624. configurable: true
  48625. });
  48626. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  48627. get: function () {
  48628. return ActionManager._OnIntersectionEnterTrigger;
  48629. },
  48630. enumerable: true,
  48631. configurable: true
  48632. });
  48633. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  48634. get: function () {
  48635. return ActionManager._OnIntersectionExitTrigger;
  48636. },
  48637. enumerable: true,
  48638. configurable: true
  48639. });
  48640. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  48641. get: function () {
  48642. return ActionManager._OnKeyDownTrigger;
  48643. },
  48644. enumerable: true,
  48645. configurable: true
  48646. });
  48647. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  48648. get: function () {
  48649. return ActionManager._OnKeyUpTrigger;
  48650. },
  48651. enumerable: true,
  48652. configurable: true
  48653. });
  48654. // Methods
  48655. ActionManager.prototype.dispose = function () {
  48656. var index = this._scene._actionManagers.indexOf(this);
  48657. for (var i = 0; i < this.actions.length; i++) {
  48658. var action = this.actions[i];
  48659. ActionManager.Triggers[action.trigger]--;
  48660. if (ActionManager.Triggers[action.trigger] === 0) {
  48661. delete ActionManager.Triggers[action.trigger];
  48662. }
  48663. }
  48664. if (index > -1) {
  48665. this._scene._actionManagers.splice(index, 1);
  48666. }
  48667. };
  48668. ActionManager.prototype.getScene = function () {
  48669. return this._scene;
  48670. };
  48671. /**
  48672. * Does this action manager handles actions of any of the given triggers
  48673. * @param {number[]} triggers - the triggers to be tested
  48674. * @return {boolean} whether one (or more) of the triggers is handeled
  48675. */
  48676. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  48677. for (var index = 0; index < this.actions.length; index++) {
  48678. var action = this.actions[index];
  48679. if (triggers.indexOf(action.trigger) > -1) {
  48680. return true;
  48681. }
  48682. }
  48683. return false;
  48684. };
  48685. /**
  48686. * Does this action manager handles actions of a given trigger
  48687. * @param {number} trigger - the trigger to be tested
  48688. * @return {boolean} whether the trigger is handeled
  48689. */
  48690. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  48691. for (var index = 0; index < this.actions.length; index++) {
  48692. var action = this.actions[index];
  48693. if (action.trigger === trigger) {
  48694. return true;
  48695. }
  48696. }
  48697. return false;
  48698. };
  48699. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  48700. /**
  48701. * Does this action manager has pointer triggers
  48702. * @return {boolean} whether or not it has pointer triggers
  48703. */
  48704. get: function () {
  48705. for (var index = 0; index < this.actions.length; index++) {
  48706. var action = this.actions[index];
  48707. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  48708. return true;
  48709. }
  48710. }
  48711. return false;
  48712. },
  48713. enumerable: true,
  48714. configurable: true
  48715. });
  48716. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  48717. /**
  48718. * Does this action manager has pick triggers
  48719. * @return {boolean} whether or not it has pick triggers
  48720. */
  48721. get: function () {
  48722. for (var index = 0; index < this.actions.length; index++) {
  48723. var action = this.actions[index];
  48724. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  48725. return true;
  48726. }
  48727. }
  48728. return false;
  48729. },
  48730. enumerable: true,
  48731. configurable: true
  48732. });
  48733. Object.defineProperty(ActionManager, "HasTriggers", {
  48734. /**
  48735. * Does exist one action manager with at least one trigger
  48736. * @return {boolean} whether or not it exists one action manager with one trigger
  48737. **/
  48738. get: function () {
  48739. for (var t in ActionManager.Triggers) {
  48740. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48741. return true;
  48742. }
  48743. }
  48744. return false;
  48745. },
  48746. enumerable: true,
  48747. configurable: true
  48748. });
  48749. Object.defineProperty(ActionManager, "HasPickTriggers", {
  48750. /**
  48751. * Does exist one action manager with at least one pick trigger
  48752. * @return {boolean} whether or not it exists one action manager with one pick trigger
  48753. **/
  48754. get: function () {
  48755. for (var t in ActionManager.Triggers) {
  48756. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48757. var t_int = parseInt(t);
  48758. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  48759. return true;
  48760. }
  48761. }
  48762. }
  48763. return false;
  48764. },
  48765. enumerable: true,
  48766. configurable: true
  48767. });
  48768. /**
  48769. * Does exist one action manager that handles actions of a given trigger
  48770. * @param {number} trigger - the trigger to be tested
  48771. * @return {boolean} whether the trigger is handeled by at least one action manager
  48772. **/
  48773. ActionManager.HasSpecificTrigger = function (trigger) {
  48774. for (var t in ActionManager.Triggers) {
  48775. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48776. var t_int = parseInt(t);
  48777. if (t_int === trigger) {
  48778. return true;
  48779. }
  48780. }
  48781. }
  48782. return false;
  48783. };
  48784. /**
  48785. * Registers an action to this action manager
  48786. * @param {BABYLON.Action} action - the action to be registered
  48787. * @return {BABYLON.Action} the action amended (prepared) after registration
  48788. */
  48789. ActionManager.prototype.registerAction = function (action) {
  48790. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  48791. if (this.getScene().actionManager !== this) {
  48792. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  48793. return null;
  48794. }
  48795. }
  48796. this.actions.push(action);
  48797. if (ActionManager.Triggers[action.trigger]) {
  48798. ActionManager.Triggers[action.trigger]++;
  48799. }
  48800. else {
  48801. ActionManager.Triggers[action.trigger] = 1;
  48802. }
  48803. action._actionManager = this;
  48804. action._prepare();
  48805. return action;
  48806. };
  48807. /**
  48808. * Unregisters an action to this action manager
  48809. * @param action The action to be unregistered
  48810. * @return whether the action has been unregistered
  48811. */
  48812. ActionManager.prototype.unregisterAction = function (action) {
  48813. var index = this.actions.indexOf(action);
  48814. if (index !== -1) {
  48815. this.actions.splice(index, 1);
  48816. ActionManager.Triggers[action.trigger] -= 1;
  48817. if (ActionManager.Triggers[action.trigger] === 0) {
  48818. delete ActionManager.Triggers[action.trigger];
  48819. }
  48820. delete action._actionManager;
  48821. return true;
  48822. }
  48823. return false;
  48824. };
  48825. /**
  48826. * Process a specific trigger
  48827. * @param {number} trigger - the trigger to process
  48828. * @param evt {BABYLON.ActionEvent} the event details to be processed
  48829. */
  48830. ActionManager.prototype.processTrigger = function (trigger, evt) {
  48831. for (var index = 0; index < this.actions.length; index++) {
  48832. var action = this.actions[index];
  48833. if (action.trigger === trigger) {
  48834. if (evt) {
  48835. if (trigger === ActionManager.OnKeyUpTrigger
  48836. || trigger === ActionManager.OnKeyDownTrigger) {
  48837. var parameter = action.getTriggerParameter();
  48838. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48839. if (!parameter.toLowerCase) {
  48840. continue;
  48841. }
  48842. var lowerCase = parameter.toLowerCase();
  48843. if (lowerCase !== evt.sourceEvent.key) {
  48844. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48845. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48846. if (actualkey !== lowerCase) {
  48847. continue;
  48848. }
  48849. }
  48850. }
  48851. }
  48852. }
  48853. action._executeCurrent(evt);
  48854. }
  48855. }
  48856. };
  48857. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48858. var properties = propertyPath.split(".");
  48859. for (var index = 0; index < properties.length - 1; index++) {
  48860. target = target[properties[index]];
  48861. }
  48862. return target;
  48863. };
  48864. ActionManager.prototype._getProperty = function (propertyPath) {
  48865. var properties = propertyPath.split(".");
  48866. return properties[properties.length - 1];
  48867. };
  48868. ActionManager.prototype.serialize = function (name) {
  48869. var root = {
  48870. children: new Array(),
  48871. name: name,
  48872. type: 3,
  48873. properties: new Array() // Empty for root but required
  48874. };
  48875. for (var i = 0; i < this.actions.length; i++) {
  48876. var triggerObject = {
  48877. type: 0,
  48878. children: new Array(),
  48879. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48880. properties: new Array()
  48881. };
  48882. var triggerOptions = this.actions[i].triggerOptions;
  48883. if (triggerOptions && typeof triggerOptions !== "number") {
  48884. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48885. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48886. }
  48887. else {
  48888. var parameter = {};
  48889. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48890. if (triggerOptions.parameter.mesh) {
  48891. parameter._meshId = triggerOptions.parameter.mesh.id;
  48892. }
  48893. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48894. }
  48895. }
  48896. // Serialize child action, recursively
  48897. this.actions[i].serialize(triggerObject);
  48898. // Add serialized trigger
  48899. root.children.push(triggerObject);
  48900. }
  48901. return root;
  48902. };
  48903. ActionManager.Parse = function (parsedActions, object, scene) {
  48904. var actionManager = new ActionManager(scene);
  48905. if (object === null)
  48906. scene.actionManager = actionManager;
  48907. else
  48908. object.actionManager = actionManager;
  48909. // instanciate a new object
  48910. var instanciate = function (name, params) {
  48911. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48912. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48913. newInstance.constructor.apply(newInstance, params);
  48914. return newInstance;
  48915. };
  48916. var parseParameter = function (name, value, target, propertyPath) {
  48917. if (propertyPath === null) {
  48918. // String, boolean or float
  48919. var floatValue = parseFloat(value);
  48920. if (value === "true" || value === "false")
  48921. return value === "true";
  48922. else
  48923. return isNaN(floatValue) ? value : floatValue;
  48924. }
  48925. var effectiveTarget = propertyPath.split(".");
  48926. var values = value.split(",");
  48927. // Get effective Target
  48928. for (var i = 0; i < effectiveTarget.length; i++) {
  48929. target = target[effectiveTarget[i]];
  48930. }
  48931. // Return appropriate value with its type
  48932. if (typeof (target) === "boolean")
  48933. return values[0] === "true";
  48934. if (typeof (target) === "string")
  48935. return values[0];
  48936. // Parameters with multiple values such as Vector3 etc.
  48937. var split = new Array();
  48938. for (var i = 0; i < values.length; i++)
  48939. split.push(parseFloat(values[i]));
  48940. if (target instanceof BABYLON.Vector3)
  48941. return BABYLON.Vector3.FromArray(split);
  48942. if (target instanceof BABYLON.Vector4)
  48943. return BABYLON.Vector4.FromArray(split);
  48944. if (target instanceof BABYLON.Color3)
  48945. return BABYLON.Color3.FromArray(split);
  48946. if (target instanceof BABYLON.Color4)
  48947. return BABYLON.Color4.FromArray(split);
  48948. return parseFloat(values[0]);
  48949. };
  48950. // traverse graph per trigger
  48951. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48952. if (combineArray === void 0) { combineArray = null; }
  48953. if (parsedAction.detached)
  48954. return;
  48955. var parameters = new Array();
  48956. var target = null;
  48957. var propertyPath = null;
  48958. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48959. // Parameters
  48960. if (parsedAction.type === 2)
  48961. parameters.push(actionManager);
  48962. else
  48963. parameters.push(trigger);
  48964. if (combine) {
  48965. var actions = new Array();
  48966. for (var j = 0; j < parsedAction.combine.length; j++) {
  48967. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48968. }
  48969. parameters.push(actions);
  48970. }
  48971. else {
  48972. for (var i = 0; i < parsedAction.properties.length; i++) {
  48973. var value = parsedAction.properties[i].value;
  48974. var name = parsedAction.properties[i].name;
  48975. var targetType = parsedAction.properties[i].targetType;
  48976. if (name === "target")
  48977. if (targetType !== null && targetType === "SceneProperties")
  48978. value = target = scene;
  48979. else
  48980. value = target = scene.getNodeByName(value);
  48981. else if (name === "parent")
  48982. value = scene.getNodeByName(value);
  48983. else if (name === "sound")
  48984. value = scene.getSoundByName(value);
  48985. else if (name !== "propertyPath") {
  48986. if (parsedAction.type === 2 && name === "operator")
  48987. value = BABYLON.ValueCondition[value];
  48988. else
  48989. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48990. }
  48991. else {
  48992. propertyPath = value;
  48993. }
  48994. parameters.push(value);
  48995. }
  48996. }
  48997. if (combineArray === null) {
  48998. parameters.push(condition);
  48999. }
  49000. else {
  49001. parameters.push(null);
  49002. }
  49003. // If interpolate value action
  49004. if (parsedAction.name === "InterpolateValueAction") {
  49005. var param = parameters[parameters.length - 2];
  49006. parameters[parameters.length - 1] = param;
  49007. parameters[parameters.length - 2] = condition;
  49008. }
  49009. // Action or condition(s) and not CombineAction
  49010. var newAction = instanciate(parsedAction.name, parameters);
  49011. if (newAction instanceof BABYLON.Condition && condition !== null) {
  49012. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  49013. if (action)
  49014. action.then(nothing);
  49015. else
  49016. actionManager.registerAction(nothing);
  49017. action = nothing;
  49018. }
  49019. if (combineArray === null) {
  49020. if (newAction instanceof BABYLON.Condition) {
  49021. condition = newAction;
  49022. newAction = action;
  49023. }
  49024. else {
  49025. condition = null;
  49026. if (action)
  49027. action.then(newAction);
  49028. else
  49029. actionManager.registerAction(newAction);
  49030. }
  49031. }
  49032. else {
  49033. combineArray.push(newAction);
  49034. }
  49035. for (var i = 0; i < parsedAction.children.length; i++)
  49036. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  49037. };
  49038. // triggers
  49039. for (var i = 0; i < parsedActions.children.length; i++) {
  49040. var triggerParams;
  49041. var trigger = parsedActions.children[i];
  49042. if (trigger.properties.length > 0) {
  49043. var param = trigger.properties[0].value;
  49044. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  49045. if (value._meshId) {
  49046. value.mesh = scene.getMeshByID(value._meshId);
  49047. }
  49048. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  49049. }
  49050. else
  49051. triggerParams = ActionManager[trigger.name];
  49052. for (var j = 0; j < trigger.children.length; j++) {
  49053. if (!trigger.detached)
  49054. traverse(trigger.children[j], triggerParams, null, null);
  49055. }
  49056. }
  49057. };
  49058. ActionManager.GetTriggerName = function (trigger) {
  49059. switch (trigger) {
  49060. case 0: return "NothingTrigger";
  49061. case 1: return "OnPickTrigger";
  49062. case 2: return "OnLeftPickTrigger";
  49063. case 3: return "OnRightPickTrigger";
  49064. case 4: return "OnCenterPickTrigger";
  49065. case 5: return "OnPickDownTrigger";
  49066. case 6: return "OnPickUpTrigger";
  49067. case 7: return "OnLongPressTrigger";
  49068. case 8: return "OnPointerOverTrigger";
  49069. case 9: return "OnPointerOutTrigger";
  49070. case 10: return "OnEveryFrameTrigger";
  49071. case 11: return "OnIntersectionEnterTrigger";
  49072. case 12: return "OnIntersectionExitTrigger";
  49073. case 13: return "OnKeyDownTrigger";
  49074. case 14: return "OnKeyUpTrigger";
  49075. case 15: return "OnPickOutTrigger";
  49076. default: return "";
  49077. }
  49078. };
  49079. // Statics
  49080. ActionManager._NothingTrigger = 0;
  49081. ActionManager._OnPickTrigger = 1;
  49082. ActionManager._OnLeftPickTrigger = 2;
  49083. ActionManager._OnRightPickTrigger = 3;
  49084. ActionManager._OnCenterPickTrigger = 4;
  49085. ActionManager._OnPickDownTrigger = 5;
  49086. ActionManager._OnDoublePickTrigger = 6;
  49087. ActionManager._OnPickUpTrigger = 7;
  49088. ActionManager._OnLongPressTrigger = 8;
  49089. ActionManager._OnPointerOverTrigger = 9;
  49090. ActionManager._OnPointerOutTrigger = 10;
  49091. ActionManager._OnEveryFrameTrigger = 11;
  49092. ActionManager._OnIntersectionEnterTrigger = 12;
  49093. ActionManager._OnIntersectionExitTrigger = 13;
  49094. ActionManager._OnKeyDownTrigger = 14;
  49095. ActionManager._OnKeyUpTrigger = 15;
  49096. ActionManager._OnPickOutTrigger = 16;
  49097. ActionManager.Triggers = {};
  49098. return ActionManager;
  49099. }());
  49100. BABYLON.ActionManager = ActionManager;
  49101. })(BABYLON || (BABYLON = {}));
  49102. //# sourceMappingURL=babylon.actionManager.js.map
  49103. var BABYLON;
  49104. (function (BABYLON) {
  49105. var InterpolateValueAction = /** @class */ (function (_super) {
  49106. __extends(InterpolateValueAction, _super);
  49107. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  49108. if (duration === void 0) { duration = 1000; }
  49109. var _this = _super.call(this, triggerOptions, condition) || this;
  49110. _this.propertyPath = propertyPath;
  49111. _this.value = value;
  49112. _this.duration = duration;
  49113. _this.stopOtherAnimations = stopOtherAnimations;
  49114. _this.onInterpolationDone = onInterpolationDone;
  49115. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  49116. _this._target = _this._effectiveTarget = target;
  49117. return _this;
  49118. }
  49119. InterpolateValueAction.prototype._prepare = function () {
  49120. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49121. this._property = this._getProperty(this.propertyPath);
  49122. };
  49123. InterpolateValueAction.prototype.execute = function () {
  49124. var _this = this;
  49125. var scene = this._actionManager.getScene();
  49126. var keys = [
  49127. {
  49128. frame: 0,
  49129. value: this._effectiveTarget[this._property]
  49130. }, {
  49131. frame: 100,
  49132. value: this.value
  49133. }
  49134. ];
  49135. var dataType;
  49136. if (typeof this.value === "number") {
  49137. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  49138. }
  49139. else if (this.value instanceof BABYLON.Color3) {
  49140. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  49141. }
  49142. else if (this.value instanceof BABYLON.Vector3) {
  49143. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  49144. }
  49145. else if (this.value instanceof BABYLON.Matrix) {
  49146. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  49147. }
  49148. else if (this.value instanceof BABYLON.Quaternion) {
  49149. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  49150. }
  49151. else {
  49152. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  49153. return;
  49154. }
  49155. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  49156. animation.setKeys(keys);
  49157. if (this.stopOtherAnimations) {
  49158. scene.stopAnimation(this._effectiveTarget);
  49159. }
  49160. var wrapper = function () {
  49161. _this.onInterpolationDoneObservable.notifyObservers(_this);
  49162. if (_this.onInterpolationDone) {
  49163. _this.onInterpolationDone();
  49164. }
  49165. };
  49166. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  49167. };
  49168. InterpolateValueAction.prototype.serialize = function (parent) {
  49169. return _super.prototype._serialize.call(this, {
  49170. name: "InterpolateValueAction",
  49171. properties: [
  49172. BABYLON.Action._GetTargetProperty(this._target),
  49173. { name: "propertyPath", value: this.propertyPath },
  49174. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49175. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49176. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49177. ]
  49178. }, parent);
  49179. };
  49180. return InterpolateValueAction;
  49181. }(BABYLON.Action));
  49182. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49183. })(BABYLON || (BABYLON = {}));
  49184. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49185. var BABYLON;
  49186. (function (BABYLON) {
  49187. var SwitchBooleanAction = /** @class */ (function (_super) {
  49188. __extends(SwitchBooleanAction, _super);
  49189. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49190. var _this = _super.call(this, triggerOptions, condition) || this;
  49191. _this.propertyPath = propertyPath;
  49192. _this._target = _this._effectiveTarget = target;
  49193. return _this;
  49194. }
  49195. SwitchBooleanAction.prototype._prepare = function () {
  49196. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49197. this._property = this._getProperty(this.propertyPath);
  49198. };
  49199. SwitchBooleanAction.prototype.execute = function () {
  49200. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49201. };
  49202. SwitchBooleanAction.prototype.serialize = function (parent) {
  49203. return _super.prototype._serialize.call(this, {
  49204. name: "SwitchBooleanAction",
  49205. properties: [
  49206. BABYLON.Action._GetTargetProperty(this._target),
  49207. { name: "propertyPath", value: this.propertyPath }
  49208. ]
  49209. }, parent);
  49210. };
  49211. return SwitchBooleanAction;
  49212. }(BABYLON.Action));
  49213. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49214. var SetStateAction = /** @class */ (function (_super) {
  49215. __extends(SetStateAction, _super);
  49216. function SetStateAction(triggerOptions, target, value, condition) {
  49217. var _this = _super.call(this, triggerOptions, condition) || this;
  49218. _this.value = value;
  49219. _this._target = target;
  49220. return _this;
  49221. }
  49222. SetStateAction.prototype.execute = function () {
  49223. this._target.state = this.value;
  49224. };
  49225. SetStateAction.prototype.serialize = function (parent) {
  49226. return _super.prototype._serialize.call(this, {
  49227. name: "SetStateAction",
  49228. properties: [
  49229. BABYLON.Action._GetTargetProperty(this._target),
  49230. { name: "value", value: this.value }
  49231. ]
  49232. }, parent);
  49233. };
  49234. return SetStateAction;
  49235. }(BABYLON.Action));
  49236. BABYLON.SetStateAction = SetStateAction;
  49237. var SetValueAction = /** @class */ (function (_super) {
  49238. __extends(SetValueAction, _super);
  49239. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49240. var _this = _super.call(this, triggerOptions, condition) || this;
  49241. _this.propertyPath = propertyPath;
  49242. _this.value = value;
  49243. _this._target = _this._effectiveTarget = target;
  49244. return _this;
  49245. }
  49246. SetValueAction.prototype._prepare = function () {
  49247. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49248. this._property = this._getProperty(this.propertyPath);
  49249. };
  49250. SetValueAction.prototype.execute = function () {
  49251. this._effectiveTarget[this._property] = this.value;
  49252. if (this._target.markAsDirty) {
  49253. this._target.markAsDirty(this._property);
  49254. }
  49255. };
  49256. SetValueAction.prototype.serialize = function (parent) {
  49257. return _super.prototype._serialize.call(this, {
  49258. name: "SetValueAction",
  49259. properties: [
  49260. BABYLON.Action._GetTargetProperty(this._target),
  49261. { name: "propertyPath", value: this.propertyPath },
  49262. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49263. ]
  49264. }, parent);
  49265. };
  49266. return SetValueAction;
  49267. }(BABYLON.Action));
  49268. BABYLON.SetValueAction = SetValueAction;
  49269. var IncrementValueAction = /** @class */ (function (_super) {
  49270. __extends(IncrementValueAction, _super);
  49271. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49272. var _this = _super.call(this, triggerOptions, condition) || this;
  49273. _this.propertyPath = propertyPath;
  49274. _this.value = value;
  49275. _this._target = _this._effectiveTarget = target;
  49276. return _this;
  49277. }
  49278. IncrementValueAction.prototype._prepare = function () {
  49279. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49280. this._property = this._getProperty(this.propertyPath);
  49281. if (typeof this._effectiveTarget[this._property] !== "number") {
  49282. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49283. }
  49284. };
  49285. IncrementValueAction.prototype.execute = function () {
  49286. this._effectiveTarget[this._property] += this.value;
  49287. if (this._target.markAsDirty) {
  49288. this._target.markAsDirty(this._property);
  49289. }
  49290. };
  49291. IncrementValueAction.prototype.serialize = function (parent) {
  49292. return _super.prototype._serialize.call(this, {
  49293. name: "IncrementValueAction",
  49294. properties: [
  49295. BABYLON.Action._GetTargetProperty(this._target),
  49296. { name: "propertyPath", value: this.propertyPath },
  49297. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49298. ]
  49299. }, parent);
  49300. };
  49301. return IncrementValueAction;
  49302. }(BABYLON.Action));
  49303. BABYLON.IncrementValueAction = IncrementValueAction;
  49304. var PlayAnimationAction = /** @class */ (function (_super) {
  49305. __extends(PlayAnimationAction, _super);
  49306. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49307. var _this = _super.call(this, triggerOptions, condition) || this;
  49308. _this.from = from;
  49309. _this.to = to;
  49310. _this.loop = loop;
  49311. _this._target = target;
  49312. return _this;
  49313. }
  49314. PlayAnimationAction.prototype._prepare = function () {
  49315. };
  49316. PlayAnimationAction.prototype.execute = function () {
  49317. var scene = this._actionManager.getScene();
  49318. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49319. };
  49320. PlayAnimationAction.prototype.serialize = function (parent) {
  49321. return _super.prototype._serialize.call(this, {
  49322. name: "PlayAnimationAction",
  49323. properties: [
  49324. BABYLON.Action._GetTargetProperty(this._target),
  49325. { name: "from", value: String(this.from) },
  49326. { name: "to", value: String(this.to) },
  49327. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49328. ]
  49329. }, parent);
  49330. };
  49331. return PlayAnimationAction;
  49332. }(BABYLON.Action));
  49333. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49334. var StopAnimationAction = /** @class */ (function (_super) {
  49335. __extends(StopAnimationAction, _super);
  49336. function StopAnimationAction(triggerOptions, target, condition) {
  49337. var _this = _super.call(this, triggerOptions, condition) || this;
  49338. _this._target = target;
  49339. return _this;
  49340. }
  49341. StopAnimationAction.prototype._prepare = function () {
  49342. };
  49343. StopAnimationAction.prototype.execute = function () {
  49344. var scene = this._actionManager.getScene();
  49345. scene.stopAnimation(this._target);
  49346. };
  49347. StopAnimationAction.prototype.serialize = function (parent) {
  49348. return _super.prototype._serialize.call(this, {
  49349. name: "StopAnimationAction",
  49350. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49351. }, parent);
  49352. };
  49353. return StopAnimationAction;
  49354. }(BABYLON.Action));
  49355. BABYLON.StopAnimationAction = StopAnimationAction;
  49356. var DoNothingAction = /** @class */ (function (_super) {
  49357. __extends(DoNothingAction, _super);
  49358. function DoNothingAction(triggerOptions, condition) {
  49359. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49360. return _super.call(this, triggerOptions, condition) || this;
  49361. }
  49362. DoNothingAction.prototype.execute = function () {
  49363. };
  49364. DoNothingAction.prototype.serialize = function (parent) {
  49365. return _super.prototype._serialize.call(this, {
  49366. name: "DoNothingAction",
  49367. properties: []
  49368. }, parent);
  49369. };
  49370. return DoNothingAction;
  49371. }(BABYLON.Action));
  49372. BABYLON.DoNothingAction = DoNothingAction;
  49373. var CombineAction = /** @class */ (function (_super) {
  49374. __extends(CombineAction, _super);
  49375. function CombineAction(triggerOptions, children, condition) {
  49376. var _this = _super.call(this, triggerOptions, condition) || this;
  49377. _this.children = children;
  49378. return _this;
  49379. }
  49380. CombineAction.prototype._prepare = function () {
  49381. for (var index = 0; index < this.children.length; index++) {
  49382. this.children[index]._actionManager = this._actionManager;
  49383. this.children[index]._prepare();
  49384. }
  49385. };
  49386. CombineAction.prototype.execute = function (evt) {
  49387. for (var index = 0; index < this.children.length; index++) {
  49388. this.children[index].execute(evt);
  49389. }
  49390. };
  49391. CombineAction.prototype.serialize = function (parent) {
  49392. var serializationObject = _super.prototype._serialize.call(this, {
  49393. name: "CombineAction",
  49394. properties: [],
  49395. combine: []
  49396. }, parent);
  49397. for (var i = 0; i < this.children.length; i++) {
  49398. serializationObject.combine.push(this.children[i].serialize(null));
  49399. }
  49400. return serializationObject;
  49401. };
  49402. return CombineAction;
  49403. }(BABYLON.Action));
  49404. BABYLON.CombineAction = CombineAction;
  49405. var ExecuteCodeAction = /** @class */ (function (_super) {
  49406. __extends(ExecuteCodeAction, _super);
  49407. function ExecuteCodeAction(triggerOptions, func, condition) {
  49408. var _this = _super.call(this, triggerOptions, condition) || this;
  49409. _this.func = func;
  49410. return _this;
  49411. }
  49412. ExecuteCodeAction.prototype.execute = function (evt) {
  49413. this.func(evt);
  49414. };
  49415. return ExecuteCodeAction;
  49416. }(BABYLON.Action));
  49417. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  49418. var SetParentAction = /** @class */ (function (_super) {
  49419. __extends(SetParentAction, _super);
  49420. function SetParentAction(triggerOptions, target, parent, condition) {
  49421. var _this = _super.call(this, triggerOptions, condition) || this;
  49422. _this._target = target;
  49423. _this._parent = parent;
  49424. return _this;
  49425. }
  49426. SetParentAction.prototype._prepare = function () {
  49427. };
  49428. SetParentAction.prototype.execute = function () {
  49429. if (this._target.parent === this._parent) {
  49430. return;
  49431. }
  49432. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49433. invertParentWorldMatrix.invert();
  49434. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49435. this._target.parent = this._parent;
  49436. };
  49437. SetParentAction.prototype.serialize = function (parent) {
  49438. return _super.prototype._serialize.call(this, {
  49439. name: "SetParentAction",
  49440. properties: [
  49441. BABYLON.Action._GetTargetProperty(this._target),
  49442. BABYLON.Action._GetTargetProperty(this._parent),
  49443. ]
  49444. }, parent);
  49445. };
  49446. return SetParentAction;
  49447. }(BABYLON.Action));
  49448. BABYLON.SetParentAction = SetParentAction;
  49449. var PlaySoundAction = /** @class */ (function (_super) {
  49450. __extends(PlaySoundAction, _super);
  49451. function PlaySoundAction(triggerOptions, sound, condition) {
  49452. var _this = _super.call(this, triggerOptions, condition) || this;
  49453. _this._sound = sound;
  49454. return _this;
  49455. }
  49456. PlaySoundAction.prototype._prepare = function () {
  49457. };
  49458. PlaySoundAction.prototype.execute = function () {
  49459. if (this._sound !== undefined)
  49460. this._sound.play();
  49461. };
  49462. PlaySoundAction.prototype.serialize = function (parent) {
  49463. return _super.prototype._serialize.call(this, {
  49464. name: "PlaySoundAction",
  49465. properties: [{ name: "sound", value: this._sound.name }]
  49466. }, parent);
  49467. };
  49468. return PlaySoundAction;
  49469. }(BABYLON.Action));
  49470. BABYLON.PlaySoundAction = PlaySoundAction;
  49471. var StopSoundAction = /** @class */ (function (_super) {
  49472. __extends(StopSoundAction, _super);
  49473. function StopSoundAction(triggerOptions, sound, condition) {
  49474. var _this = _super.call(this, triggerOptions, condition) || this;
  49475. _this._sound = sound;
  49476. return _this;
  49477. }
  49478. StopSoundAction.prototype._prepare = function () {
  49479. };
  49480. StopSoundAction.prototype.execute = function () {
  49481. if (this._sound !== undefined)
  49482. this._sound.stop();
  49483. };
  49484. StopSoundAction.prototype.serialize = function (parent) {
  49485. return _super.prototype._serialize.call(this, {
  49486. name: "StopSoundAction",
  49487. properties: [{ name: "sound", value: this._sound.name }]
  49488. }, parent);
  49489. };
  49490. return StopSoundAction;
  49491. }(BABYLON.Action));
  49492. BABYLON.StopSoundAction = StopSoundAction;
  49493. })(BABYLON || (BABYLON = {}));
  49494. //# sourceMappingURL=babylon.directActions.js.map
  49495. var BABYLON;
  49496. (function (BABYLON) {
  49497. var SpriteManager = /** @class */ (function () {
  49498. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49499. if (epsilon === void 0) { epsilon = 0.01; }
  49500. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49501. this.name = name;
  49502. this.sprites = new Array();
  49503. this.renderingGroupId = 0;
  49504. this.layerMask = 0x0FFFFFFF;
  49505. this.fogEnabled = true;
  49506. this.isPickable = false;
  49507. /**
  49508. * An event triggered when the manager is disposed.
  49509. * @type {BABYLON.Observable}
  49510. */
  49511. this.onDisposeObservable = new BABYLON.Observable();
  49512. this._vertexBuffers = {};
  49513. this._capacity = capacity;
  49514. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49515. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49516. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49517. if (cellSize.width && cellSize.height) {
  49518. this.cellWidth = cellSize.width;
  49519. this.cellHeight = cellSize.height;
  49520. }
  49521. else if (cellSize !== undefined) {
  49522. this.cellWidth = cellSize;
  49523. this.cellHeight = cellSize;
  49524. }
  49525. else {
  49526. return;
  49527. }
  49528. this._epsilon = epsilon;
  49529. this._scene = scene;
  49530. this._scene.spriteManagers.push(this);
  49531. var indices = [];
  49532. var index = 0;
  49533. for (var count = 0; count < capacity; count++) {
  49534. indices.push(index);
  49535. indices.push(index + 1);
  49536. indices.push(index + 2);
  49537. indices.push(index);
  49538. indices.push(index + 2);
  49539. indices.push(index + 3);
  49540. index += 4;
  49541. }
  49542. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49543. // VBO
  49544. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49545. this._vertexData = new Float32Array(capacity * 16 * 4);
  49546. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49547. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49548. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49549. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  49550. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  49551. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49552. this._vertexBuffers["options"] = options;
  49553. this._vertexBuffers["cellInfo"] = cellInfo;
  49554. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49555. // Effects
  49556. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  49557. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  49558. }
  49559. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  49560. set: function (callback) {
  49561. if (this._onDisposeObserver) {
  49562. this.onDisposeObservable.remove(this._onDisposeObserver);
  49563. }
  49564. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49565. },
  49566. enumerable: true,
  49567. configurable: true
  49568. });
  49569. Object.defineProperty(SpriteManager.prototype, "texture", {
  49570. get: function () {
  49571. return this._spriteTexture;
  49572. },
  49573. set: function (value) {
  49574. this._spriteTexture = value;
  49575. },
  49576. enumerable: true,
  49577. configurable: true
  49578. });
  49579. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  49580. var arrayOffset = index * 16;
  49581. if (offsetX === 0)
  49582. offsetX = this._epsilon;
  49583. else if (offsetX === 1)
  49584. offsetX = 1 - this._epsilon;
  49585. if (offsetY === 0)
  49586. offsetY = this._epsilon;
  49587. else if (offsetY === 1)
  49588. offsetY = 1 - this._epsilon;
  49589. this._vertexData[arrayOffset] = sprite.position.x;
  49590. this._vertexData[arrayOffset + 1] = sprite.position.y;
  49591. this._vertexData[arrayOffset + 2] = sprite.position.z;
  49592. this._vertexData[arrayOffset + 3] = sprite.angle;
  49593. this._vertexData[arrayOffset + 4] = sprite.width;
  49594. this._vertexData[arrayOffset + 5] = sprite.height;
  49595. this._vertexData[arrayOffset + 6] = offsetX;
  49596. this._vertexData[arrayOffset + 7] = offsetY;
  49597. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  49598. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  49599. var offset = (sprite.cellIndex / rowSize) >> 0;
  49600. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  49601. this._vertexData[arrayOffset + 11] = offset;
  49602. // Color
  49603. this._vertexData[arrayOffset + 12] = sprite.color.r;
  49604. this._vertexData[arrayOffset + 13] = sprite.color.g;
  49605. this._vertexData[arrayOffset + 14] = sprite.color.b;
  49606. this._vertexData[arrayOffset + 15] = sprite.color.a;
  49607. };
  49608. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  49609. var count = Math.min(this._capacity, this.sprites.length);
  49610. var min = BABYLON.Vector3.Zero();
  49611. var max = BABYLON.Vector3.Zero();
  49612. var distance = Number.MAX_VALUE;
  49613. var currentSprite = null;
  49614. var cameraSpacePosition = BABYLON.Vector3.Zero();
  49615. var cameraView = camera.getViewMatrix();
  49616. for (var index = 0; index < count; index++) {
  49617. var sprite = this.sprites[index];
  49618. if (!sprite) {
  49619. continue;
  49620. }
  49621. if (predicate) {
  49622. if (!predicate(sprite)) {
  49623. continue;
  49624. }
  49625. }
  49626. else if (!sprite.isPickable) {
  49627. continue;
  49628. }
  49629. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  49630. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  49631. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  49632. if (ray.intersectsBoxMinMax(min, max)) {
  49633. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  49634. if (distance > currentDistance) {
  49635. distance = currentDistance;
  49636. currentSprite = sprite;
  49637. if (fastCheck) {
  49638. break;
  49639. }
  49640. }
  49641. }
  49642. }
  49643. if (currentSprite) {
  49644. var result = new BABYLON.PickingInfo();
  49645. result.hit = true;
  49646. result.pickedSprite = currentSprite;
  49647. result.distance = distance;
  49648. return result;
  49649. }
  49650. return null;
  49651. };
  49652. SpriteManager.prototype.render = function () {
  49653. // Check
  49654. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  49655. return;
  49656. var engine = this._scene.getEngine();
  49657. var baseSize = this._spriteTexture.getBaseSize();
  49658. // Sprites
  49659. var deltaTime = engine.getDeltaTime();
  49660. var max = Math.min(this._capacity, this.sprites.length);
  49661. var rowSize = baseSize.width / this.cellWidth;
  49662. var offset = 0;
  49663. for (var index = 0; index < max; index++) {
  49664. var sprite = this.sprites[index];
  49665. if (!sprite) {
  49666. continue;
  49667. }
  49668. sprite._animate(deltaTime);
  49669. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  49670. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  49671. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  49672. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  49673. }
  49674. this._buffer.update(this._vertexData);
  49675. // Render
  49676. var effect = this._effectBase;
  49677. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49678. effect = this._effectFog;
  49679. }
  49680. engine.enableEffect(effect);
  49681. var viewMatrix = this._scene.getViewMatrix();
  49682. effect.setTexture("diffuseSampler", this._spriteTexture);
  49683. effect.setMatrix("view", viewMatrix);
  49684. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  49685. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  49686. // Fog
  49687. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49688. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  49689. effect.setColor3("vFogColor", this._scene.fogColor);
  49690. }
  49691. // VBOs
  49692. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  49693. // Draw order
  49694. engine.setDepthFunctionToLessOrEqual();
  49695. effect.setBool("alphaTest", true);
  49696. engine.setColorWrite(false);
  49697. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49698. engine.setColorWrite(true);
  49699. effect.setBool("alphaTest", false);
  49700. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  49701. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49702. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49703. };
  49704. SpriteManager.prototype.dispose = function () {
  49705. if (this._buffer) {
  49706. this._buffer.dispose();
  49707. this._buffer = null;
  49708. }
  49709. if (this._indexBuffer) {
  49710. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49711. this._indexBuffer = null;
  49712. }
  49713. if (this._spriteTexture) {
  49714. this._spriteTexture.dispose();
  49715. this._spriteTexture = null;
  49716. }
  49717. // Remove from scene
  49718. var index = this._scene.spriteManagers.indexOf(this);
  49719. this._scene.spriteManagers.splice(index, 1);
  49720. // Callback
  49721. this.onDisposeObservable.notifyObservers(this);
  49722. this.onDisposeObservable.clear();
  49723. };
  49724. return SpriteManager;
  49725. }());
  49726. BABYLON.SpriteManager = SpriteManager;
  49727. })(BABYLON || (BABYLON = {}));
  49728. //# sourceMappingURL=babylon.spriteManager.js.map
  49729. var BABYLON;
  49730. (function (BABYLON) {
  49731. var Sprite = /** @class */ (function () {
  49732. function Sprite(name, manager) {
  49733. this.name = name;
  49734. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49735. this.width = 1.0;
  49736. this.height = 1.0;
  49737. this.angle = 0;
  49738. this.cellIndex = 0;
  49739. this.invertU = 0;
  49740. this.invertV = 0;
  49741. this.animations = new Array();
  49742. this.isPickable = false;
  49743. this._animationStarted = false;
  49744. this._loopAnimation = false;
  49745. this._fromIndex = 0;
  49746. this._toIndex = 0;
  49747. this._delay = 0;
  49748. this._direction = 1;
  49749. this._time = 0;
  49750. this._manager = manager;
  49751. this._manager.sprites.push(this);
  49752. this.position = BABYLON.Vector3.Zero();
  49753. }
  49754. Object.defineProperty(Sprite.prototype, "size", {
  49755. get: function () {
  49756. return this.width;
  49757. },
  49758. set: function (value) {
  49759. this.width = value;
  49760. this.height = value;
  49761. },
  49762. enumerable: true,
  49763. configurable: true
  49764. });
  49765. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  49766. this._fromIndex = from;
  49767. this._toIndex = to;
  49768. this._loopAnimation = loop;
  49769. this._delay = delay;
  49770. this._animationStarted = true;
  49771. this._direction = from < to ? 1 : -1;
  49772. this.cellIndex = from;
  49773. this._time = 0;
  49774. this._onAnimationEnd = onAnimationEnd;
  49775. };
  49776. Sprite.prototype.stopAnimation = function () {
  49777. this._animationStarted = false;
  49778. };
  49779. Sprite.prototype._animate = function (deltaTime) {
  49780. if (!this._animationStarted)
  49781. return;
  49782. this._time += deltaTime;
  49783. if (this._time > this._delay) {
  49784. this._time = this._time % this._delay;
  49785. this.cellIndex += this._direction;
  49786. if (this.cellIndex > this._toIndex) {
  49787. if (this._loopAnimation) {
  49788. this.cellIndex = this._fromIndex;
  49789. }
  49790. else {
  49791. this.cellIndex = this._toIndex;
  49792. this._animationStarted = false;
  49793. if (this._onAnimationEnd) {
  49794. this._onAnimationEnd();
  49795. }
  49796. if (this.disposeWhenFinishedAnimating) {
  49797. this.dispose();
  49798. }
  49799. }
  49800. }
  49801. }
  49802. };
  49803. Sprite.prototype.dispose = function () {
  49804. for (var i = 0; i < this._manager.sprites.length; i++) {
  49805. if (this._manager.sprites[i] == this) {
  49806. this._manager.sprites.splice(i, 1);
  49807. }
  49808. }
  49809. };
  49810. return Sprite;
  49811. }());
  49812. BABYLON.Sprite = Sprite;
  49813. })(BABYLON || (BABYLON = {}));
  49814. //# sourceMappingURL=babylon.sprite.js.map
  49815. var BABYLON;
  49816. (function (BABYLON) {
  49817. var IntersectionInfo = /** @class */ (function () {
  49818. function IntersectionInfo(bu, bv, distance) {
  49819. this.bu = bu;
  49820. this.bv = bv;
  49821. this.distance = distance;
  49822. this.faceId = 0;
  49823. this.subMeshId = 0;
  49824. }
  49825. return IntersectionInfo;
  49826. }());
  49827. BABYLON.IntersectionInfo = IntersectionInfo;
  49828. var PickingInfo = /** @class */ (function () {
  49829. function PickingInfo() {
  49830. this.hit = false;
  49831. this.distance = 0;
  49832. this.pickedPoint = null;
  49833. this.pickedMesh = null;
  49834. this.bu = 0;
  49835. this.bv = 0;
  49836. this.faceId = -1;
  49837. this.subMeshId = 0;
  49838. this.pickedSprite = null;
  49839. }
  49840. // Methods
  49841. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49842. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49843. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49844. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49845. return null;
  49846. }
  49847. var indices = this.pickedMesh.getIndices();
  49848. if (!indices) {
  49849. return null;
  49850. }
  49851. var result;
  49852. if (useVerticesNormals) {
  49853. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49854. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49855. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49856. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49857. normal0 = normal0.scale(this.bu);
  49858. normal1 = normal1.scale(this.bv);
  49859. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49860. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49861. }
  49862. else {
  49863. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49864. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49865. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49866. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49867. var p1p2 = vertex1.subtract(vertex2);
  49868. var p3p2 = vertex3.subtract(vertex2);
  49869. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49870. }
  49871. if (useWorldCoordinates) {
  49872. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49873. }
  49874. return BABYLON.Vector3.Normalize(result);
  49875. };
  49876. PickingInfo.prototype.getTextureCoordinates = function () {
  49877. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49878. return null;
  49879. }
  49880. var indices = this.pickedMesh.getIndices();
  49881. if (!indices) {
  49882. return null;
  49883. }
  49884. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49885. if (!uvs) {
  49886. return null;
  49887. }
  49888. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49889. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49890. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49891. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49892. uv1 = uv1.scale(this.bu);
  49893. uv2 = uv2.scale(this.bv);
  49894. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49895. };
  49896. return PickingInfo;
  49897. }());
  49898. BABYLON.PickingInfo = PickingInfo;
  49899. })(BABYLON || (BABYLON = {}));
  49900. //# sourceMappingURL=babylon.pickingInfo.js.map
  49901. var BABYLON;
  49902. (function (BABYLON) {
  49903. var Ray = /** @class */ (function () {
  49904. function Ray(origin, direction, length) {
  49905. if (length === void 0) { length = Number.MAX_VALUE; }
  49906. this.origin = origin;
  49907. this.direction = direction;
  49908. this.length = length;
  49909. }
  49910. // Methods
  49911. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49912. var d = 0.0;
  49913. var maxValue = Number.MAX_VALUE;
  49914. var inv;
  49915. var min;
  49916. var max;
  49917. var temp;
  49918. if (Math.abs(this.direction.x) < 0.0000001) {
  49919. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49920. return false;
  49921. }
  49922. }
  49923. else {
  49924. inv = 1.0 / this.direction.x;
  49925. min = (minimum.x - this.origin.x) * inv;
  49926. max = (maximum.x - this.origin.x) * inv;
  49927. if (max === -Infinity) {
  49928. max = Infinity;
  49929. }
  49930. if (min > max) {
  49931. temp = min;
  49932. min = max;
  49933. max = temp;
  49934. }
  49935. d = Math.max(min, d);
  49936. maxValue = Math.min(max, maxValue);
  49937. if (d > maxValue) {
  49938. return false;
  49939. }
  49940. }
  49941. if (Math.abs(this.direction.y) < 0.0000001) {
  49942. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49943. return false;
  49944. }
  49945. }
  49946. else {
  49947. inv = 1.0 / this.direction.y;
  49948. min = (minimum.y - this.origin.y) * inv;
  49949. max = (maximum.y - this.origin.y) * inv;
  49950. if (max === -Infinity) {
  49951. max = Infinity;
  49952. }
  49953. if (min > max) {
  49954. temp = min;
  49955. min = max;
  49956. max = temp;
  49957. }
  49958. d = Math.max(min, d);
  49959. maxValue = Math.min(max, maxValue);
  49960. if (d > maxValue) {
  49961. return false;
  49962. }
  49963. }
  49964. if (Math.abs(this.direction.z) < 0.0000001) {
  49965. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49966. return false;
  49967. }
  49968. }
  49969. else {
  49970. inv = 1.0 / this.direction.z;
  49971. min = (minimum.z - this.origin.z) * inv;
  49972. max = (maximum.z - this.origin.z) * inv;
  49973. if (max === -Infinity) {
  49974. max = Infinity;
  49975. }
  49976. if (min > max) {
  49977. temp = min;
  49978. min = max;
  49979. max = temp;
  49980. }
  49981. d = Math.max(min, d);
  49982. maxValue = Math.min(max, maxValue);
  49983. if (d > maxValue) {
  49984. return false;
  49985. }
  49986. }
  49987. return true;
  49988. };
  49989. Ray.prototype.intersectsBox = function (box) {
  49990. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49991. };
  49992. Ray.prototype.intersectsSphere = function (sphere) {
  49993. var x = sphere.center.x - this.origin.x;
  49994. var y = sphere.center.y - this.origin.y;
  49995. var z = sphere.center.z - this.origin.z;
  49996. var pyth = (x * x) + (y * y) + (z * z);
  49997. var rr = sphere.radius * sphere.radius;
  49998. if (pyth <= rr) {
  49999. return true;
  50000. }
  50001. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  50002. if (dot < 0.0) {
  50003. return false;
  50004. }
  50005. var temp = pyth - (dot * dot);
  50006. return temp <= rr;
  50007. };
  50008. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  50009. if (!this._edge1) {
  50010. this._edge1 = BABYLON.Vector3.Zero();
  50011. this._edge2 = BABYLON.Vector3.Zero();
  50012. this._pvec = BABYLON.Vector3.Zero();
  50013. this._tvec = BABYLON.Vector3.Zero();
  50014. this._qvec = BABYLON.Vector3.Zero();
  50015. }
  50016. vertex1.subtractToRef(vertex0, this._edge1);
  50017. vertex2.subtractToRef(vertex0, this._edge2);
  50018. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  50019. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  50020. if (det === 0) {
  50021. return null;
  50022. }
  50023. var invdet = 1 / det;
  50024. this.origin.subtractToRef(vertex0, this._tvec);
  50025. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  50026. if (bu < 0 || bu > 1.0) {
  50027. return null;
  50028. }
  50029. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  50030. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  50031. if (bv < 0 || bu + bv > 1.0) {
  50032. return null;
  50033. }
  50034. //check if the distance is longer than the predefined length.
  50035. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  50036. if (distance > this.length) {
  50037. return null;
  50038. }
  50039. return new BABYLON.IntersectionInfo(bu, bv, distance);
  50040. };
  50041. Ray.prototype.intersectsPlane = function (plane) {
  50042. var distance;
  50043. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  50044. if (Math.abs(result1) < 9.99999997475243E-07) {
  50045. return null;
  50046. }
  50047. else {
  50048. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  50049. distance = (-plane.d - result2) / result1;
  50050. if (distance < 0.0) {
  50051. if (distance < -9.99999997475243E-07) {
  50052. return null;
  50053. }
  50054. else {
  50055. return 0;
  50056. }
  50057. }
  50058. return distance;
  50059. }
  50060. };
  50061. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  50062. var tm = BABYLON.Tmp.Matrix[0];
  50063. mesh.getWorldMatrix().invertToRef(tm);
  50064. if (this._tmpRay) {
  50065. Ray.TransformToRef(this, tm, this._tmpRay);
  50066. }
  50067. else {
  50068. this._tmpRay = Ray.Transform(this, tm);
  50069. }
  50070. return mesh.intersects(this._tmpRay, fastCheck);
  50071. };
  50072. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  50073. if (results) {
  50074. results.length = 0;
  50075. }
  50076. else {
  50077. results = [];
  50078. }
  50079. for (var i = 0; i < meshes.length; i++) {
  50080. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  50081. if (pickInfo.hit) {
  50082. results.push(pickInfo);
  50083. }
  50084. }
  50085. results.sort(this._comparePickingInfo);
  50086. return results;
  50087. };
  50088. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  50089. if (pickingInfoA.distance < pickingInfoB.distance) {
  50090. return -1;
  50091. }
  50092. else if (pickingInfoA.distance > pickingInfoB.distance) {
  50093. return 1;
  50094. }
  50095. else {
  50096. return 0;
  50097. }
  50098. };
  50099. /**
  50100. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  50101. * @param sega the first point of the segment to test the intersection against
  50102. * @param segb the second point of the segment to test the intersection against
  50103. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  50104. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  50105. */
  50106. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  50107. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  50108. var u = segb.subtract(sega);
  50109. var v = rsegb.subtract(this.origin);
  50110. var w = sega.subtract(this.origin);
  50111. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  50112. var b = BABYLON.Vector3.Dot(u, v);
  50113. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  50114. var d = BABYLON.Vector3.Dot(u, w);
  50115. var e = BABYLON.Vector3.Dot(v, w);
  50116. var D = a * c - b * b; // always >= 0
  50117. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  50118. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  50119. // compute the line parameters of the two closest points
  50120. if (D < Ray.smallnum) {
  50121. sN = 0.0; // force using point P0 on segment S1
  50122. sD = 1.0; // to prevent possible division by 0.0 later
  50123. tN = e;
  50124. tD = c;
  50125. }
  50126. else {
  50127. sN = (b * e - c * d);
  50128. tN = (a * e - b * d);
  50129. if (sN < 0.0) {
  50130. sN = 0.0;
  50131. tN = e;
  50132. tD = c;
  50133. }
  50134. else if (sN > sD) {
  50135. sN = sD;
  50136. tN = e + b;
  50137. tD = c;
  50138. }
  50139. }
  50140. if (tN < 0.0) {
  50141. tN = 0.0;
  50142. // recompute sc for this edge
  50143. if (-d < 0.0) {
  50144. sN = 0.0;
  50145. }
  50146. else if (-d > a)
  50147. sN = sD;
  50148. else {
  50149. sN = -d;
  50150. sD = a;
  50151. }
  50152. }
  50153. else if (tN > tD) {
  50154. tN = tD;
  50155. // recompute sc for this edge
  50156. if ((-d + b) < 0.0) {
  50157. sN = 0;
  50158. }
  50159. else if ((-d + b) > a) {
  50160. sN = sD;
  50161. }
  50162. else {
  50163. sN = (-d + b);
  50164. sD = a;
  50165. }
  50166. }
  50167. // finally do the division to get sc and tc
  50168. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  50169. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  50170. // get the difference of the two closest points
  50171. var qtc = v.multiplyByFloats(tc, tc, tc);
  50172. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50173. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50174. if (isIntersected) {
  50175. return qtc.length();
  50176. }
  50177. return -1;
  50178. };
  50179. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50180. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50181. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50182. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50183. this.direction.normalize();
  50184. return this;
  50185. };
  50186. // Statics
  50187. Ray.Zero = function () {
  50188. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50189. };
  50190. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50191. var result = Ray.Zero();
  50192. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50193. };
  50194. /**
  50195. * 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
  50196. * transformed to the given world matrix.
  50197. * @param origin The origin point
  50198. * @param end The end point
  50199. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50200. */
  50201. Ray.CreateNewFromTo = function (origin, end, world) {
  50202. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50203. var direction = end.subtract(origin);
  50204. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50205. direction.normalize();
  50206. return Ray.Transform(new Ray(origin, direction, length), world);
  50207. };
  50208. Ray.Transform = function (ray, matrix) {
  50209. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50210. Ray.TransformToRef(ray, matrix, result);
  50211. return result;
  50212. };
  50213. Ray.TransformToRef = function (ray, matrix, result) {
  50214. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50215. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50216. result.length = ray.length;
  50217. var dir = result.direction;
  50218. var len = dir.length();
  50219. if (!(len === 0 || len === 1)) {
  50220. var num = 1.0 / len;
  50221. dir.x *= num;
  50222. dir.y *= num;
  50223. dir.z *= num;
  50224. result.length *= len;
  50225. }
  50226. };
  50227. Ray.smallnum = 0.00000001;
  50228. Ray.rayl = 10e8;
  50229. return Ray;
  50230. }());
  50231. BABYLON.Ray = Ray;
  50232. })(BABYLON || (BABYLON = {}));
  50233. //# sourceMappingURL=babylon.ray.js.map
  50234. var BABYLON;
  50235. (function (BABYLON) {
  50236. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50237. if (boxMin.x > sphereCenter.x + sphereRadius)
  50238. return false;
  50239. if (sphereCenter.x - sphereRadius > boxMax.x)
  50240. return false;
  50241. if (boxMin.y > sphereCenter.y + sphereRadius)
  50242. return false;
  50243. if (sphereCenter.y - sphereRadius > boxMax.y)
  50244. return false;
  50245. if (boxMin.z > sphereCenter.z + sphereRadius)
  50246. return false;
  50247. if (sphereCenter.z - sphereRadius > boxMax.z)
  50248. return false;
  50249. return true;
  50250. };
  50251. var getLowestRoot = (function () {
  50252. var result = { root: 0, found: false };
  50253. return function (a, b, c, maxR) {
  50254. result.root = 0;
  50255. result.found = false;
  50256. var determinant = b * b - 4.0 * a * c;
  50257. if (determinant < 0)
  50258. return result;
  50259. var sqrtD = Math.sqrt(determinant);
  50260. var r1 = (-b - sqrtD) / (2.0 * a);
  50261. var r2 = (-b + sqrtD) / (2.0 * a);
  50262. if (r1 > r2) {
  50263. var temp = r2;
  50264. r2 = r1;
  50265. r1 = temp;
  50266. }
  50267. if (r1 > 0 && r1 < maxR) {
  50268. result.root = r1;
  50269. result.found = true;
  50270. return result;
  50271. }
  50272. if (r2 > 0 && r2 < maxR) {
  50273. result.root = r2;
  50274. result.found = true;
  50275. return result;
  50276. }
  50277. return result;
  50278. };
  50279. })();
  50280. var Collider = /** @class */ (function () {
  50281. function Collider() {
  50282. this._collisionPoint = BABYLON.Vector3.Zero();
  50283. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50284. this._tempVector = BABYLON.Vector3.Zero();
  50285. this._tempVector2 = BABYLON.Vector3.Zero();
  50286. this._tempVector3 = BABYLON.Vector3.Zero();
  50287. this._tempVector4 = BABYLON.Vector3.Zero();
  50288. this._edge = BABYLON.Vector3.Zero();
  50289. this._baseToVertex = BABYLON.Vector3.Zero();
  50290. this._destinationPoint = BABYLON.Vector3.Zero();
  50291. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50292. this._displacementVector = BABYLON.Vector3.Zero();
  50293. this._radius = BABYLON.Vector3.One();
  50294. this._retry = 0;
  50295. this._basePointWorld = BABYLON.Vector3.Zero();
  50296. this._velocityWorld = BABYLON.Vector3.Zero();
  50297. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50298. this._collisionMask = -1;
  50299. }
  50300. Object.defineProperty(Collider.prototype, "collisionMask", {
  50301. get: function () {
  50302. return this._collisionMask;
  50303. },
  50304. set: function (mask) {
  50305. this._collisionMask = !isNaN(mask) ? mask : -1;
  50306. },
  50307. enumerable: true,
  50308. configurable: true
  50309. });
  50310. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50311. /**
  50312. * Gets the plane normal used to compute the sliding response (in local space)
  50313. */
  50314. get: function () {
  50315. return this._slidePlaneNormal;
  50316. },
  50317. enumerable: true,
  50318. configurable: true
  50319. });
  50320. // Methods
  50321. Collider.prototype._initialize = function (source, dir, e) {
  50322. this._velocity = dir;
  50323. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50324. this._basePoint = source;
  50325. source.multiplyToRef(this._radius, this._basePointWorld);
  50326. dir.multiplyToRef(this._radius, this._velocityWorld);
  50327. this._velocityWorldLength = this._velocityWorld.length();
  50328. this._epsilon = e;
  50329. this.collisionFound = false;
  50330. };
  50331. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50332. pa.subtractToRef(point, this._tempVector);
  50333. pb.subtractToRef(point, this._tempVector2);
  50334. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  50335. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50336. if (d < 0)
  50337. return false;
  50338. pc.subtractToRef(point, this._tempVector3);
  50339. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  50340. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50341. if (d < 0)
  50342. return false;
  50343. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  50344. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50345. return d >= 0;
  50346. };
  50347. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50348. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50349. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50350. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50351. return false;
  50352. }
  50353. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50354. return false;
  50355. return true;
  50356. };
  50357. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50358. var t0;
  50359. var embeddedInPlane = false;
  50360. //defensive programming, actually not needed.
  50361. if (!trianglePlaneArray) {
  50362. trianglePlaneArray = [];
  50363. }
  50364. if (!trianglePlaneArray[faceIndex]) {
  50365. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50366. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50367. }
  50368. var trianglePlane = trianglePlaneArray[faceIndex];
  50369. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50370. return;
  50371. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50372. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50373. if (normalDotVelocity == 0) {
  50374. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50375. return;
  50376. embeddedInPlane = true;
  50377. t0 = 0;
  50378. }
  50379. else {
  50380. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50381. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50382. if (t0 > t1) {
  50383. var temp = t1;
  50384. t1 = t0;
  50385. t0 = temp;
  50386. }
  50387. if (t0 > 1.0 || t1 < 0.0)
  50388. return;
  50389. if (t0 < 0)
  50390. t0 = 0;
  50391. if (t0 > 1.0)
  50392. t0 = 1.0;
  50393. }
  50394. this._collisionPoint.copyFromFloats(0, 0, 0);
  50395. var found = false;
  50396. var t = 1.0;
  50397. if (!embeddedInPlane) {
  50398. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  50399. this._velocity.scaleToRef(t0, this._tempVector);
  50400. this._planeIntersectionPoint.addInPlace(this._tempVector);
  50401. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  50402. found = true;
  50403. t = t0;
  50404. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  50405. }
  50406. }
  50407. if (!found) {
  50408. var velocitySquaredLength = this._velocity.lengthSquared();
  50409. var a = velocitySquaredLength;
  50410. this._basePoint.subtractToRef(p1, this._tempVector);
  50411. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50412. var c = this._tempVector.lengthSquared() - 1.0;
  50413. var lowestRoot = getLowestRoot(a, b, c, t);
  50414. if (lowestRoot.found) {
  50415. t = lowestRoot.root;
  50416. found = true;
  50417. this._collisionPoint.copyFrom(p1);
  50418. }
  50419. this._basePoint.subtractToRef(p2, this._tempVector);
  50420. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50421. c = this._tempVector.lengthSquared() - 1.0;
  50422. lowestRoot = getLowestRoot(a, b, c, t);
  50423. if (lowestRoot.found) {
  50424. t = lowestRoot.root;
  50425. found = true;
  50426. this._collisionPoint.copyFrom(p2);
  50427. }
  50428. this._basePoint.subtractToRef(p3, this._tempVector);
  50429. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50430. c = this._tempVector.lengthSquared() - 1.0;
  50431. lowestRoot = getLowestRoot(a, b, c, t);
  50432. if (lowestRoot.found) {
  50433. t = lowestRoot.root;
  50434. found = true;
  50435. this._collisionPoint.copyFrom(p3);
  50436. }
  50437. p2.subtractToRef(p1, this._edge);
  50438. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50439. var edgeSquaredLength = this._edge.lengthSquared();
  50440. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50441. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50442. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50443. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50444. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50445. lowestRoot = getLowestRoot(a, b, c, t);
  50446. if (lowestRoot.found) {
  50447. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50448. if (f >= 0.0 && f <= 1.0) {
  50449. t = lowestRoot.root;
  50450. found = true;
  50451. this._edge.scaleInPlace(f);
  50452. p1.addToRef(this._edge, this._collisionPoint);
  50453. }
  50454. }
  50455. p3.subtractToRef(p2, this._edge);
  50456. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50457. edgeSquaredLength = this._edge.lengthSquared();
  50458. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50459. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50460. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50461. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50462. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50463. lowestRoot = getLowestRoot(a, b, c, t);
  50464. if (lowestRoot.found) {
  50465. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50466. if (f >= 0.0 && f <= 1.0) {
  50467. t = lowestRoot.root;
  50468. found = true;
  50469. this._edge.scaleInPlace(f);
  50470. p2.addToRef(this._edge, this._collisionPoint);
  50471. }
  50472. }
  50473. p1.subtractToRef(p3, this._edge);
  50474. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50475. edgeSquaredLength = this._edge.lengthSquared();
  50476. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50477. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50478. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50479. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50480. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50481. lowestRoot = getLowestRoot(a, b, c, t);
  50482. if (lowestRoot.found) {
  50483. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50484. if (f >= 0.0 && f <= 1.0) {
  50485. t = lowestRoot.root;
  50486. found = true;
  50487. this._edge.scaleInPlace(f);
  50488. p3.addToRef(this._edge, this._collisionPoint);
  50489. }
  50490. }
  50491. }
  50492. if (found) {
  50493. var distToCollision = t * this._velocity.length();
  50494. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50495. if (!this.intersectionPoint) {
  50496. this.intersectionPoint = this._collisionPoint.clone();
  50497. }
  50498. else {
  50499. this.intersectionPoint.copyFrom(this._collisionPoint);
  50500. }
  50501. this._nearestDistance = distToCollision;
  50502. this.collisionFound = true;
  50503. }
  50504. }
  50505. };
  50506. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50507. for (var i = indexStart; i < indexEnd; i += 3) {
  50508. var p1 = pts[indices[i] - decal];
  50509. var p2 = pts[indices[i + 1] - decal];
  50510. var p3 = pts[indices[i + 2] - decal];
  50511. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50512. }
  50513. };
  50514. Collider.prototype._getResponse = function (pos, vel) {
  50515. pos.addToRef(vel, this._destinationPoint);
  50516. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50517. this._basePoint.addToRef(vel, pos);
  50518. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50519. this._slidePlaneNormal.normalize();
  50520. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50521. pos.addInPlace(this._displacementVector);
  50522. this.intersectionPoint.addInPlace(this._displacementVector);
  50523. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50524. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50525. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50526. };
  50527. return Collider;
  50528. }());
  50529. BABYLON.Collider = Collider;
  50530. })(BABYLON || (BABYLON = {}));
  50531. //# sourceMappingURL=babylon.collider.js.map
  50532. var BABYLON;
  50533. (function (BABYLON) {
  50534. //WebWorker code will be inserted to this variable.
  50535. BABYLON.CollisionWorker = "";
  50536. var WorkerTaskType;
  50537. (function (WorkerTaskType) {
  50538. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50539. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50540. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50541. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50542. var WorkerReplyType;
  50543. (function (WorkerReplyType) {
  50544. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  50545. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  50546. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  50547. var CollisionCoordinatorWorker = /** @class */ (function () {
  50548. function CollisionCoordinatorWorker() {
  50549. var _this = this;
  50550. this._scaledPosition = BABYLON.Vector3.Zero();
  50551. this._scaledVelocity = BABYLON.Vector3.Zero();
  50552. this.onMeshUpdated = function (transformNode) {
  50553. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  50554. };
  50555. this.onGeometryUpdated = function (geometry) {
  50556. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  50557. };
  50558. this._afterRender = function () {
  50559. if (!_this._init)
  50560. return;
  50561. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  50562. return;
  50563. }
  50564. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  50565. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  50566. if (_this._runningUpdated > 4) {
  50567. return;
  50568. }
  50569. ++_this._runningUpdated;
  50570. var payload = {
  50571. updatedMeshes: _this._addUpdateMeshesList,
  50572. updatedGeometries: _this._addUpdateGeometriesList,
  50573. removedGeometries: _this._toRemoveGeometryArray,
  50574. removedMeshes: _this._toRemoveMeshesArray
  50575. };
  50576. var message = {
  50577. payload: payload,
  50578. taskType: WorkerTaskType.UPDATE
  50579. };
  50580. var serializable = [];
  50581. for (var id in payload.updatedGeometries) {
  50582. if (payload.updatedGeometries.hasOwnProperty(id)) {
  50583. //prepare transferables
  50584. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  50585. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  50586. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  50587. }
  50588. }
  50589. _this._worker.postMessage(message, serializable);
  50590. _this._addUpdateMeshesList = {};
  50591. _this._addUpdateGeometriesList = {};
  50592. _this._toRemoveGeometryArray = [];
  50593. _this._toRemoveMeshesArray = [];
  50594. };
  50595. this._onMessageFromWorker = function (e) {
  50596. var returnData = e.data;
  50597. if (returnData.error != WorkerReplyType.SUCCESS) {
  50598. //TODO what errors can be returned from the worker?
  50599. BABYLON.Tools.Warn("error returned from worker!");
  50600. return;
  50601. }
  50602. switch (returnData.taskType) {
  50603. case WorkerTaskType.INIT:
  50604. _this._init = true;
  50605. //Update the worked with ALL of the scene's current state
  50606. _this._scene.meshes.forEach(function (mesh) {
  50607. _this.onMeshAdded(mesh);
  50608. });
  50609. _this._scene.getGeometries().forEach(function (geometry) {
  50610. _this.onGeometryAdded(geometry);
  50611. });
  50612. break;
  50613. case WorkerTaskType.UPDATE:
  50614. _this._runningUpdated--;
  50615. break;
  50616. case WorkerTaskType.COLLIDE:
  50617. var returnPayload = returnData.payload;
  50618. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  50619. return;
  50620. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  50621. if (callback) {
  50622. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  50623. if (mesh) {
  50624. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  50625. }
  50626. }
  50627. //cleanup
  50628. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  50629. break;
  50630. }
  50631. };
  50632. this._collisionsCallbackArray = [];
  50633. this._init = false;
  50634. this._runningUpdated = 0;
  50635. this._addUpdateMeshesList = {};
  50636. this._addUpdateGeometriesList = {};
  50637. this._toRemoveGeometryArray = [];
  50638. this._toRemoveMeshesArray = [];
  50639. }
  50640. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50641. if (!this._init)
  50642. return;
  50643. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  50644. return;
  50645. position.divideToRef(collider._radius, this._scaledPosition);
  50646. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50647. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  50648. var payload = {
  50649. collider: {
  50650. position: this._scaledPosition.asArray(),
  50651. velocity: this._scaledVelocity.asArray(),
  50652. radius: collider._radius.asArray()
  50653. },
  50654. collisionId: collisionIndex,
  50655. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  50656. maximumRetry: maximumRetry
  50657. };
  50658. var message = {
  50659. payload: payload,
  50660. taskType: WorkerTaskType.COLLIDE
  50661. };
  50662. this._worker.postMessage(message);
  50663. };
  50664. CollisionCoordinatorWorker.prototype.init = function (scene) {
  50665. this._scene = scene;
  50666. this._scene.registerAfterRender(this._afterRender);
  50667. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  50668. this._worker = new Worker(workerUrl);
  50669. this._worker.onmessage = this._onMessageFromWorker;
  50670. var message = {
  50671. payload: {},
  50672. taskType: WorkerTaskType.INIT
  50673. };
  50674. this._worker.postMessage(message);
  50675. };
  50676. CollisionCoordinatorWorker.prototype.destroy = function () {
  50677. this._scene.unregisterAfterRender(this._afterRender);
  50678. this._worker.terminate();
  50679. };
  50680. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  50681. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  50682. this.onMeshUpdated(mesh);
  50683. };
  50684. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  50685. this._toRemoveMeshesArray.push(mesh.uniqueId);
  50686. };
  50687. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  50688. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  50689. geometry.onGeometryUpdated = this.onGeometryUpdated;
  50690. this.onGeometryUpdated(geometry);
  50691. };
  50692. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  50693. this._toRemoveGeometryArray.push(geometry.id);
  50694. };
  50695. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  50696. var submeshes = [];
  50697. if (mesh.subMeshes) {
  50698. submeshes = mesh.subMeshes.map(function (sm, idx) {
  50699. var boundingInfo = sm.getBoundingInfo();
  50700. return {
  50701. position: idx,
  50702. verticesStart: sm.verticesStart,
  50703. verticesCount: sm.verticesCount,
  50704. indexStart: sm.indexStart,
  50705. indexCount: sm.indexCount,
  50706. hasMaterial: !!sm.getMaterial(),
  50707. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50708. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50709. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50710. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  50711. };
  50712. });
  50713. }
  50714. var geometryId = null;
  50715. if (mesh instanceof BABYLON.Mesh) {
  50716. var geometry = mesh.geometry;
  50717. geometryId = geometry ? geometry.id : null;
  50718. }
  50719. else if (mesh instanceof BABYLON.InstancedMesh) {
  50720. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  50721. geometryId = geometry ? geometry.id : null;
  50722. }
  50723. var boundingInfo = mesh.getBoundingInfo();
  50724. return {
  50725. uniqueId: mesh.uniqueId,
  50726. id: mesh.id,
  50727. name: mesh.name,
  50728. geometryId: geometryId,
  50729. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50730. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50731. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50732. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  50733. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  50734. subMeshes: submeshes,
  50735. checkCollisions: mesh.checkCollisions
  50736. };
  50737. };
  50738. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  50739. return {
  50740. id: geometry.id,
  50741. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  50742. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  50743. indices: new Uint32Array(geometry.getIndices() || []),
  50744. };
  50745. };
  50746. return CollisionCoordinatorWorker;
  50747. }());
  50748. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  50749. var CollisionCoordinatorLegacy = /** @class */ (function () {
  50750. function CollisionCoordinatorLegacy() {
  50751. this._scaledPosition = BABYLON.Vector3.Zero();
  50752. this._scaledVelocity = BABYLON.Vector3.Zero();
  50753. this._finalPosition = BABYLON.Vector3.Zero();
  50754. }
  50755. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50756. position.divideToRef(collider._radius, this._scaledPosition);
  50757. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50758. collider.collidedMesh = null;
  50759. collider._retry = 0;
  50760. collider._initialVelocity = this._scaledVelocity;
  50761. collider._initialPosition = this._scaledPosition;
  50762. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  50763. this._finalPosition.multiplyInPlace(collider._radius);
  50764. //run the callback
  50765. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  50766. };
  50767. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  50768. this._scene = scene;
  50769. };
  50770. CollisionCoordinatorLegacy.prototype.destroy = function () {
  50771. //Legacy need no destruction method.
  50772. };
  50773. //No update in legacy mode
  50774. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  50775. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  50776. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  50777. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  50778. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  50779. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  50780. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  50781. if (excludedMesh === void 0) { excludedMesh = null; }
  50782. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  50783. if (collider._retry >= maximumRetry) {
  50784. finalPosition.copyFrom(position);
  50785. return;
  50786. }
  50787. // Check if this is a mesh else camera or -1
  50788. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  50789. collider._initialize(position, velocity, closeDistance);
  50790. // Check all meshes
  50791. for (var index = 0; index < this._scene.meshes.length; index++) {
  50792. var mesh = this._scene.meshes[index];
  50793. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  50794. mesh._checkCollision(collider);
  50795. }
  50796. }
  50797. if (!collider.collisionFound) {
  50798. position.addToRef(velocity, finalPosition);
  50799. return;
  50800. }
  50801. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  50802. collider._getResponse(position, velocity);
  50803. }
  50804. if (velocity.length() <= closeDistance) {
  50805. finalPosition.copyFrom(position);
  50806. return;
  50807. }
  50808. collider._retry++;
  50809. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  50810. };
  50811. return CollisionCoordinatorLegacy;
  50812. }());
  50813. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  50814. })(BABYLON || (BABYLON = {}));
  50815. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  50816. var BABYLON;
  50817. (function (BABYLON) {
  50818. /**
  50819. * A particle represents one of the element emitted by a particle system.
  50820. * This is mainly define by its coordinates, direction, velocity and age.
  50821. */
  50822. var Particle = /** @class */ (function () {
  50823. /**
  50824. * Creates a new instance of @see Particle
  50825. * @param particleSystem the particle system the particle belongs to
  50826. */
  50827. function Particle(
  50828. /**
  50829. * particleSystem the particle system the particle belongs to.
  50830. */
  50831. particleSystem) {
  50832. this.particleSystem = particleSystem;
  50833. /**
  50834. * The world position of the particle in the scene.
  50835. */
  50836. this.position = BABYLON.Vector3.Zero();
  50837. /**
  50838. * The world direction of the particle in the scene.
  50839. */
  50840. this.direction = BABYLON.Vector3.Zero();
  50841. /**
  50842. * The color of the particle.
  50843. */
  50844. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50845. /**
  50846. * The color change of the particle per step.
  50847. */
  50848. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50849. /**
  50850. * Defines how long will the life of the particle be.
  50851. */
  50852. this.lifeTime = 1.0;
  50853. /**
  50854. * The current age of the particle.
  50855. */
  50856. this.age = 0;
  50857. /**
  50858. * The current size of the particle.
  50859. */
  50860. this.size = 0;
  50861. /**
  50862. * The current angle of the particle.
  50863. */
  50864. this.angle = 0;
  50865. /**
  50866. * Defines how fast is the angle changing.
  50867. */
  50868. this.angularSpeed = 0;
  50869. /**
  50870. * Defines the cell index used by the particle to be rendered from a sprite.
  50871. */
  50872. this.cellIndex = 0;
  50873. this._currentFrameCounter = 0;
  50874. if (!this.particleSystem.isAnimationSheetEnabled) {
  50875. return;
  50876. }
  50877. this.updateCellInfoFromSystem();
  50878. }
  50879. Particle.prototype.updateCellInfoFromSystem = function () {
  50880. this.cellIndex = this.particleSystem.startSpriteCellID;
  50881. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50882. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  50883. }
  50884. else {
  50885. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  50886. }
  50887. };
  50888. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50889. // (ageOffset / scaledUpdateSpeed) / available cells
  50890. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50891. this._currentFrameCounter += scaledUpdateSpeed;
  50892. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50893. this._currentFrameCounter = 0;
  50894. this.cellIndex++;
  50895. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50896. this.cellIndex = this.particleSystem.endSpriteCellID;
  50897. }
  50898. }
  50899. };
  50900. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  50901. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50902. this.cellIndex++;
  50903. this._currentFrameCounter = 0;
  50904. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50905. if (this.particleSystem.spriteCellLoop) {
  50906. this.cellIndex = this.particleSystem.startSpriteCellID;
  50907. }
  50908. else {
  50909. this.cellIndex = this.particleSystem.endSpriteCellID;
  50910. }
  50911. }
  50912. }
  50913. else {
  50914. this._currentFrameCounter++;
  50915. }
  50916. };
  50917. /**
  50918. * Copy the properties of particle to another one.
  50919. * @param other the particle to copy the information to.
  50920. */
  50921. Particle.prototype.copyTo = function (other) {
  50922. other.position.copyFrom(this.position);
  50923. other.direction.copyFrom(this.direction);
  50924. other.color.copyFrom(this.color);
  50925. other.colorStep.copyFrom(this.colorStep);
  50926. other.lifeTime = this.lifeTime;
  50927. other.age = this.age;
  50928. other.size = this.size;
  50929. other.angle = this.angle;
  50930. other.angularSpeed = this.angularSpeed;
  50931. other.particleSystem = this.particleSystem;
  50932. other.cellIndex = this.cellIndex;
  50933. };
  50934. return Particle;
  50935. }());
  50936. BABYLON.Particle = Particle;
  50937. })(BABYLON || (BABYLON = {}));
  50938. //# sourceMappingURL=babylon.particle.js.map
  50939. var BABYLON;
  50940. (function (BABYLON) {
  50941. /**
  50942. * This represents a particle system in Babylon.
  50943. * 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.
  50944. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50945. * @example https://doc.babylonjs.com/babylon101/particles
  50946. */
  50947. var ParticleSystem = /** @class */ (function () {
  50948. /**
  50949. * Instantiates a particle system.
  50950. * 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.
  50951. * @param name The name of the particle system
  50952. * @param capacity The max number of particles alive at the same time
  50953. * @param scene The scene the particle system belongs to
  50954. * @param customEffect a custom effect used to change the way particles are rendered by default
  50955. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50956. * @param epsilon Offset used to render the particles
  50957. */
  50958. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50959. if (customEffect === void 0) { customEffect = null; }
  50960. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50961. if (epsilon === void 0) { epsilon = 0.01; }
  50962. var _this = this;
  50963. /**
  50964. * List of animations used by the particle system.
  50965. */
  50966. this.animations = [];
  50967. /**
  50968. * The rendering group used by the Particle system to chose when to render.
  50969. */
  50970. this.renderingGroupId = 0;
  50971. /**
  50972. * The emitter represents the Mesh or position we are attaching the particle system to.
  50973. */
  50974. this.emitter = null;
  50975. /**
  50976. * The maximum number of particles to emit per frame
  50977. */
  50978. this.emitRate = 10;
  50979. /**
  50980. * If you want to launch only a few particles at once, that can be done, as well.
  50981. */
  50982. this.manualEmitCount = -1;
  50983. /**
  50984. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50985. */
  50986. this.updateSpeed = 0.01;
  50987. /**
  50988. * The amount of time the particle system is running (depends of the overall update speed).
  50989. */
  50990. this.targetStopDuration = 0;
  50991. /**
  50992. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50993. */
  50994. this.disposeOnStop = false;
  50995. /**
  50996. * Minimum power of emitting particles.
  50997. */
  50998. this.minEmitPower = 1;
  50999. /**
  51000. * Maximum power of emitting particles.
  51001. */
  51002. this.maxEmitPower = 1;
  51003. /**
  51004. * Minimum life time of emitting particles.
  51005. */
  51006. this.minLifeTime = 1;
  51007. /**
  51008. * Maximum life time of emitting particles.
  51009. */
  51010. this.maxLifeTime = 1;
  51011. /**
  51012. * Minimum Size of emitting particles.
  51013. */
  51014. this.minSize = 1;
  51015. /**
  51016. * Maximum Size of emitting particles.
  51017. */
  51018. this.maxSize = 1;
  51019. /**
  51020. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  51021. */
  51022. this.minAngularSpeed = 0;
  51023. /**
  51024. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  51025. */
  51026. this.maxAngularSpeed = 0;
  51027. /**
  51028. * The layer mask we are rendering the particles through.
  51029. */
  51030. this.layerMask = 0x0FFFFFFF;
  51031. /**
  51032. * This can help using your own shader to render the particle system.
  51033. * The according effect will be created
  51034. */
  51035. this.customShader = null;
  51036. /**
  51037. * By default particle system starts as soon as they are created. This prevents the
  51038. * automatic start to happen and let you decide when to start emitting particles.
  51039. */
  51040. this.preventAutoStart = false;
  51041. /**
  51042. * Callback triggered when the particle animation is ending.
  51043. */
  51044. this.onAnimationEnd = null;
  51045. /**
  51046. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  51047. */
  51048. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  51049. /**
  51050. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  51051. * to override the particles.
  51052. */
  51053. this.forceDepthWrite = false;
  51054. /**
  51055. * You can use gravity if you want to give an orientation to your particles.
  51056. */
  51057. this.gravity = BABYLON.Vector3.Zero();
  51058. /**
  51059. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51060. */
  51061. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51062. /**
  51063. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51064. */
  51065. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51066. /**
  51067. * Color the particle will have at the end of its lifetime.
  51068. */
  51069. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  51070. /**
  51071. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  51072. */
  51073. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51074. /**
  51075. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  51076. */
  51077. this.spriteCellLoop = true;
  51078. /**
  51079. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  51080. */
  51081. this.spriteCellChangeSpeed = 0;
  51082. /**
  51083. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  51084. */
  51085. this.startSpriteCellID = 0;
  51086. /**
  51087. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  51088. */
  51089. this.endSpriteCellID = 0;
  51090. /**
  51091. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  51092. */
  51093. this.spriteCellWidth = 0;
  51094. /**
  51095. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  51096. */
  51097. this.spriteCellHeight = 0;
  51098. /**
  51099. * An event triggered when the system is disposed.
  51100. */
  51101. this.onDisposeObservable = new BABYLON.Observable();
  51102. this._particles = new Array();
  51103. this._stockParticles = new Array();
  51104. this._newPartsExcess = 0;
  51105. this._vertexBuffers = {};
  51106. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  51107. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  51108. this._scaledDirection = BABYLON.Vector3.Zero();
  51109. this._scaledGravity = BABYLON.Vector3.Zero();
  51110. this._currentRenderId = -1;
  51111. this._started = false;
  51112. this._stopped = false;
  51113. this._actualFrame = 0;
  51114. this._vertexBufferSize = 11;
  51115. // start of sub system methods
  51116. /**
  51117. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51118. * Its lifetime will start back at 0.
  51119. */
  51120. this.recycleParticle = function (particle) {
  51121. var lastParticle = _this._particles.pop();
  51122. if (lastParticle !== particle) {
  51123. lastParticle.copyTo(particle);
  51124. }
  51125. _this._stockParticles.push(lastParticle);
  51126. };
  51127. this._createParticle = function () {
  51128. var particle;
  51129. if (_this._stockParticles.length !== 0) {
  51130. particle = _this._stockParticles.pop();
  51131. particle.age = 0;
  51132. particle.cellIndex = _this.startSpriteCellID;
  51133. }
  51134. else {
  51135. particle = new BABYLON.Particle(_this);
  51136. }
  51137. return particle;
  51138. };
  51139. this._emitFromParticle = function (particle) {
  51140. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  51141. return;
  51142. }
  51143. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  51144. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  51145. subSystem._rootParticleSystem = _this;
  51146. _this.activeSubSystems.push(subSystem);
  51147. subSystem.start();
  51148. };
  51149. this._appendParticleVertexes = null;
  51150. this.id = name;
  51151. this.name = name;
  51152. this._capacity = capacity;
  51153. this._epsilon = epsilon;
  51154. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  51155. if (isAnimationSheetEnabled) {
  51156. this._vertexBufferSize = 12;
  51157. }
  51158. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51159. this._customEffect = customEffect;
  51160. scene.particleSystems.push(this);
  51161. this._createIndexBuffer();
  51162. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  51163. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  51164. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  51165. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  51166. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  51167. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  51168. if (this._isAnimationSheetEnabled) {
  51169. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  51170. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  51171. }
  51172. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51173. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51174. this._vertexBuffers["options"] = options;
  51175. // Default emitter type
  51176. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51177. this.updateFunction = function (particles) {
  51178. for (var index = 0; index < particles.length; index++) {
  51179. var particle = particles[index];
  51180. particle.age += _this._scaledUpdateSpeed;
  51181. if (particle.age >= particle.lifeTime) {
  51182. _this._emitFromParticle(particle);
  51183. _this.recycleParticle(particle);
  51184. index--;
  51185. continue;
  51186. }
  51187. else {
  51188. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51189. particle.color.addInPlace(_this._scaledColorStep);
  51190. if (particle.color.a < 0)
  51191. particle.color.a = 0;
  51192. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51193. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51194. particle.position.addInPlace(_this._scaledDirection);
  51195. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51196. particle.direction.addInPlace(_this._scaledGravity);
  51197. if (_this._isAnimationSheetEnabled) {
  51198. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51199. }
  51200. }
  51201. }
  51202. };
  51203. }
  51204. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51205. /**
  51206. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51207. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51208. */
  51209. get: function () {
  51210. if (this.particleEmitterType.direction1) {
  51211. return this.particleEmitterType.direction1;
  51212. }
  51213. return BABYLON.Vector3.Zero();
  51214. },
  51215. set: function (value) {
  51216. if (this.particleEmitterType.direction1) {
  51217. this.particleEmitterType.direction1 = value;
  51218. }
  51219. },
  51220. enumerable: true,
  51221. configurable: true
  51222. });
  51223. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51224. /**
  51225. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51226. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51227. */
  51228. get: function () {
  51229. if (this.particleEmitterType.direction2) {
  51230. return this.particleEmitterType.direction2;
  51231. }
  51232. return BABYLON.Vector3.Zero();
  51233. },
  51234. set: function (value) {
  51235. if (this.particleEmitterType.direction2) {
  51236. this.particleEmitterType.direction2 = value;
  51237. }
  51238. },
  51239. enumerable: true,
  51240. configurable: true
  51241. });
  51242. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51243. /**
  51244. * 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.
  51245. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51246. */
  51247. get: function () {
  51248. if (this.particleEmitterType.minEmitBox) {
  51249. return this.particleEmitterType.minEmitBox;
  51250. }
  51251. return BABYLON.Vector3.Zero();
  51252. },
  51253. set: function (value) {
  51254. if (this.particleEmitterType.minEmitBox) {
  51255. this.particleEmitterType.minEmitBox = value;
  51256. }
  51257. },
  51258. enumerable: true,
  51259. configurable: true
  51260. });
  51261. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  51262. /**
  51263. * 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.
  51264. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51265. */
  51266. get: function () {
  51267. if (this.particleEmitterType.maxEmitBox) {
  51268. return this.particleEmitterType.maxEmitBox;
  51269. }
  51270. return BABYLON.Vector3.Zero();
  51271. },
  51272. set: function (value) {
  51273. if (this.particleEmitterType.maxEmitBox) {
  51274. this.particleEmitterType.maxEmitBox = value;
  51275. }
  51276. },
  51277. enumerable: true,
  51278. configurable: true
  51279. });
  51280. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  51281. /**
  51282. * Sets a callback that will be triggered when the system is disposed.
  51283. */
  51284. set: function (callback) {
  51285. if (this._onDisposeObserver) {
  51286. this.onDisposeObservable.remove(this._onDisposeObserver);
  51287. }
  51288. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51289. },
  51290. enumerable: true,
  51291. configurable: true
  51292. });
  51293. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  51294. /**
  51295. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  51296. */
  51297. get: function () {
  51298. return this._isAnimationSheetEnabled;
  51299. },
  51300. enumerable: true,
  51301. configurable: true
  51302. });
  51303. Object.defineProperty(ParticleSystem.prototype, "particles", {
  51304. //end of Sub-emitter
  51305. /**
  51306. * Gets the current list of active particles
  51307. */
  51308. get: function () {
  51309. return this._particles;
  51310. },
  51311. enumerable: true,
  51312. configurable: true
  51313. });
  51314. /**
  51315. * Returns the string "ParticleSystem"
  51316. * @returns a string containing the class name
  51317. */
  51318. ParticleSystem.prototype.getClassName = function () {
  51319. return "ParticleSystem";
  51320. };
  51321. ParticleSystem.prototype._createIndexBuffer = function () {
  51322. var indices = [];
  51323. var index = 0;
  51324. for (var count = 0; count < this._capacity; count++) {
  51325. indices.push(index);
  51326. indices.push(index + 1);
  51327. indices.push(index + 2);
  51328. indices.push(index);
  51329. indices.push(index + 2);
  51330. indices.push(index + 3);
  51331. index += 4;
  51332. }
  51333. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  51334. };
  51335. /**
  51336. * Gets the maximum number of particles active at the same time.
  51337. * @returns The max number of active particles.
  51338. */
  51339. ParticleSystem.prototype.getCapacity = function () {
  51340. return this._capacity;
  51341. };
  51342. /**
  51343. * Gets Wether there are still active particles in the system.
  51344. * @returns True if it is alive, otherwise false.
  51345. */
  51346. ParticleSystem.prototype.isAlive = function () {
  51347. return this._alive;
  51348. };
  51349. /**
  51350. * Gets Wether the system has been started.
  51351. * @returns True if it has been started, otherwise false.
  51352. */
  51353. ParticleSystem.prototype.isStarted = function () {
  51354. return this._started;
  51355. };
  51356. /**
  51357. * Starts the particle system and begins to emit.
  51358. */
  51359. ParticleSystem.prototype.start = function () {
  51360. this._started = true;
  51361. this._stopped = false;
  51362. this._actualFrame = 0;
  51363. if (this.subEmitters && this.subEmitters.length != 0) {
  51364. this.activeSubSystems = new Array();
  51365. }
  51366. };
  51367. /**
  51368. * Stops the particle system.
  51369. * @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.
  51370. */
  51371. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  51372. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  51373. this._stopped = true;
  51374. if (stopSubEmitters) {
  51375. this._stopSubEmitters();
  51376. }
  51377. };
  51378. // animation sheet
  51379. /**
  51380. * Remove all active particles
  51381. */
  51382. ParticleSystem.prototype.reset = function () {
  51383. this._stockParticles = [];
  51384. this._particles = [];
  51385. };
  51386. /**
  51387. * @ignore (for internal use only)
  51388. */
  51389. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  51390. var offset = index * this._vertexBufferSize;
  51391. this._vertexData[offset] = particle.position.x;
  51392. this._vertexData[offset + 1] = particle.position.y;
  51393. this._vertexData[offset + 2] = particle.position.z;
  51394. this._vertexData[offset + 3] = particle.color.r;
  51395. this._vertexData[offset + 4] = particle.color.g;
  51396. this._vertexData[offset + 5] = particle.color.b;
  51397. this._vertexData[offset + 6] = particle.color.a;
  51398. this._vertexData[offset + 7] = particle.angle;
  51399. this._vertexData[offset + 8] = particle.size;
  51400. this._vertexData[offset + 9] = offsetX;
  51401. this._vertexData[offset + 10] = offsetY;
  51402. };
  51403. /**
  51404. * @ignore (for internal use only)
  51405. */
  51406. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  51407. if (offsetX === 0)
  51408. offsetX = this._epsilon;
  51409. else if (offsetX === 1)
  51410. offsetX = 1 - this._epsilon;
  51411. if (offsetY === 0)
  51412. offsetY = this._epsilon;
  51413. else if (offsetY === 1)
  51414. offsetY = 1 - this._epsilon;
  51415. var offset = index * this._vertexBufferSize;
  51416. this._vertexData[offset] = particle.position.x;
  51417. this._vertexData[offset + 1] = particle.position.y;
  51418. this._vertexData[offset + 2] = particle.position.z;
  51419. this._vertexData[offset + 3] = particle.color.r;
  51420. this._vertexData[offset + 4] = particle.color.g;
  51421. this._vertexData[offset + 5] = particle.color.b;
  51422. this._vertexData[offset + 6] = particle.color.a;
  51423. this._vertexData[offset + 7] = particle.angle;
  51424. this._vertexData[offset + 8] = particle.size;
  51425. this._vertexData[offset + 9] = offsetX;
  51426. this._vertexData[offset + 10] = offsetY;
  51427. this._vertexData[offset + 11] = particle.cellIndex;
  51428. };
  51429. ParticleSystem.prototype._stopSubEmitters = function () {
  51430. if (!this.activeSubSystems) {
  51431. return;
  51432. }
  51433. this.activeSubSystems.forEach(function (subSystem) {
  51434. subSystem.stop(true);
  51435. });
  51436. this.activeSubSystems = new Array();
  51437. };
  51438. ParticleSystem.prototype._removeFromRoot = function () {
  51439. if (!this._rootParticleSystem) {
  51440. return;
  51441. }
  51442. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  51443. if (index !== -1) {
  51444. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  51445. }
  51446. };
  51447. // end of sub system methods
  51448. ParticleSystem.prototype._update = function (newParticles) {
  51449. // Update current
  51450. this._alive = this._particles.length > 0;
  51451. this.updateFunction(this._particles);
  51452. // Add new ones
  51453. var worldMatrix;
  51454. if (this.emitter.position) {
  51455. var emitterMesh = this.emitter;
  51456. worldMatrix = emitterMesh.getWorldMatrix();
  51457. }
  51458. else {
  51459. var emitterPosition = this.emitter;
  51460. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51461. }
  51462. var particle;
  51463. for (var index = 0; index < newParticles; index++) {
  51464. if (this._particles.length === this._capacity) {
  51465. break;
  51466. }
  51467. particle = this._createParticle();
  51468. this._particles.push(particle);
  51469. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  51470. if (this.startPositionFunction) {
  51471. this.startPositionFunction(worldMatrix, particle.position, particle);
  51472. }
  51473. else {
  51474. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  51475. }
  51476. if (this.startDirectionFunction) {
  51477. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51478. }
  51479. else {
  51480. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51481. }
  51482. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  51483. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  51484. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  51485. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  51486. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  51487. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  51488. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  51489. }
  51490. };
  51491. ParticleSystem.prototype._getEffect = function () {
  51492. if (this._customEffect) {
  51493. return this._customEffect;
  51494. }
  51495. ;
  51496. var defines = [];
  51497. if (this._scene.clipPlane) {
  51498. defines.push("#define CLIPPLANE");
  51499. }
  51500. if (this._isAnimationSheetEnabled) {
  51501. defines.push("#define ANIMATESHEET");
  51502. }
  51503. // Effect
  51504. var join = defines.join("\n");
  51505. if (this._cachedDefines !== join) {
  51506. this._cachedDefines = join;
  51507. var attributesNamesOrOptions;
  51508. var effectCreationOption;
  51509. if (this._isAnimationSheetEnabled) {
  51510. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  51511. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  51512. }
  51513. else {
  51514. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  51515. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  51516. }
  51517. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  51518. }
  51519. return this._effect;
  51520. };
  51521. /**
  51522. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51523. */
  51524. ParticleSystem.prototype.animate = function () {
  51525. if (!this._started)
  51526. return;
  51527. var effect = this._getEffect();
  51528. // Check
  51529. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  51530. return;
  51531. if (this._currentRenderId === this._scene.getRenderId()) {
  51532. return;
  51533. }
  51534. this._currentRenderId = this._scene.getRenderId();
  51535. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  51536. // determine the number of particles we need to create
  51537. var newParticles;
  51538. if (this.manualEmitCount > -1) {
  51539. newParticles = this.manualEmitCount;
  51540. this._newPartsExcess = 0;
  51541. this.manualEmitCount = 0;
  51542. }
  51543. else {
  51544. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  51545. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  51546. }
  51547. if (this._newPartsExcess > 1.0) {
  51548. newParticles += this._newPartsExcess >> 0;
  51549. this._newPartsExcess -= this._newPartsExcess >> 0;
  51550. }
  51551. this._alive = false;
  51552. if (!this._stopped) {
  51553. this._actualFrame += this._scaledUpdateSpeed;
  51554. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  51555. this.stop();
  51556. }
  51557. else {
  51558. newParticles = 0;
  51559. }
  51560. this._update(newParticles);
  51561. // Stopped?
  51562. if (this._stopped) {
  51563. if (!this._alive) {
  51564. this._started = false;
  51565. if (this.onAnimationEnd) {
  51566. this.onAnimationEnd();
  51567. }
  51568. if (this.disposeOnStop) {
  51569. this._scene._toBeDisposed.push(this);
  51570. }
  51571. }
  51572. }
  51573. // Animation sheet
  51574. if (this._isAnimationSheetEnabled) {
  51575. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  51576. }
  51577. else {
  51578. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  51579. }
  51580. // Update VBO
  51581. var offset = 0;
  51582. for (var index = 0; index < this._particles.length; index++) {
  51583. var particle = this._particles[index];
  51584. this._appendParticleVertexes(offset, particle);
  51585. offset += 4;
  51586. }
  51587. if (this._vertexBuffer) {
  51588. this._vertexBuffer.update(this._vertexData);
  51589. }
  51590. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  51591. this.stop();
  51592. }
  51593. };
  51594. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  51595. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  51596. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  51597. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  51598. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  51599. };
  51600. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  51601. this._appendParticleVertex(offset++, particle, 0, 0);
  51602. this._appendParticleVertex(offset++, particle, 1, 0);
  51603. this._appendParticleVertex(offset++, particle, 1, 1);
  51604. this._appendParticleVertex(offset++, particle, 0, 1);
  51605. };
  51606. /**
  51607. * Rebuilds the particle system.
  51608. */
  51609. ParticleSystem.prototype.rebuild = function () {
  51610. this._createIndexBuffer();
  51611. if (this._vertexBuffer) {
  51612. this._vertexBuffer._rebuild();
  51613. }
  51614. };
  51615. /**
  51616. * Is this system ready to be used/rendered
  51617. * @return true if the system is ready
  51618. */
  51619. ParticleSystem.prototype.isReady = function () {
  51620. var effect = this._getEffect();
  51621. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  51622. return false;
  51623. }
  51624. return true;
  51625. };
  51626. /**
  51627. * Renders the particle system in its current state.
  51628. * @returns the current number of particles
  51629. */
  51630. ParticleSystem.prototype.render = function () {
  51631. var effect = this._getEffect();
  51632. // Check
  51633. if (!this.isReady() || !this._particles.length) {
  51634. return 0;
  51635. }
  51636. var engine = this._scene.getEngine();
  51637. // Render
  51638. engine.enableEffect(effect);
  51639. engine.setState(false);
  51640. var viewMatrix = this._scene.getViewMatrix();
  51641. effect.setTexture("diffuseSampler", this.particleTexture);
  51642. effect.setMatrix("view", viewMatrix);
  51643. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51644. if (this._isAnimationSheetEnabled && this.particleTexture) {
  51645. var baseSize = this.particleTexture.getBaseSize();
  51646. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  51647. }
  51648. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  51649. if (this._scene.clipPlane) {
  51650. var clipPlane = this._scene.clipPlane;
  51651. var invView = viewMatrix.clone();
  51652. invView.invert();
  51653. effect.setMatrix("invView", invView);
  51654. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51655. }
  51656. // VBOs
  51657. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51658. // Draw order
  51659. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  51660. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51661. }
  51662. else {
  51663. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51664. }
  51665. if (this.forceDepthWrite) {
  51666. engine.setDepthWrite(true);
  51667. }
  51668. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  51669. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51670. return this._particles.length;
  51671. };
  51672. /**
  51673. * Disposes the particle system and free the associated resources
  51674. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  51675. */
  51676. ParticleSystem.prototype.dispose = function (disposeTexture) {
  51677. if (disposeTexture === void 0) { disposeTexture = true; }
  51678. if (this._vertexBuffer) {
  51679. this._vertexBuffer.dispose();
  51680. this._vertexBuffer = null;
  51681. }
  51682. if (this._indexBuffer) {
  51683. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51684. this._indexBuffer = null;
  51685. }
  51686. if (disposeTexture && this.particleTexture) {
  51687. this.particleTexture.dispose();
  51688. this.particleTexture = null;
  51689. }
  51690. this._removeFromRoot();
  51691. // Remove from scene
  51692. var index = this._scene.particleSystems.indexOf(this);
  51693. if (index > -1) {
  51694. this._scene.particleSystems.splice(index, 1);
  51695. }
  51696. // Callback
  51697. this.onDisposeObservable.notifyObservers(this);
  51698. this.onDisposeObservable.clear();
  51699. };
  51700. /**
  51701. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  51702. * @param radius The radius of the sphere to emit from
  51703. * @returns the emitter
  51704. */
  51705. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  51706. if (radius === void 0) { radius = 1; }
  51707. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  51708. this.particleEmitterType = particleEmitter;
  51709. return particleEmitter;
  51710. };
  51711. /**
  51712. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  51713. * @param radius The radius of the sphere to emit from
  51714. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  51715. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  51716. * @returns the emitter
  51717. */
  51718. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  51719. if (radius === void 0) { radius = 1; }
  51720. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  51721. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  51722. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  51723. this.particleEmitterType = particleEmitter;
  51724. return particleEmitter;
  51725. };
  51726. /**
  51727. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  51728. * @param radius The radius of the cone to emit from
  51729. * @param angle The base angle of the cone
  51730. * @returns the emitter
  51731. */
  51732. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  51733. if (radius === void 0) { radius = 1; }
  51734. if (angle === void 0) { angle = Math.PI / 4; }
  51735. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  51736. this.particleEmitterType = particleEmitter;
  51737. return particleEmitter;
  51738. };
  51739. // 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.
  51740. /**
  51741. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  51742. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  51743. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  51744. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51745. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51746. * @returns the emitter
  51747. */
  51748. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  51749. var particleEmitter = new BABYLON.BoxParticleEmitter();
  51750. this.direction1 = direction1;
  51751. this.direction2 = direction2;
  51752. this.minEmitBox = minEmitBox;
  51753. this.maxEmitBox = maxEmitBox;
  51754. this.particleEmitterType = particleEmitter;
  51755. return particleEmitter;
  51756. };
  51757. // Clone
  51758. /**
  51759. * Clones the particle system.
  51760. * @param name The name of the cloned object
  51761. * @param newEmitter The new emitter to use
  51762. * @returns the cloned particle system
  51763. */
  51764. ParticleSystem.prototype.clone = function (name, newEmitter) {
  51765. var custom = null;
  51766. var program = null;
  51767. if (this.customShader != null) {
  51768. program = this.customShader;
  51769. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51770. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51771. }
  51772. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  51773. result.customShader = program;
  51774. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  51775. if (newEmitter === undefined) {
  51776. newEmitter = this.emitter;
  51777. }
  51778. result.emitter = newEmitter;
  51779. if (this.particleTexture) {
  51780. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  51781. }
  51782. if (!this.preventAutoStart) {
  51783. result.start();
  51784. }
  51785. return result;
  51786. };
  51787. /**
  51788. * Serializes the particle system to a JSON object.
  51789. * @returns the JSON object
  51790. */
  51791. ParticleSystem.prototype.serialize = function () {
  51792. var serializationObject = {};
  51793. serializationObject.name = this.name;
  51794. serializationObject.id = this.id;
  51795. // Emitter
  51796. if (this.emitter.position) {
  51797. var emitterMesh = this.emitter;
  51798. serializationObject.emitterId = emitterMesh.id;
  51799. }
  51800. else {
  51801. var emitterPosition = this.emitter;
  51802. serializationObject.emitter = emitterPosition.asArray();
  51803. }
  51804. serializationObject.capacity = this.getCapacity();
  51805. if (this.particleTexture) {
  51806. serializationObject.textureName = this.particleTexture.name;
  51807. }
  51808. // Animations
  51809. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  51810. // Particle system
  51811. serializationObject.minAngularSpeed = this.minAngularSpeed;
  51812. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  51813. serializationObject.minSize = this.minSize;
  51814. serializationObject.maxSize = this.maxSize;
  51815. serializationObject.minEmitPower = this.minEmitPower;
  51816. serializationObject.maxEmitPower = this.maxEmitPower;
  51817. serializationObject.minLifeTime = this.minLifeTime;
  51818. serializationObject.maxLifeTime = this.maxLifeTime;
  51819. serializationObject.emitRate = this.emitRate;
  51820. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51821. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51822. serializationObject.gravity = this.gravity.asArray();
  51823. serializationObject.direction1 = this.direction1.asArray();
  51824. serializationObject.direction2 = this.direction2.asArray();
  51825. serializationObject.color1 = this.color1.asArray();
  51826. serializationObject.color2 = this.color2.asArray();
  51827. serializationObject.colorDead = this.colorDead.asArray();
  51828. serializationObject.updateSpeed = this.updateSpeed;
  51829. serializationObject.targetStopDuration = this.targetStopDuration;
  51830. serializationObject.textureMask = this.textureMask.asArray();
  51831. serializationObject.blendMode = this.blendMode;
  51832. serializationObject.customShader = this.customShader;
  51833. serializationObject.preventAutoStart = this.preventAutoStart;
  51834. serializationObject.startSpriteCellID = this.startSpriteCellID;
  51835. serializationObject.endSpriteCellID = this.endSpriteCellID;
  51836. serializationObject.spriteCellLoop = this.spriteCellLoop;
  51837. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  51838. serializationObject.spriteCellWidth = this.spriteCellWidth;
  51839. serializationObject.spriteCellHeight = this.spriteCellHeight;
  51840. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  51841. // Emitter
  51842. if (this.particleEmitterType) {
  51843. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  51844. }
  51845. return serializationObject;
  51846. };
  51847. /**
  51848. * Parses a JSON object to create a particle system.
  51849. * @param parsedParticleSystem The JSON object to parse
  51850. * @param scene The scene to create the particle system in
  51851. * @param rootUrl The root url to use to load external dependencies like texture
  51852. * @returns the Parsed particle system
  51853. */
  51854. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  51855. var name = parsedParticleSystem.name;
  51856. var custom = null;
  51857. var program = null;
  51858. if (parsedParticleSystem.customShader) {
  51859. program = parsedParticleSystem.customShader;
  51860. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51861. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51862. }
  51863. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  51864. particleSystem.customShader = program;
  51865. if (parsedParticleSystem.id) {
  51866. particleSystem.id = parsedParticleSystem.id;
  51867. }
  51868. // Auto start
  51869. if (parsedParticleSystem.preventAutoStart) {
  51870. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  51871. }
  51872. // Texture
  51873. if (parsedParticleSystem.textureName) {
  51874. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  51875. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  51876. }
  51877. // Emitter
  51878. if (parsedParticleSystem.emitterId) {
  51879. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  51880. }
  51881. else {
  51882. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  51883. }
  51884. // Animations
  51885. if (parsedParticleSystem.animations) {
  51886. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  51887. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  51888. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51889. }
  51890. }
  51891. if (parsedParticleSystem.autoAnimate) {
  51892. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  51893. }
  51894. // Particle system
  51895. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  51896. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  51897. particleSystem.minSize = parsedParticleSystem.minSize;
  51898. particleSystem.maxSize = parsedParticleSystem.maxSize;
  51899. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  51900. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  51901. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  51902. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  51903. particleSystem.emitRate = parsedParticleSystem.emitRate;
  51904. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  51905. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  51906. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  51907. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  51908. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  51909. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  51910. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  51911. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  51912. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  51913. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  51914. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  51915. particleSystem.blendMode = parsedParticleSystem.blendMode;
  51916. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  51917. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51918. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51919. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51920. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51921. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51922. if (!particleSystem.preventAutoStart) {
  51923. particleSystem.start();
  51924. }
  51925. return particleSystem;
  51926. };
  51927. /**
  51928. * Source color is added to the destination color without alpha affecting the result.
  51929. */
  51930. ParticleSystem.BLENDMODE_ONEONE = 0;
  51931. /**
  51932. * Blend current color and particle color using particle’s alpha.
  51933. */
  51934. ParticleSystem.BLENDMODE_STANDARD = 1;
  51935. return ParticleSystem;
  51936. }());
  51937. BABYLON.ParticleSystem = ParticleSystem;
  51938. })(BABYLON || (BABYLON = {}));
  51939. //# sourceMappingURL=babylon.particleSystem.js.map
  51940. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51941. var BABYLON;
  51942. (function (BABYLON) {
  51943. /**
  51944. * Particle emitter emitting particles from the inside of a box.
  51945. * It emits the particles randomly between 2 given directions.
  51946. */
  51947. var BoxParticleEmitter = /** @class */ (function () {
  51948. /**
  51949. * Creates a new instance of @see BoxParticleEmitter
  51950. */
  51951. function BoxParticleEmitter() {
  51952. /**
  51953. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51954. */
  51955. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51956. /**
  51957. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51958. */
  51959. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51960. /**
  51961. * 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.
  51962. */
  51963. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51964. /**
  51965. * 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.
  51966. */
  51967. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51968. }
  51969. /**
  51970. * Called by the particle System when the direction is computed for the created particle.
  51971. * @param emitPower is the power of the particle (speed)
  51972. * @param worldMatrix is the world matrix of the particle system
  51973. * @param directionToUpdate is the direction vector to update with the result
  51974. * @param particle is the particle we are computed the direction for
  51975. */
  51976. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51977. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51978. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51979. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51980. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51981. };
  51982. /**
  51983. * Called by the particle System when the position is computed for the created particle.
  51984. * @param worldMatrix is the world matrix of the particle system
  51985. * @param positionToUpdate is the position vector to update with the result
  51986. * @param particle is the particle we are computed the position for
  51987. */
  51988. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51989. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51990. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51991. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51992. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51993. };
  51994. /**
  51995. * Clones the current emitter and returns a copy of it
  51996. * @returns the new emitter
  51997. */
  51998. BoxParticleEmitter.prototype.clone = function () {
  51999. var newOne = new BoxParticleEmitter();
  52000. BABYLON.Tools.DeepCopy(this, newOne);
  52001. return newOne;
  52002. };
  52003. /**
  52004. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52005. * @param effect defines the update shader
  52006. */
  52007. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  52008. effect.setVector3("direction1", this.direction1);
  52009. effect.setVector3("direction2", this.direction2);
  52010. effect.setVector3("minEmitBox", this.minEmitBox);
  52011. effect.setVector3("maxEmitBox", this.maxEmitBox);
  52012. };
  52013. /**
  52014. * Returns a string to use to update the GPU particles update shader
  52015. * @returns a string containng the defines string
  52016. */
  52017. BoxParticleEmitter.prototype.getEffectDefines = function () {
  52018. return "#define BOXEMITTER";
  52019. };
  52020. /**
  52021. * Returns the string "BoxEmitter"
  52022. * @returns a string containing the class name
  52023. */
  52024. BoxParticleEmitter.prototype.getClassName = function () {
  52025. return "BoxEmitter";
  52026. };
  52027. /**
  52028. * Serializes the particle system to a JSON object.
  52029. * @returns the JSON object
  52030. */
  52031. BoxParticleEmitter.prototype.serialize = function () {
  52032. var serializationObject = {};
  52033. serializationObject.type = this.getClassName();
  52034. serializationObject.direction1 = this.direction1.asArray();
  52035. ;
  52036. serializationObject.direction2 = this.direction2.asArray();
  52037. ;
  52038. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52039. ;
  52040. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52041. ;
  52042. return serializationObject;
  52043. };
  52044. /**
  52045. * Parse properties from a JSON object
  52046. * @param serializationObject defines the JSON object
  52047. */
  52048. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  52049. this.direction1.copyFrom(serializationObject.direction1);
  52050. this.direction2.copyFrom(serializationObject.direction2);
  52051. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  52052. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  52053. };
  52054. return BoxParticleEmitter;
  52055. }());
  52056. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  52057. })(BABYLON || (BABYLON = {}));
  52058. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  52059. var BABYLON;
  52060. (function (BABYLON) {
  52061. /**
  52062. * Particle emitter emitting particles from the inside of a cone.
  52063. * It emits the particles alongside the cone volume from the base to the particle.
  52064. * The emission direction might be randomized.
  52065. */
  52066. var ConeParticleEmitter = /** @class */ (function () {
  52067. /**
  52068. * Creates a new instance of @see ConeParticleEmitter
  52069. * @param radius the radius of the emission cone (1 by default)
  52070. * @param angles the cone base angle (PI by default)
  52071. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52072. */
  52073. function ConeParticleEmitter(radius,
  52074. /**
  52075. * The radius of the emission cone.
  52076. */
  52077. angle,
  52078. /**
  52079. * The cone base angle.
  52080. */
  52081. directionRandomizer) {
  52082. if (radius === void 0) { radius = 1; }
  52083. if (angle === void 0) { angle = Math.PI; }
  52084. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52085. this.angle = angle;
  52086. this.directionRandomizer = directionRandomizer;
  52087. this.radius = radius;
  52088. }
  52089. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  52090. /**
  52091. * Gets the radius of the emission cone.
  52092. */
  52093. get: function () {
  52094. return this._radius;
  52095. },
  52096. /**
  52097. * Sets the radius of the emission cone.
  52098. */
  52099. set: function (value) {
  52100. this._radius = value;
  52101. if (this.angle !== 0) {
  52102. this._height = value / Math.tan(this.angle / 2);
  52103. }
  52104. else {
  52105. this._height = 1;
  52106. }
  52107. },
  52108. enumerable: true,
  52109. configurable: true
  52110. });
  52111. /**
  52112. * Called by the particle System when the direction is computed for the created particle.
  52113. * @param emitPower is the power of the particle (speed)
  52114. * @param worldMatrix is the world matrix of the particle system
  52115. * @param directionToUpdate is the direction vector to update with the result
  52116. * @param particle is the particle we are computed the direction for
  52117. */
  52118. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52119. if (this.angle === 0) {
  52120. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  52121. }
  52122. else {
  52123. // measure the direction Vector from the emitter to the particle.
  52124. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52125. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52126. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52127. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52128. direction.x += randX;
  52129. direction.y += randY;
  52130. direction.z += randZ;
  52131. direction.normalize();
  52132. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52133. }
  52134. };
  52135. /**
  52136. * Called by the particle System when the position is computed for the created particle.
  52137. * @param worldMatrix is the world matrix of the particle system
  52138. * @param positionToUpdate is the position vector to update with the result
  52139. * @param particle is the particle we are computed the position for
  52140. */
  52141. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52142. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  52143. var h = BABYLON.Scalar.RandomRange(0, 1);
  52144. // Better distribution in a cone at normal angles.
  52145. h = 1 - h * h;
  52146. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  52147. radius = radius * h / this._height;
  52148. var randX = radius * Math.sin(s);
  52149. var randZ = radius * Math.cos(s);
  52150. var randY = h * this._height;
  52151. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52152. };
  52153. /**
  52154. * Clones the current emitter and returns a copy of it
  52155. * @returns the new emitter
  52156. */
  52157. ConeParticleEmitter.prototype.clone = function () {
  52158. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  52159. BABYLON.Tools.DeepCopy(this, newOne);
  52160. return newOne;
  52161. };
  52162. /**
  52163. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52164. * @param effect defines the update shader
  52165. */
  52166. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  52167. effect.setFloat("radius", this.radius);
  52168. effect.setFloat("angle", this.angle);
  52169. effect.setFloat("height", this._height);
  52170. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52171. };
  52172. /**
  52173. * Returns a string to use to update the GPU particles update shader
  52174. * @returns a string containng the defines string
  52175. */
  52176. ConeParticleEmitter.prototype.getEffectDefines = function () {
  52177. return "#define CONEEMITTER";
  52178. };
  52179. /**
  52180. * Returns the string "BoxEmitter"
  52181. * @returns a string containing the class name
  52182. */
  52183. ConeParticleEmitter.prototype.getClassName = function () {
  52184. return "ConeEmitter";
  52185. };
  52186. /**
  52187. * Serializes the particle system to a JSON object.
  52188. * @returns the JSON object
  52189. */
  52190. ConeParticleEmitter.prototype.serialize = function () {
  52191. var serializationObject = {};
  52192. serializationObject.type = this.getClassName();
  52193. serializationObject.radius = this.radius;
  52194. serializationObject.angle = this.angle;
  52195. serializationObject.directionRandomizer = this.directionRandomizer;
  52196. return serializationObject;
  52197. };
  52198. /**
  52199. * Parse properties from a JSON object
  52200. * @param serializationObject defines the JSON object
  52201. */
  52202. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52203. this.radius = serializationObject.radius;
  52204. this.angle = serializationObject.angle;
  52205. this.directionRandomizer = serializationObject.directionRandomizer;
  52206. };
  52207. return ConeParticleEmitter;
  52208. }());
  52209. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52210. })(BABYLON || (BABYLON = {}));
  52211. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52212. var BABYLON;
  52213. (function (BABYLON) {
  52214. /**
  52215. * Particle emitter emitting particles from the inside of a sphere.
  52216. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52217. */
  52218. var SphereParticleEmitter = /** @class */ (function () {
  52219. /**
  52220. * Creates a new instance of @see SphereParticleEmitter
  52221. * @param radius the radius of the emission sphere (1 by default)
  52222. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52223. */
  52224. function SphereParticleEmitter(
  52225. /**
  52226. * The radius of the emission sphere.
  52227. */
  52228. radius,
  52229. /**
  52230. * How much to randomize the particle direction [0-1].
  52231. */
  52232. directionRandomizer) {
  52233. if (radius === void 0) { radius = 1; }
  52234. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52235. this.radius = radius;
  52236. this.directionRandomizer = directionRandomizer;
  52237. }
  52238. /**
  52239. * Called by the particle System when the direction is computed for the created particle.
  52240. * @param emitPower is the power of the particle (speed)
  52241. * @param worldMatrix is the world matrix of the particle system
  52242. * @param directionToUpdate is the direction vector to update with the result
  52243. * @param particle is the particle we are computed the direction for
  52244. */
  52245. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52246. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52247. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52248. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52249. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52250. direction.x += randX;
  52251. direction.y += randY;
  52252. direction.z += randZ;
  52253. direction.normalize();
  52254. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52255. };
  52256. /**
  52257. * Called by the particle System when the position is computed for the created particle.
  52258. * @param worldMatrix is the world matrix of the particle system
  52259. * @param positionToUpdate is the position vector to update with the result
  52260. * @param particle is the particle we are computed the position for
  52261. */
  52262. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52263. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  52264. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  52265. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  52266. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  52267. var randY = randRadius * Math.cos(theta);
  52268. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  52269. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52270. };
  52271. /**
  52272. * Clones the current emitter and returns a copy of it
  52273. * @returns the new emitter
  52274. */
  52275. SphereParticleEmitter.prototype.clone = function () {
  52276. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  52277. BABYLON.Tools.DeepCopy(this, newOne);
  52278. return newOne;
  52279. };
  52280. /**
  52281. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52282. * @param effect defines the update shader
  52283. */
  52284. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  52285. effect.setFloat("radius", this.radius);
  52286. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52287. };
  52288. /**
  52289. * Returns a string to use to update the GPU particles update shader
  52290. * @returns a string containng the defines string
  52291. */
  52292. SphereParticleEmitter.prototype.getEffectDefines = function () {
  52293. return "#define SPHEREEMITTER";
  52294. };
  52295. /**
  52296. * Returns the string "SphereParticleEmitter"
  52297. * @returns a string containing the class name
  52298. */
  52299. SphereParticleEmitter.prototype.getClassName = function () {
  52300. return "SphereParticleEmitter";
  52301. };
  52302. /**
  52303. * Serializes the particle system to a JSON object.
  52304. * @returns the JSON object
  52305. */
  52306. SphereParticleEmitter.prototype.serialize = function () {
  52307. var serializationObject = {};
  52308. serializationObject.type = this.getClassName();
  52309. serializationObject.radius = this.radius;
  52310. serializationObject.directionRandomizer = this.directionRandomizer;
  52311. return serializationObject;
  52312. };
  52313. /**
  52314. * Parse properties from a JSON object
  52315. * @param serializationObject defines the JSON object
  52316. */
  52317. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  52318. this.radius = serializationObject.radius;
  52319. this.directionRandomizer = serializationObject.directionRandomizer;
  52320. };
  52321. return SphereParticleEmitter;
  52322. }());
  52323. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  52324. /**
  52325. * Particle emitter emitting particles from the inside of a sphere.
  52326. * It emits the particles randomly between two vectors.
  52327. */
  52328. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  52329. __extends(SphereDirectedParticleEmitter, _super);
  52330. /**
  52331. * Creates a new instance of @see SphereDirectedParticleEmitter
  52332. * @param radius the radius of the emission sphere (1 by default)
  52333. * @param direction1 the min limit of the emission direction (up vector by default)
  52334. * @param direction2 the max limit of the emission direction (up vector by default)
  52335. */
  52336. function SphereDirectedParticleEmitter(radius,
  52337. /**
  52338. * The min limit of the emission direction.
  52339. */
  52340. direction1,
  52341. /**
  52342. * The max limit of the emission direction.
  52343. */
  52344. direction2) {
  52345. if (radius === void 0) { radius = 1; }
  52346. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  52347. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  52348. var _this = _super.call(this, radius) || this;
  52349. _this.direction1 = direction1;
  52350. _this.direction2 = direction2;
  52351. return _this;
  52352. }
  52353. /**
  52354. * Called by the particle System when the direction is computed for the created particle.
  52355. * @param emitPower is the power of the particle (speed)
  52356. * @param worldMatrix is the world matrix of the particle system
  52357. * @param directionToUpdate is the direction vector to update with the result
  52358. * @param particle is the particle we are computed the direction for
  52359. */
  52360. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52361. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52362. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52363. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52364. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52365. };
  52366. /**
  52367. * Clones the current emitter and returns a copy of it
  52368. * @returns the new emitter
  52369. */
  52370. SphereDirectedParticleEmitter.prototype.clone = function () {
  52371. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  52372. BABYLON.Tools.DeepCopy(this, newOne);
  52373. return newOne;
  52374. };
  52375. /**
  52376. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52377. * @param effect defines the update shader
  52378. */
  52379. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  52380. effect.setFloat("radius", this.radius);
  52381. effect.setVector3("direction1", this.direction1);
  52382. effect.setVector3("direction2", this.direction2);
  52383. };
  52384. /**
  52385. * Returns a string to use to update the GPU particles update shader
  52386. * @returns a string containng the defines string
  52387. */
  52388. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  52389. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  52390. };
  52391. /**
  52392. * Returns the string "SphereDirectedParticleEmitter"
  52393. * @returns a string containing the class name
  52394. */
  52395. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  52396. return "SphereDirectedParticleEmitter";
  52397. };
  52398. /**
  52399. * Serializes the particle system to a JSON object.
  52400. * @returns the JSON object
  52401. */
  52402. SphereDirectedParticleEmitter.prototype.serialize = function () {
  52403. var serializationObject = _super.prototype.serialize.call(this);
  52404. ;
  52405. serializationObject.direction1 = this.direction1.asArray();
  52406. ;
  52407. serializationObject.direction2 = this.direction2.asArray();
  52408. ;
  52409. return serializationObject;
  52410. };
  52411. /**
  52412. * Parse properties from a JSON object
  52413. * @param serializationObject defines the JSON object
  52414. */
  52415. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  52416. _super.prototype.parse.call(this, serializationObject);
  52417. this.direction1.copyFrom(serializationObject.direction1);
  52418. this.direction2.copyFrom(serializationObject.direction2);
  52419. };
  52420. return SphereDirectedParticleEmitter;
  52421. }(SphereParticleEmitter));
  52422. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  52423. })(BABYLON || (BABYLON = {}));
  52424. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  52425. var __assign = (this && this.__assign) || Object.assign || function(t) {
  52426. for (var s, i = 1, n = arguments.length; i < n; i++) {
  52427. s = arguments[i];
  52428. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  52429. t[p] = s[p];
  52430. }
  52431. return t;
  52432. };
  52433. var BABYLON;
  52434. (function (BABYLON) {
  52435. /**
  52436. * This represents a GPU particle system in Babylon
  52437. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  52438. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  52439. */
  52440. var GPUParticleSystem = /** @class */ (function () {
  52441. /**
  52442. * Instantiates a GPU particle system.
  52443. * 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.
  52444. * @param name The name of the particle system
  52445. * @param capacity The max number of particles alive at the same time
  52446. * @param scene The scene the particle system belongs to
  52447. */
  52448. function GPUParticleSystem(name, options, scene) {
  52449. /**
  52450. * The emitter represents the Mesh or position we are attaching the particle system to.
  52451. */
  52452. this.emitter = null;
  52453. /**
  52454. * The rendering group used by the Particle system to chose when to render.
  52455. */
  52456. this.renderingGroupId = 0;
  52457. /**
  52458. * The layer mask we are rendering the particles through.
  52459. */
  52460. this.layerMask = 0x0FFFFFFF;
  52461. this._targetIndex = 0;
  52462. this._currentRenderId = -1;
  52463. this._started = false;
  52464. this._stopped = false;
  52465. this._timeDelta = 0;
  52466. this._attributesStrideSize = 14;
  52467. this._actualFrame = 0;
  52468. /**
  52469. * List of animations used by the particle system.
  52470. */
  52471. this.animations = [];
  52472. /**
  52473. * An event triggered when the system is disposed.
  52474. */
  52475. this.onDisposeObservable = new BABYLON.Observable();
  52476. /**
  52477. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  52478. */
  52479. this.updateSpeed = 0.01;
  52480. /**
  52481. * The amount of time the particle system is running (depends of the overall update speed).
  52482. */
  52483. this.targetStopDuration = 0;
  52484. /**
  52485. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  52486. */
  52487. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  52488. /**
  52489. * Minimum life time of emitting particles.
  52490. */
  52491. this.minLifeTime = 1;
  52492. /**
  52493. * Maximum life time of emitting particles.
  52494. */
  52495. this.maxLifeTime = 1;
  52496. /**
  52497. * Minimum Size of emitting particles.
  52498. */
  52499. this.minSize = 1;
  52500. /**
  52501. * Maximum Size of emitting particles.
  52502. */
  52503. this.maxSize = 1;
  52504. /**
  52505. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52506. */
  52507. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52508. /**
  52509. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52510. */
  52511. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52512. /**
  52513. * Color the particle will have at the end of its lifetime.
  52514. */
  52515. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  52516. /**
  52517. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  52518. */
  52519. this.emitRate = 100;
  52520. /**
  52521. * You can use gravity if you want to give an orientation to your particles.
  52522. */
  52523. this.gravity = BABYLON.Vector3.Zero();
  52524. /**
  52525. * Minimum power of emitting particles.
  52526. */
  52527. this.minEmitPower = 1;
  52528. /**
  52529. * Maximum power of emitting particles.
  52530. */
  52531. this.maxEmitPower = 1;
  52532. /**
  52533. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  52534. * to override the particles.
  52535. */
  52536. this.forceDepthWrite = false;
  52537. this.id = name;
  52538. this.name = name;
  52539. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52540. this._engine = this._scene.getEngine();
  52541. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  52542. this._capacity = fullOptions.capacity;
  52543. this._activeCount = fullOptions.capacity;
  52544. this._currentActiveCount = 0;
  52545. this._scene.particleSystems.push(this);
  52546. this._updateEffectOptions = {
  52547. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  52548. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  52549. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  52550. uniformBuffersNames: [],
  52551. samplers: ["randomSampler"],
  52552. defines: "",
  52553. fallbacks: null,
  52554. onCompiled: null,
  52555. onError: null,
  52556. indexParameters: null,
  52557. maxSimultaneousLights: 0,
  52558. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  52559. };
  52560. // Random data
  52561. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  52562. var d = [];
  52563. for (var i = 0; i < maxTextureSize; ++i) {
  52564. d.push(Math.random());
  52565. d.push(Math.random());
  52566. d.push(Math.random());
  52567. d.push(Math.random());
  52568. }
  52569. 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);
  52570. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52571. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52572. this._randomTextureSize = maxTextureSize;
  52573. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  52574. }
  52575. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  52576. /**
  52577. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  52578. */
  52579. get: function () {
  52580. if (!BABYLON.Engine.LastCreatedEngine) {
  52581. return false;
  52582. }
  52583. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  52584. },
  52585. enumerable: true,
  52586. configurable: true
  52587. });
  52588. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  52589. /**
  52590. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52591. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52592. */
  52593. get: function () {
  52594. if (this.particleEmitterType.direction1) {
  52595. return this.particleEmitterType.direction1;
  52596. }
  52597. return BABYLON.Vector3.Zero();
  52598. },
  52599. set: function (value) {
  52600. if (this.particleEmitterType.direction1) {
  52601. this.particleEmitterType.direction1 = value;
  52602. }
  52603. },
  52604. enumerable: true,
  52605. configurable: true
  52606. });
  52607. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  52608. /**
  52609. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52610. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52611. */
  52612. get: function () {
  52613. if (this.particleEmitterType.direction2) {
  52614. return this.particleEmitterType.direction2;
  52615. }
  52616. return BABYLON.Vector3.Zero();
  52617. },
  52618. set: function (value) {
  52619. if (this.particleEmitterType.direction2) {
  52620. this.particleEmitterType.direction2 = value;
  52621. }
  52622. },
  52623. enumerable: true,
  52624. configurable: true
  52625. });
  52626. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  52627. /**
  52628. * 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.
  52629. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52630. */
  52631. get: function () {
  52632. if (this.particleEmitterType.minEmitBox) {
  52633. return this.particleEmitterType.minEmitBox;
  52634. }
  52635. return BABYLON.Vector3.Zero();
  52636. },
  52637. set: function (value) {
  52638. if (this.particleEmitterType.minEmitBox) {
  52639. this.particleEmitterType.minEmitBox = value;
  52640. }
  52641. },
  52642. enumerable: true,
  52643. configurable: true
  52644. });
  52645. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  52646. /**
  52647. * 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.
  52648. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52649. */
  52650. get: function () {
  52651. if (this.particleEmitterType.maxEmitBox) {
  52652. return this.particleEmitterType.maxEmitBox;
  52653. }
  52654. return BABYLON.Vector3.Zero();
  52655. },
  52656. set: function (value) {
  52657. if (this.particleEmitterType.maxEmitBox) {
  52658. this.particleEmitterType.maxEmitBox = value;
  52659. }
  52660. },
  52661. enumerable: true,
  52662. configurable: true
  52663. });
  52664. /**
  52665. * Gets the maximum number of particles active at the same time.
  52666. * @returns The max number of active particles.
  52667. */
  52668. GPUParticleSystem.prototype.getCapacity = function () {
  52669. return this._capacity;
  52670. };
  52671. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  52672. /**
  52673. * Gets or set the number of active particles
  52674. */
  52675. get: function () {
  52676. return this._activeCount;
  52677. },
  52678. set: function (value) {
  52679. this._activeCount = Math.min(value, this._capacity);
  52680. },
  52681. enumerable: true,
  52682. configurable: true
  52683. });
  52684. /**
  52685. * Is this system ready to be used/rendered
  52686. * @return true if the system is ready
  52687. */
  52688. GPUParticleSystem.prototype.isReady = function () {
  52689. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  52690. return false;
  52691. }
  52692. return true;
  52693. };
  52694. /**
  52695. * Gets Wether the system has been started.
  52696. * @returns True if it has been started, otherwise false.
  52697. */
  52698. GPUParticleSystem.prototype.isStarted = function () {
  52699. return this._started;
  52700. };
  52701. /**
  52702. * Starts the particle system and begins to emit.
  52703. */
  52704. GPUParticleSystem.prototype.start = function () {
  52705. this._started = true;
  52706. this._stopped = false;
  52707. };
  52708. /**
  52709. * Stops the particle system.
  52710. */
  52711. GPUParticleSystem.prototype.stop = function () {
  52712. this._stopped = true;
  52713. };
  52714. /**
  52715. * Remove all active particles
  52716. */
  52717. GPUParticleSystem.prototype.reset = function () {
  52718. this._releaseBuffers();
  52719. this._releaseVAOs();
  52720. this._currentActiveCount = 0;
  52721. this._targetIndex = 0;
  52722. };
  52723. /**
  52724. * Returns the string "GPUParticleSystem"
  52725. * @returns a string containing the class name
  52726. */
  52727. GPUParticleSystem.prototype.getClassName = function () {
  52728. return "GPUParticleSystem";
  52729. };
  52730. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  52731. var updateVertexBuffers = {};
  52732. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  52733. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  52734. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  52735. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  52736. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  52737. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  52738. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  52739. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  52740. this._engine.bindArrayBuffer(null);
  52741. return vao;
  52742. };
  52743. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  52744. var renderVertexBuffers = {};
  52745. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  52746. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  52747. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  52748. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  52749. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  52750. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  52751. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  52752. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  52753. this._engine.bindArrayBuffer(null);
  52754. return vao;
  52755. };
  52756. GPUParticleSystem.prototype._initialize = function (force) {
  52757. if (force === void 0) { force = false; }
  52758. if (this._buffer0 && !force) {
  52759. return;
  52760. }
  52761. var engine = this._scene.getEngine();
  52762. var data = new Array();
  52763. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  52764. // position
  52765. data.push(0.0);
  52766. data.push(0.0);
  52767. data.push(0.0);
  52768. // Age and life
  52769. data.push(0.0); // create the particle as a dead one to create a new one at start
  52770. data.push(0.0);
  52771. // Seed
  52772. data.push(Math.random());
  52773. // Size
  52774. data.push(0.0);
  52775. // color
  52776. data.push(0.0);
  52777. data.push(0.0);
  52778. data.push(0.0);
  52779. data.push(0.0);
  52780. // direction
  52781. data.push(0.0);
  52782. data.push(0.0);
  52783. data.push(0.0);
  52784. }
  52785. // Sprite data
  52786. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  52787. -0.5, 0.5, 0, 1,
  52788. -0.5, -0.5, 0, 0,
  52789. 0.5, -0.5, 1, 0]);
  52790. // Buffers
  52791. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  52792. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  52793. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  52794. // Update VAO
  52795. this._updateVAO = [];
  52796. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  52797. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  52798. // Render VAO
  52799. this._renderVAO = [];
  52800. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  52801. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  52802. // Links
  52803. this._sourceBuffer = this._buffer0;
  52804. this._targetBuffer = this._buffer1;
  52805. };
  52806. /** @ignore */
  52807. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  52808. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  52809. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  52810. return;
  52811. }
  52812. this._updateEffectOptions.defines = defines;
  52813. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  52814. };
  52815. /** @ignore */
  52816. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  52817. var defines = "";
  52818. if (this._scene.clipPlane) {
  52819. defines = "\n#define CLIPPLANE";
  52820. }
  52821. if (this._renderEffect && this._renderEffect.defines === defines) {
  52822. return;
  52823. }
  52824. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  52825. };
  52826. /**
  52827. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  52828. */
  52829. GPUParticleSystem.prototype.animate = function () {
  52830. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  52831. this._actualFrame += this._timeDelta;
  52832. if (!this._stopped) {
  52833. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  52834. this.stop();
  52835. }
  52836. }
  52837. };
  52838. /**
  52839. * Renders the particle system in its current state.
  52840. * @returns the current number of particles
  52841. */
  52842. GPUParticleSystem.prototype.render = function () {
  52843. if (!this._started) {
  52844. return 0;
  52845. }
  52846. this._recreateUpdateEffect();
  52847. this._recreateRenderEffect();
  52848. if (!this.isReady()) {
  52849. return 0;
  52850. }
  52851. if (this._currentRenderId === this._scene.getRenderId()) {
  52852. return 0;
  52853. }
  52854. this._currentRenderId = this._scene.getRenderId();
  52855. // Get everything ready to render
  52856. this._initialize();
  52857. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  52858. // Enable update effect
  52859. this._engine.enableEffect(this._updateEffect);
  52860. this._engine.setState(false);
  52861. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  52862. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  52863. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  52864. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  52865. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  52866. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  52867. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  52868. this._updateEffect.setDirectColor4("color1", this.color1);
  52869. this._updateEffect.setDirectColor4("color2", this.color2);
  52870. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  52871. this._updateEffect.setVector3("gravity", this.gravity);
  52872. if (this.particleEmitterType) {
  52873. this.particleEmitterType.applyToShader(this._updateEffect);
  52874. }
  52875. var emitterWM;
  52876. if (this.emitter.position) {
  52877. var emitterMesh = this.emitter;
  52878. emitterWM = emitterMesh.getWorldMatrix();
  52879. }
  52880. else {
  52881. var emitterPosition = this.emitter;
  52882. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  52883. }
  52884. this._updateEffect.setMatrix("emitterWM", emitterWM);
  52885. // Bind source VAO
  52886. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  52887. // Update
  52888. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  52889. this._engine.setRasterizerState(false);
  52890. this._engine.beginTransformFeedback();
  52891. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  52892. this._engine.endTransformFeedback();
  52893. this._engine.setRasterizerState(true);
  52894. this._engine.bindTransformFeedbackBuffer(null);
  52895. // Enable render effect
  52896. this._engine.enableEffect(this._renderEffect);
  52897. var viewMatrix = this._scene.getViewMatrix();
  52898. this._renderEffect.setMatrix("view", viewMatrix);
  52899. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  52900. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  52901. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  52902. if (this._scene.clipPlane) {
  52903. var clipPlane = this._scene.clipPlane;
  52904. var invView = viewMatrix.clone();
  52905. invView.invert();
  52906. this._renderEffect.setMatrix("invView", invView);
  52907. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52908. }
  52909. // Draw order
  52910. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  52911. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52912. }
  52913. else {
  52914. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52915. }
  52916. if (this.forceDepthWrite) {
  52917. this._engine.setDepthWrite(true);
  52918. }
  52919. // Bind source VAO
  52920. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  52921. // Render
  52922. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  52923. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52924. // Switch VAOs
  52925. this._targetIndex++;
  52926. if (this._targetIndex === 2) {
  52927. this._targetIndex = 0;
  52928. }
  52929. // Switch buffers
  52930. var tmpBuffer = this._sourceBuffer;
  52931. this._sourceBuffer = this._targetBuffer;
  52932. this._targetBuffer = tmpBuffer;
  52933. return this._currentActiveCount;
  52934. };
  52935. /**
  52936. * Rebuilds the particle system
  52937. */
  52938. GPUParticleSystem.prototype.rebuild = function () {
  52939. this._initialize(true);
  52940. };
  52941. GPUParticleSystem.prototype._releaseBuffers = function () {
  52942. if (this._buffer0) {
  52943. this._buffer0.dispose();
  52944. this._buffer0 = null;
  52945. }
  52946. if (this._buffer1) {
  52947. this._buffer1.dispose();
  52948. this._buffer1 = null;
  52949. }
  52950. if (this._spriteBuffer) {
  52951. this._spriteBuffer.dispose();
  52952. this._spriteBuffer = null;
  52953. }
  52954. };
  52955. GPUParticleSystem.prototype._releaseVAOs = function () {
  52956. if (!this._updateVAO) {
  52957. return;
  52958. }
  52959. for (var index = 0; index < this._updateVAO.length; index++) {
  52960. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  52961. }
  52962. this._updateVAO = [];
  52963. for (var index = 0; index < this._renderVAO.length; index++) {
  52964. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  52965. }
  52966. this._renderVAO = [];
  52967. };
  52968. /**
  52969. * Disposes the particle system and free the associated resources
  52970. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52971. */
  52972. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  52973. if (disposeTexture === void 0) { disposeTexture = true; }
  52974. var index = this._scene.particleSystems.indexOf(this);
  52975. if (index > -1) {
  52976. this._scene.particleSystems.splice(index, 1);
  52977. }
  52978. this._releaseBuffers();
  52979. this._releaseVAOs();
  52980. if (this._randomTexture) {
  52981. this._randomTexture.dispose();
  52982. this._randomTexture = null;
  52983. }
  52984. if (disposeTexture && this.particleTexture) {
  52985. this.particleTexture.dispose();
  52986. this.particleTexture = null;
  52987. }
  52988. // Callback
  52989. this.onDisposeObservable.notifyObservers(this);
  52990. this.onDisposeObservable.clear();
  52991. };
  52992. /**
  52993. * Clones the particle system.
  52994. * @param name The name of the cloned object
  52995. * @param newEmitter The new emitter to use
  52996. * @returns the cloned particle system
  52997. */
  52998. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  52999. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  53000. BABYLON.Tools.DeepCopy(this, result);
  53001. if (newEmitter === undefined) {
  53002. newEmitter = this.emitter;
  53003. }
  53004. result.emitter = newEmitter;
  53005. if (this.particleTexture) {
  53006. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  53007. }
  53008. return result;
  53009. };
  53010. /**
  53011. * Serializes the particle system to a JSON object.
  53012. * @returns the JSON object
  53013. */
  53014. GPUParticleSystem.prototype.serialize = function () {
  53015. var serializationObject = {};
  53016. serializationObject.name = this.name;
  53017. serializationObject.id = this.id;
  53018. // Emitter
  53019. if (this.emitter.position) {
  53020. var emitterMesh = this.emitter;
  53021. serializationObject.emitterId = emitterMesh.id;
  53022. }
  53023. else {
  53024. var emitterPosition = this.emitter;
  53025. serializationObject.emitter = emitterPosition.asArray();
  53026. }
  53027. serializationObject.capacity = this.getCapacity();
  53028. if (this.particleTexture) {
  53029. serializationObject.textureName = this.particleTexture.name;
  53030. }
  53031. // Animations
  53032. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  53033. // Particle system
  53034. serializationObject.activeParticleCount = this.activeParticleCount;
  53035. serializationObject.randomTextureSize = this._randomTextureSize;
  53036. serializationObject.minSize = this.minSize;
  53037. serializationObject.maxSize = this.maxSize;
  53038. serializationObject.minEmitPower = this.minEmitPower;
  53039. serializationObject.maxEmitPower = this.maxEmitPower;
  53040. serializationObject.minLifeTime = this.minLifeTime;
  53041. serializationObject.maxLifeTime = this.maxLifeTime;
  53042. serializationObject.emitRate = this.emitRate;
  53043. serializationObject.gravity = this.gravity.asArray();
  53044. serializationObject.color1 = this.color1.asArray();
  53045. serializationObject.color2 = this.color2.asArray();
  53046. serializationObject.colorDead = this.colorDead.asArray();
  53047. serializationObject.updateSpeed = this.updateSpeed;
  53048. serializationObject.targetStopDuration = this.targetStopDuration;
  53049. serializationObject.blendMode = this.blendMode;
  53050. // Emitter
  53051. if (this.particleEmitterType) {
  53052. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  53053. }
  53054. return serializationObject;
  53055. };
  53056. /**
  53057. * Parses a JSON object to create a GPU particle system.
  53058. * @param parsedParticleSystem The JSON object to parse
  53059. * @param scene The scene to create the particle system in
  53060. * @param rootUrl The root url to use to load external dependencies like texture
  53061. * @returns the parsed GPU particle system
  53062. */
  53063. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  53064. var name = parsedParticleSystem.name;
  53065. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  53066. if (parsedParticleSystem.id) {
  53067. particleSystem.id = parsedParticleSystem.id;
  53068. }
  53069. // Texture
  53070. if (parsedParticleSystem.textureName) {
  53071. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  53072. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  53073. }
  53074. // Emitter
  53075. if (parsedParticleSystem.emitterId) {
  53076. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  53077. }
  53078. else {
  53079. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  53080. }
  53081. // Animations
  53082. if (parsedParticleSystem.animations) {
  53083. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  53084. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  53085. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53086. }
  53087. }
  53088. // Particle system
  53089. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  53090. particleSystem.minSize = parsedParticleSystem.minSize;
  53091. particleSystem.maxSize = parsedParticleSystem.maxSize;
  53092. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  53093. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  53094. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  53095. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  53096. particleSystem.emitRate = parsedParticleSystem.emitRate;
  53097. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  53098. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  53099. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  53100. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  53101. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  53102. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  53103. particleSystem.blendMode = parsedParticleSystem.blendMode;
  53104. // Emitter
  53105. if (parsedParticleSystem.particleEmitterType) {
  53106. var emitterType = void 0;
  53107. switch (parsedParticleSystem.particleEmitterType.type) {
  53108. case "SphereEmitter":
  53109. emitterType = new BABYLON.SphereParticleEmitter();
  53110. break;
  53111. case "SphereDirectedParticleEmitter":
  53112. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  53113. break;
  53114. case "ConeEmitter":
  53115. emitterType = new BABYLON.ConeParticleEmitter();
  53116. break;
  53117. case "BoxEmitter":
  53118. default:
  53119. emitterType = new BABYLON.BoxParticleEmitter();
  53120. break;
  53121. }
  53122. emitterType.parse(parsedParticleSystem.particleEmitterType);
  53123. particleSystem.particleEmitterType = emitterType;
  53124. }
  53125. return particleSystem;
  53126. };
  53127. return GPUParticleSystem;
  53128. }());
  53129. BABYLON.GPUParticleSystem = GPUParticleSystem;
  53130. })(BABYLON || (BABYLON = {}));
  53131. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  53132. var BABYLON;
  53133. (function (BABYLON) {
  53134. /**
  53135. * Represents one particle of a solid particle system.
  53136. * @see SolidParticleSystem
  53137. */
  53138. var SolidParticle = /** @class */ (function () {
  53139. /**
  53140. * Creates a Solid Particle object.
  53141. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  53142. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  53143. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  53144. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  53145. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  53146. * @param shapeId (integer) is the model shape identifier in the SPS.
  53147. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  53148. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  53149. */
  53150. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  53151. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  53152. /**
  53153. * particle global index
  53154. */
  53155. this.idx = 0;
  53156. /**
  53157. * The color of the particle
  53158. */
  53159. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53160. /**
  53161. * The world space position of the particle.
  53162. */
  53163. this.position = BABYLON.Vector3.Zero();
  53164. /**
  53165. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  53166. */
  53167. this.rotation = BABYLON.Vector3.Zero();
  53168. /**
  53169. * The scaling of the particle.
  53170. */
  53171. this.scaling = BABYLON.Vector3.One();
  53172. /**
  53173. * The uvs of the particle.
  53174. */
  53175. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  53176. /**
  53177. * The current speed of the particle.
  53178. */
  53179. this.velocity = BABYLON.Vector3.Zero();
  53180. /**
  53181. * The pivot point in the particle local space.
  53182. */
  53183. this.pivot = BABYLON.Vector3.Zero();
  53184. /**
  53185. * Must the particle be translated from its pivot point in its local space ?
  53186. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  53187. * Default : false
  53188. */
  53189. this.translateFromPivot = false;
  53190. /**
  53191. * Is the particle active or not ?
  53192. */
  53193. this.alive = true;
  53194. /**
  53195. * Is the particle visible or not ?
  53196. */
  53197. this.isVisible = true;
  53198. /**
  53199. * Index of this particle in the global "positions" array (Internal use)
  53200. */
  53201. this._pos = 0;
  53202. /**
  53203. * Index of this particle in the global "indices" array (Internal use)
  53204. */
  53205. this._ind = 0;
  53206. /**
  53207. * ModelShape id of this particle
  53208. */
  53209. this.shapeId = 0;
  53210. /**
  53211. * Index of the particle in its shape id (Internal use)
  53212. */
  53213. this.idxInShape = 0;
  53214. /**
  53215. * Still set as invisible in order to skip useless computations (Internal use)
  53216. */
  53217. this._stillInvisible = false;
  53218. /**
  53219. * Last computed particle rotation matrix
  53220. */
  53221. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  53222. /**
  53223. * Parent particle Id, if any.
  53224. * Default null.
  53225. */
  53226. this.parentId = null;
  53227. /**
  53228. * Internal global position in the SPS.
  53229. */
  53230. this._globalPosition = BABYLON.Vector3.Zero();
  53231. this.idx = particleIndex;
  53232. this._pos = positionIndex;
  53233. this._ind = indiceIndex;
  53234. this._model = model;
  53235. this.shapeId = shapeId;
  53236. this.idxInShape = idxInShape;
  53237. this._sps = sps;
  53238. if (modelBoundingInfo) {
  53239. this._modelBoundingInfo = modelBoundingInfo;
  53240. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  53241. }
  53242. }
  53243. Object.defineProperty(SolidParticle.prototype, "scale", {
  53244. /**
  53245. * Legacy support, changed scale to scaling
  53246. */
  53247. get: function () {
  53248. return this.scaling;
  53249. },
  53250. /**
  53251. * Legacy support, changed scale to scaling
  53252. */
  53253. set: function (scale) {
  53254. this.scaling = scale;
  53255. },
  53256. enumerable: true,
  53257. configurable: true
  53258. });
  53259. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53260. /**
  53261. * Legacy support, changed quaternion to rotationQuaternion
  53262. */
  53263. get: function () {
  53264. return this.rotationQuaternion;
  53265. },
  53266. /**
  53267. * Legacy support, changed quaternion to rotationQuaternion
  53268. */
  53269. set: function (q) {
  53270. this.rotationQuaternion = q;
  53271. },
  53272. enumerable: true,
  53273. configurable: true
  53274. });
  53275. /**
  53276. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  53277. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  53278. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  53279. * @returns true if it intersects
  53280. */
  53281. SolidParticle.prototype.intersectsMesh = function (target) {
  53282. if (!this._boundingInfo || !target._boundingInfo) {
  53283. return false;
  53284. }
  53285. if (this._sps._bSphereOnly) {
  53286. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  53287. }
  53288. return this._boundingInfo.intersects(target._boundingInfo, false);
  53289. };
  53290. return SolidParticle;
  53291. }());
  53292. BABYLON.SolidParticle = SolidParticle;
  53293. /**
  53294. * Represents the shape of the model used by one particle of a solid particle system.
  53295. * SPS internal tool, don't use it manually.
  53296. * @see SolidParticleSystem
  53297. */
  53298. var ModelShape = /** @class */ (function () {
  53299. /**
  53300. * 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.
  53301. * SPS internal tool, don't use it manually.
  53302. * @ignore
  53303. */
  53304. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  53305. /**
  53306. * length of the shape in the model indices array (internal use)
  53307. */
  53308. this._indicesLength = 0;
  53309. this.shapeID = id;
  53310. this._shape = shape;
  53311. this._indicesLength = indicesLength;
  53312. this._shapeUV = shapeUV;
  53313. this._positionFunction = posFunction;
  53314. this._vertexFunction = vtxFunction;
  53315. }
  53316. return ModelShape;
  53317. }());
  53318. BABYLON.ModelShape = ModelShape;
  53319. /**
  53320. * Represents a Depth Sorted Particle in the solid particle system.
  53321. * @see SolidParticleSystem
  53322. */
  53323. var DepthSortedParticle = /** @class */ (function () {
  53324. function DepthSortedParticle() {
  53325. /**
  53326. * Index of the particle in the "indices" array
  53327. */
  53328. this.ind = 0;
  53329. /**
  53330. * Length of the particle shape in the "indices" array
  53331. */
  53332. this.indicesLength = 0;
  53333. /**
  53334. * Squared distance from the particle to the camera
  53335. */
  53336. this.sqDistance = 0.0;
  53337. }
  53338. return DepthSortedParticle;
  53339. }());
  53340. BABYLON.DepthSortedParticle = DepthSortedParticle;
  53341. })(BABYLON || (BABYLON = {}));
  53342. //# sourceMappingURL=babylon.solidParticle.js.map
  53343. var BABYLON;
  53344. (function (BABYLON) {
  53345. /**
  53346. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  53347. *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.
  53348. * The SPS is also a particle system. It provides some methods to manage the particles.
  53349. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  53350. *
  53351. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  53352. */
  53353. var SolidParticleSystem = /** @class */ (function () {
  53354. /**
  53355. * Creates a SPS (Solid Particle System) object.
  53356. * @param name (String) is the SPS name, this will be the underlying mesh name.
  53357. * @param scene (Scene) is the scene in which the SPS is added.
  53358. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  53359. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  53360. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  53361. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  53362. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  53363. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  53364. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  53365. */
  53366. function SolidParticleSystem(name, scene, options) {
  53367. /**
  53368. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  53369. * Example : var p = SPS.particles[i];
  53370. */
  53371. this.particles = new Array();
  53372. /**
  53373. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  53374. */
  53375. this.nbParticles = 0;
  53376. /**
  53377. * If the particles must ever face the camera (default false). Useful for planar particles.
  53378. */
  53379. this.billboard = false;
  53380. /**
  53381. * Recompute normals when adding a shape
  53382. */
  53383. this.recomputeNormals = true;
  53384. /**
  53385. * This a counter ofr your own usage. It's not set by any SPS functions.
  53386. */
  53387. this.counter = 0;
  53388. /**
  53389. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  53390. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  53391. */
  53392. this.vars = {};
  53393. /**
  53394. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  53395. */
  53396. this._bSphereOnly = false;
  53397. /**
  53398. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  53399. */
  53400. this._bSphereRadiusFactor = 1.0;
  53401. this._positions = new Array();
  53402. this._indices = new Array();
  53403. this._normals = new Array();
  53404. this._colors = new Array();
  53405. this._uvs = new Array();
  53406. this._index = 0; // indices index
  53407. this._updatable = true;
  53408. this._pickable = false;
  53409. this._isVisibilityBoxLocked = false;
  53410. this._alwaysVisible = false;
  53411. this._depthSort = false;
  53412. this._shapeCounter = 0;
  53413. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  53414. this._color = new BABYLON.Color4(0, 0, 0, 0);
  53415. this._computeParticleColor = true;
  53416. this._computeParticleTexture = true;
  53417. this._computeParticleRotation = true;
  53418. this._computeParticleVertex = false;
  53419. this._computeBoundingBox = false;
  53420. this._depthSortParticles = true;
  53421. this._cam_axisZ = BABYLON.Vector3.Zero();
  53422. this._cam_axisY = BABYLON.Vector3.Zero();
  53423. this._cam_axisX = BABYLON.Vector3.Zero();
  53424. this._axisZ = BABYLON.Axis.Z;
  53425. this._camDir = BABYLON.Vector3.Zero();
  53426. this._camInvertedPosition = BABYLON.Vector3.Zero();
  53427. this._rotMatrix = new BABYLON.Matrix();
  53428. this._invertMatrix = new BABYLON.Matrix();
  53429. this._rotated = BABYLON.Vector3.Zero();
  53430. this._quaternion = new BABYLON.Quaternion();
  53431. this._vertex = BABYLON.Vector3.Zero();
  53432. this._normal = BABYLON.Vector3.Zero();
  53433. this._yaw = 0.0;
  53434. this._pitch = 0.0;
  53435. this._roll = 0.0;
  53436. this._halfroll = 0.0;
  53437. this._halfpitch = 0.0;
  53438. this._halfyaw = 0.0;
  53439. this._sinRoll = 0.0;
  53440. this._cosRoll = 0.0;
  53441. this._sinPitch = 0.0;
  53442. this._cosPitch = 0.0;
  53443. this._sinYaw = 0.0;
  53444. this._cosYaw = 0.0;
  53445. this._mustUnrotateFixedNormals = false;
  53446. this._minimum = BABYLON.Vector3.Zero();
  53447. this._maximum = BABYLON.Vector3.Zero();
  53448. this._minBbox = BABYLON.Vector3.Zero();
  53449. this._maxBbox = BABYLON.Vector3.Zero();
  53450. this._particlesIntersect = false;
  53451. this._depthSortFunction = function (p1, p2) {
  53452. return (p2.sqDistance - p1.sqDistance);
  53453. };
  53454. this._needs32Bits = false;
  53455. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  53456. this._scaledPivot = BABYLON.Vector3.Zero();
  53457. this._particleHasParent = false;
  53458. this.name = name;
  53459. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53460. this._camera = scene.activeCamera;
  53461. this._pickable = options ? options.isPickable : false;
  53462. this._depthSort = options ? options.enableDepthSort : false;
  53463. this._particlesIntersect = options ? options.particleIntersection : false;
  53464. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  53465. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  53466. if (options && options.updatable) {
  53467. this._updatable = options.updatable;
  53468. }
  53469. else {
  53470. this._updatable = true;
  53471. }
  53472. if (this._pickable) {
  53473. this.pickedParticles = [];
  53474. }
  53475. if (this._depthSort) {
  53476. this.depthSortedParticles = [];
  53477. }
  53478. }
  53479. /**
  53480. * Builds the SPS underlying mesh. Returns a standard Mesh.
  53481. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  53482. * @returns the created mesh
  53483. */
  53484. SolidParticleSystem.prototype.buildMesh = function () {
  53485. if (this.nbParticles === 0) {
  53486. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  53487. this.addShape(triangle, 1);
  53488. triangle.dispose();
  53489. }
  53490. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  53491. this._positions32 = new Float32Array(this._positions);
  53492. this._uvs32 = new Float32Array(this._uvs);
  53493. this._colors32 = new Float32Array(this._colors);
  53494. if (this.recomputeNormals) {
  53495. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  53496. }
  53497. this._normals32 = new Float32Array(this._normals);
  53498. this._fixedNormal32 = new Float32Array(this._normals);
  53499. if (this._mustUnrotateFixedNormals) {
  53500. this._unrotateFixedNormals();
  53501. }
  53502. var vertexData = new BABYLON.VertexData();
  53503. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  53504. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  53505. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  53506. if (this._uvs32) {
  53507. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  53508. ;
  53509. }
  53510. if (this._colors32) {
  53511. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  53512. }
  53513. var mesh = new BABYLON.Mesh(this.name, this._scene);
  53514. vertexData.applyToMesh(mesh, this._updatable);
  53515. this.mesh = mesh;
  53516. this.mesh.isPickable = this._pickable;
  53517. // free memory
  53518. if (!this._depthSort) {
  53519. this._indices = null;
  53520. }
  53521. this._positions = null;
  53522. this._normals = null;
  53523. this._uvs = null;
  53524. this._colors = null;
  53525. if (!this._updatable) {
  53526. this.particles.length = 0;
  53527. }
  53528. return mesh;
  53529. };
  53530. /**
  53531. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  53532. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  53533. * Thus the particles generated from `digest()` have their property `position` set yet.
  53534. * @param mesh ( Mesh ) is the mesh to be digested
  53535. * @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
  53536. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  53537. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  53538. * @returns the current SPS
  53539. */
  53540. SolidParticleSystem.prototype.digest = function (mesh, options) {
  53541. var size = (options && options.facetNb) || 1;
  53542. var number = (options && options.number) || 0;
  53543. var delta = (options && options.delta) || 0;
  53544. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53545. var meshInd = mesh.getIndices();
  53546. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53547. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53548. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53549. var f = 0; // facet counter
  53550. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  53551. // compute size from number
  53552. if (number) {
  53553. number = (number > totalFacets) ? totalFacets : number;
  53554. size = Math.round(totalFacets / number);
  53555. delta = 0;
  53556. }
  53557. else {
  53558. size = (size > totalFacets) ? totalFacets : size;
  53559. }
  53560. var facetPos = []; // submesh positions
  53561. var facetInd = []; // submesh indices
  53562. var facetUV = []; // submesh UV
  53563. var facetCol = []; // submesh colors
  53564. var barycenter = BABYLON.Vector3.Zero();
  53565. var sizeO = size;
  53566. while (f < totalFacets) {
  53567. size = sizeO + Math.floor((1 + delta) * Math.random());
  53568. if (f > totalFacets - size) {
  53569. size = totalFacets - f;
  53570. }
  53571. // reset temp arrays
  53572. facetPos.length = 0;
  53573. facetInd.length = 0;
  53574. facetUV.length = 0;
  53575. facetCol.length = 0;
  53576. // iterate over "size" facets
  53577. var fi = 0;
  53578. for (var j = f * 3; j < (f + size) * 3; j++) {
  53579. facetInd.push(fi);
  53580. var i = meshInd[j];
  53581. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  53582. if (meshUV) {
  53583. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  53584. }
  53585. if (meshCol) {
  53586. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  53587. }
  53588. fi++;
  53589. }
  53590. // create a model shape for each single particle
  53591. var idx = this.nbParticles;
  53592. var shape = this._posToShape(facetPos);
  53593. var shapeUV = this._uvsToShapeUV(facetUV);
  53594. // compute the barycenter of the shape
  53595. var v;
  53596. for (v = 0; v < shape.length; v++) {
  53597. barycenter.addInPlace(shape[v]);
  53598. }
  53599. barycenter.scaleInPlace(1 / shape.length);
  53600. // shift the shape from its barycenter to the origin
  53601. for (v = 0; v < shape.length; v++) {
  53602. shape[v].subtractInPlace(barycenter);
  53603. }
  53604. var bInfo;
  53605. if (this._particlesIntersect) {
  53606. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  53607. }
  53608. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  53609. // add the particle in the SPS
  53610. var currentPos = this._positions.length;
  53611. var currentInd = this._indices.length;
  53612. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  53613. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  53614. // initialize the particle position
  53615. this.particles[this.nbParticles].position.addInPlace(barycenter);
  53616. this._index += shape.length;
  53617. idx++;
  53618. this.nbParticles++;
  53619. this._shapeCounter++;
  53620. f += size;
  53621. }
  53622. return this;
  53623. };
  53624. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  53625. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  53626. var index = 0;
  53627. var idx = 0;
  53628. for (var p = 0; p < this.particles.length; p++) {
  53629. this._particle = this.particles[p];
  53630. this._shape = this._particle._model._shape;
  53631. if (this._particle.rotationQuaternion) {
  53632. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53633. }
  53634. else {
  53635. this._yaw = this._particle.rotation.y;
  53636. this._pitch = this._particle.rotation.x;
  53637. this._roll = this._particle.rotation.z;
  53638. this._quaternionRotationYPR();
  53639. }
  53640. this._quaternionToRotationMatrix();
  53641. this._rotMatrix.invertToRef(this._invertMatrix);
  53642. for (var pt = 0; pt < this._shape.length; pt++) {
  53643. idx = index + pt * 3;
  53644. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  53645. this._fixedNormal32[idx] = this._normal.x;
  53646. this._fixedNormal32[idx + 1] = this._normal.y;
  53647. this._fixedNormal32[idx + 2] = this._normal.z;
  53648. }
  53649. index = idx + 3;
  53650. }
  53651. };
  53652. //reset copy
  53653. SolidParticleSystem.prototype._resetCopy = function () {
  53654. this._copy.position.x = 0;
  53655. this._copy.position.y = 0;
  53656. this._copy.position.z = 0;
  53657. this._copy.rotation.x = 0;
  53658. this._copy.rotation.y = 0;
  53659. this._copy.rotation.z = 0;
  53660. this._copy.rotationQuaternion = null;
  53661. this._copy.scaling.x = 1.0;
  53662. this._copy.scaling.y = 1.0;
  53663. this._copy.scaling.z = 1.0;
  53664. this._copy.uvs.x = 0;
  53665. this._copy.uvs.y = 0;
  53666. this._copy.uvs.z = 1.0;
  53667. this._copy.uvs.w = 1.0;
  53668. this._copy.color = null;
  53669. this._copy.translateFromPivot = false;
  53670. };
  53671. // _meshBuilder : inserts the shape model in the global SPS mesh
  53672. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  53673. var i;
  53674. var u = 0;
  53675. var c = 0;
  53676. var n = 0;
  53677. this._resetCopy();
  53678. if (options && options.positionFunction) {
  53679. options.positionFunction(this._copy, idx, idxInShape);
  53680. this._mustUnrotateFixedNormals = true;
  53681. }
  53682. if (this._copy.rotationQuaternion) {
  53683. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53684. }
  53685. else {
  53686. this._yaw = this._copy.rotation.y;
  53687. this._pitch = this._copy.rotation.x;
  53688. this._roll = this._copy.rotation.z;
  53689. this._quaternionRotationYPR();
  53690. }
  53691. this._quaternionToRotationMatrix();
  53692. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  53693. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  53694. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  53695. if (this._copy.translateFromPivot) {
  53696. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53697. }
  53698. else {
  53699. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53700. }
  53701. for (i = 0; i < shape.length; i++) {
  53702. this._vertex.x = shape[i].x;
  53703. this._vertex.y = shape[i].y;
  53704. this._vertex.z = shape[i].z;
  53705. if (options && options.vertexFunction) {
  53706. options.vertexFunction(this._copy, this._vertex, i);
  53707. }
  53708. this._vertex.x *= this._copy.scaling.x;
  53709. this._vertex.y *= this._copy.scaling.y;
  53710. this._vertex.z *= this._copy.scaling.z;
  53711. this._vertex.x -= this._scaledPivot.x;
  53712. this._vertex.y -= this._scaledPivot.y;
  53713. this._vertex.z -= this._scaledPivot.z;
  53714. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53715. this._rotated.addInPlace(this._pivotBackTranslation);
  53716. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  53717. if (meshUV) {
  53718. 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);
  53719. u += 2;
  53720. }
  53721. if (this._copy.color) {
  53722. this._color = this._copy.color;
  53723. }
  53724. else if (meshCol && meshCol[c] !== undefined) {
  53725. this._color.r = meshCol[c];
  53726. this._color.g = meshCol[c + 1];
  53727. this._color.b = meshCol[c + 2];
  53728. this._color.a = meshCol[c + 3];
  53729. }
  53730. else {
  53731. this._color.r = 1.0;
  53732. this._color.g = 1.0;
  53733. this._color.b = 1.0;
  53734. this._color.a = 1.0;
  53735. }
  53736. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  53737. c += 4;
  53738. if (!this.recomputeNormals && meshNor) {
  53739. this._normal.x = meshNor[n];
  53740. this._normal.y = meshNor[n + 1];
  53741. this._normal.z = meshNor[n + 2];
  53742. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  53743. normals.push(this._normal.x, this._normal.y, this._normal.z);
  53744. n += 3;
  53745. }
  53746. }
  53747. for (i = 0; i < meshInd.length; i++) {
  53748. var current_ind = p + meshInd[i];
  53749. indices.push(current_ind);
  53750. if (current_ind > 65535) {
  53751. this._needs32Bits = true;
  53752. }
  53753. }
  53754. if (this._pickable) {
  53755. var nbfaces = meshInd.length / 3;
  53756. for (i = 0; i < nbfaces; i++) {
  53757. this.pickedParticles.push({ idx: idx, faceId: i });
  53758. }
  53759. }
  53760. if (this._depthSort) {
  53761. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  53762. }
  53763. return this._copy;
  53764. };
  53765. // returns a shape array from positions array
  53766. SolidParticleSystem.prototype._posToShape = function (positions) {
  53767. var shape = [];
  53768. for (var i = 0; i < positions.length; i += 3) {
  53769. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  53770. }
  53771. return shape;
  53772. };
  53773. // returns a shapeUV array from a Vector4 uvs
  53774. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  53775. var shapeUV = [];
  53776. if (uvs) {
  53777. for (var i = 0; i < uvs.length; i++)
  53778. shapeUV.push(uvs[i]);
  53779. }
  53780. return shapeUV;
  53781. };
  53782. // adds a new particle object in the particles array
  53783. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  53784. if (bInfo === void 0) { bInfo = null; }
  53785. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  53786. this.particles.push(sp);
  53787. return sp;
  53788. };
  53789. /**
  53790. * Adds some particles to the SPS from the model shape. Returns the shape id.
  53791. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  53792. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  53793. * @param nb (positive integer) the number of particles to be created from this model
  53794. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  53795. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  53796. * @returns the number of shapes in the system
  53797. */
  53798. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  53799. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53800. var meshInd = mesh.getIndices();
  53801. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53802. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53803. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53804. var bbInfo;
  53805. if (this._particlesIntersect) {
  53806. bbInfo = mesh.getBoundingInfo();
  53807. }
  53808. var shape = this._posToShape(meshPos);
  53809. var shapeUV = this._uvsToShapeUV(meshUV);
  53810. var posfunc = options ? options.positionFunction : null;
  53811. var vtxfunc = options ? options.vertexFunction : null;
  53812. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  53813. // particles
  53814. var sp;
  53815. var currentCopy;
  53816. var idx = this.nbParticles;
  53817. for (var i = 0; i < nb; i++) {
  53818. var currentPos = this._positions.length;
  53819. var currentInd = this._indices.length;
  53820. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  53821. if (this._updatable) {
  53822. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  53823. sp.position.copyFrom(currentCopy.position);
  53824. sp.rotation.copyFrom(currentCopy.rotation);
  53825. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  53826. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  53827. }
  53828. if (currentCopy.color && sp.color) {
  53829. sp.color.copyFrom(currentCopy.color);
  53830. }
  53831. sp.scaling.copyFrom(currentCopy.scaling);
  53832. sp.uvs.copyFrom(currentCopy.uvs);
  53833. }
  53834. this._index += shape.length;
  53835. idx++;
  53836. }
  53837. this.nbParticles += nb;
  53838. this._shapeCounter++;
  53839. return this._shapeCounter - 1;
  53840. };
  53841. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  53842. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  53843. this._resetCopy();
  53844. if (particle._model._positionFunction) {
  53845. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  53846. }
  53847. if (this._copy.rotationQuaternion) {
  53848. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53849. }
  53850. else {
  53851. this._yaw = this._copy.rotation.y;
  53852. this._pitch = this._copy.rotation.x;
  53853. this._roll = this._copy.rotation.z;
  53854. this._quaternionRotationYPR();
  53855. }
  53856. this._quaternionToRotationMatrix();
  53857. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53858. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53859. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53860. if (this._copy.translateFromPivot) {
  53861. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53862. }
  53863. else {
  53864. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53865. }
  53866. this._shape = particle._model._shape;
  53867. for (var pt = 0; pt < this._shape.length; pt++) {
  53868. this._vertex.x = this._shape[pt].x;
  53869. this._vertex.y = this._shape[pt].y;
  53870. this._vertex.z = this._shape[pt].z;
  53871. if (particle._model._vertexFunction) {
  53872. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  53873. }
  53874. this._vertex.x *= this._copy.scaling.x;
  53875. this._vertex.y *= this._copy.scaling.y;
  53876. this._vertex.z *= this._copy.scaling.z;
  53877. this._vertex.x -= this._scaledPivot.x;
  53878. this._vertex.y -= this._scaledPivot.y;
  53879. this._vertex.z -= this._scaledPivot.z;
  53880. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53881. this._rotated.addInPlace(this._pivotBackTranslation);
  53882. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  53883. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  53884. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  53885. }
  53886. particle.position.x = 0.0;
  53887. particle.position.y = 0.0;
  53888. particle.position.z = 0.0;
  53889. particle.rotation.x = 0.0;
  53890. particle.rotation.y = 0.0;
  53891. particle.rotation.z = 0.0;
  53892. particle.rotationQuaternion = null;
  53893. particle.scaling.x = 1.0;
  53894. particle.scaling.y = 1.0;
  53895. particle.scaling.z = 1.0;
  53896. particle.uvs.x = 0.0;
  53897. particle.uvs.y = 0.0;
  53898. particle.uvs.z = 1.0;
  53899. particle.uvs.w = 1.0;
  53900. particle.pivot.x = 0.0;
  53901. particle.pivot.y = 0.0;
  53902. particle.pivot.z = 0.0;
  53903. particle.translateFromPivot = false;
  53904. particle.parentId = null;
  53905. };
  53906. /**
  53907. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  53908. * @returns the SPS.
  53909. */
  53910. SolidParticleSystem.prototype.rebuildMesh = function () {
  53911. for (var p = 0; p < this.particles.length; p++) {
  53912. this._rebuildParticle(this.particles[p]);
  53913. }
  53914. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53915. return this;
  53916. };
  53917. /**
  53918. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  53919. * This method calls `updateParticle()` for each particle of the SPS.
  53920. * For an animated SPS, it is usually called within the render loop.
  53921. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  53922. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  53923. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  53924. * @returns the SPS.
  53925. */
  53926. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  53927. if (start === void 0) { start = 0; }
  53928. if (end === void 0) { end = this.nbParticles - 1; }
  53929. if (update === void 0) { update = true; }
  53930. if (!this._updatable) {
  53931. return this;
  53932. }
  53933. // custom beforeUpdate
  53934. this.beforeUpdateParticles(start, end, update);
  53935. this._cam_axisX.x = 1.0;
  53936. this._cam_axisX.y = 0.0;
  53937. this._cam_axisX.z = 0.0;
  53938. this._cam_axisY.x = 0.0;
  53939. this._cam_axisY.y = 1.0;
  53940. this._cam_axisY.z = 0.0;
  53941. this._cam_axisZ.x = 0.0;
  53942. this._cam_axisZ.y = 0.0;
  53943. this._cam_axisZ.z = 1.0;
  53944. // cases when the World Matrix is to be computed first
  53945. if (this.billboard || this._depthSort) {
  53946. this.mesh.computeWorldMatrix(true);
  53947. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  53948. }
  53949. // if the particles will always face the camera
  53950. if (this.billboard) {
  53951. // compute the camera position and un-rotate it by the current mesh rotation
  53952. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  53953. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  53954. this._cam_axisZ.normalize();
  53955. // same for camera up vector extracted from the cam view matrix
  53956. var view = this._camera.getViewMatrix(true);
  53957. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  53958. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  53959. this._cam_axisY.normalize();
  53960. this._cam_axisX.normalize();
  53961. }
  53962. // if depthSort, compute the camera global position in the mesh local system
  53963. if (this._depthSort) {
  53964. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  53965. }
  53966. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  53967. var idx = 0; // current position index in the global array positions32
  53968. var index = 0; // position start index in the global array positions32 of the current particle
  53969. var colidx = 0; // current color index in the global array colors32
  53970. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  53971. var uvidx = 0; // current uv index in the global array uvs32
  53972. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  53973. var pt = 0; // current index in the particle model shape
  53974. if (this.mesh.isFacetDataEnabled) {
  53975. this._computeBoundingBox = true;
  53976. }
  53977. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  53978. if (this._computeBoundingBox) {
  53979. if (start == 0 && end == this.nbParticles - 1) {
  53980. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  53981. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  53982. }
  53983. else {
  53984. if (this.mesh._boundingInfo) {
  53985. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  53986. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  53987. }
  53988. }
  53989. }
  53990. // particle loop
  53991. index = this.particles[start]._pos;
  53992. var vpos = (index / 3) | 0;
  53993. colorIndex = vpos * 4;
  53994. uvIndex = vpos * 2;
  53995. for (var p = start; p <= end; p++) {
  53996. this._particle = this.particles[p];
  53997. this._shape = this._particle._model._shape;
  53998. this._shapeUV = this._particle._model._shapeUV;
  53999. // call to custom user function to update the particle properties
  54000. this.updateParticle(this._particle);
  54001. // camera-particle distance for depth sorting
  54002. if (this._depthSort && this._depthSortParticles) {
  54003. var dsp = this.depthSortedParticles[p];
  54004. dsp.ind = this._particle._ind;
  54005. dsp.indicesLength = this._particle._model._indicesLength;
  54006. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  54007. }
  54008. // skip the computations for inactive or already invisible particles
  54009. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  54010. // increment indexes for the next particle
  54011. pt = this._shape.length;
  54012. index += pt * 3;
  54013. colorIndex += pt * 4;
  54014. uvIndex += pt * 2;
  54015. continue;
  54016. }
  54017. if (this._particle.isVisible) {
  54018. this._particle._stillInvisible = false; // un-mark permanent invisibility
  54019. this._particleHasParent = (this._particle.parentId !== null);
  54020. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54021. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54022. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54023. // particle rotation matrix
  54024. if (this.billboard) {
  54025. this._particle.rotation.x = 0.0;
  54026. this._particle.rotation.y = 0.0;
  54027. }
  54028. if (this._computeParticleRotation || this.billboard) {
  54029. if (this._particle.rotationQuaternion) {
  54030. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54031. }
  54032. else {
  54033. this._yaw = this._particle.rotation.y;
  54034. this._pitch = this._particle.rotation.x;
  54035. this._roll = this._particle.rotation.z;
  54036. this._quaternionRotationYPR();
  54037. }
  54038. this._quaternionToRotationMatrix();
  54039. }
  54040. if (this._particleHasParent) {
  54041. this._parent = this.particles[this._particle.parentId];
  54042. 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];
  54043. 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];
  54044. 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];
  54045. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  54046. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  54047. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  54048. if (this._computeParticleRotation || this.billboard) {
  54049. 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];
  54050. 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];
  54051. 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];
  54052. 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];
  54053. 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];
  54054. 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];
  54055. 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];
  54056. 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];
  54057. 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];
  54058. }
  54059. }
  54060. else {
  54061. this._particle._globalPosition.x = this._particle.position.x;
  54062. this._particle._globalPosition.y = this._particle.position.y;
  54063. this._particle._globalPosition.z = this._particle.position.z;
  54064. if (this._computeParticleRotation || this.billboard) {
  54065. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  54066. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  54067. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  54068. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  54069. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  54070. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  54071. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  54072. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  54073. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  54074. }
  54075. }
  54076. if (this._particle.translateFromPivot) {
  54077. this._pivotBackTranslation.x = 0.0;
  54078. this._pivotBackTranslation.y = 0.0;
  54079. this._pivotBackTranslation.z = 0.0;
  54080. }
  54081. else {
  54082. this._pivotBackTranslation.x = this._scaledPivot.x;
  54083. this._pivotBackTranslation.y = this._scaledPivot.y;
  54084. this._pivotBackTranslation.z = this._scaledPivot.z;
  54085. }
  54086. // particle vertex loop
  54087. for (pt = 0; pt < this._shape.length; pt++) {
  54088. idx = index + pt * 3;
  54089. colidx = colorIndex + pt * 4;
  54090. uvidx = uvIndex + pt * 2;
  54091. this._vertex.x = this._shape[pt].x;
  54092. this._vertex.y = this._shape[pt].y;
  54093. this._vertex.z = this._shape[pt].z;
  54094. if (this._computeParticleVertex) {
  54095. this.updateParticleVertex(this._particle, this._vertex, pt);
  54096. }
  54097. // positions
  54098. this._vertex.x *= this._particle.scaling.x;
  54099. this._vertex.y *= this._particle.scaling.y;
  54100. this._vertex.z *= this._particle.scaling.z;
  54101. this._vertex.x -= this._scaledPivot.x;
  54102. this._vertex.y -= this._scaledPivot.y;
  54103. this._vertex.z -= this._scaledPivot.z;
  54104. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54105. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54106. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54107. this._rotated.x += this._pivotBackTranslation.x;
  54108. this._rotated.y += this._pivotBackTranslation.y;
  54109. this._rotated.z += this._pivotBackTranslation.z;
  54110. 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;
  54111. 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;
  54112. 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;
  54113. if (this._computeBoundingBox) {
  54114. if (this._positions32[idx] < this._minimum.x) {
  54115. this._minimum.x = this._positions32[idx];
  54116. }
  54117. if (this._positions32[idx] > this._maximum.x) {
  54118. this._maximum.x = this._positions32[idx];
  54119. }
  54120. if (this._positions32[idx + 1] < this._minimum.y) {
  54121. this._minimum.y = this._positions32[idx + 1];
  54122. }
  54123. if (this._positions32[idx + 1] > this._maximum.y) {
  54124. this._maximum.y = this._positions32[idx + 1];
  54125. }
  54126. if (this._positions32[idx + 2] < this._minimum.z) {
  54127. this._minimum.z = this._positions32[idx + 2];
  54128. }
  54129. if (this._positions32[idx + 2] > this._maximum.z) {
  54130. this._maximum.z = this._positions32[idx + 2];
  54131. }
  54132. }
  54133. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  54134. if (!this._computeParticleVertex) {
  54135. this._normal.x = this._fixedNormal32[idx];
  54136. this._normal.y = this._fixedNormal32[idx + 1];
  54137. this._normal.z = this._fixedNormal32[idx + 2];
  54138. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  54139. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  54140. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  54141. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54142. 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;
  54143. 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;
  54144. }
  54145. if (this._computeParticleColor && this._particle.color) {
  54146. this._colors32[colidx] = this._particle.color.r;
  54147. this._colors32[colidx + 1] = this._particle.color.g;
  54148. this._colors32[colidx + 2] = this._particle.color.b;
  54149. this._colors32[colidx + 3] = this._particle.color.a;
  54150. }
  54151. if (this._computeParticleTexture) {
  54152. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54153. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54154. }
  54155. }
  54156. }
  54157. else {
  54158. this._particle._stillInvisible = true; // mark the particle as invisible
  54159. for (pt = 0; pt < this._shape.length; pt++) {
  54160. idx = index + pt * 3;
  54161. colidx = colorIndex + pt * 4;
  54162. uvidx = uvIndex + pt * 2;
  54163. this._positions32[idx] = 0.0;
  54164. this._positions32[idx + 1] = 0.0;
  54165. this._positions32[idx + 2] = 0.0;
  54166. this._normals32[idx] = 0.0;
  54167. this._normals32[idx + 1] = 0.0;
  54168. this._normals32[idx + 2] = 0.0;
  54169. if (this._computeParticleColor && this._particle.color) {
  54170. this._colors32[colidx] = this._particle.color.r;
  54171. this._colors32[colidx + 1] = this._particle.color.g;
  54172. this._colors32[colidx + 2] = this._particle.color.b;
  54173. this._colors32[colidx + 3] = this._particle.color.a;
  54174. }
  54175. if (this._computeParticleTexture) {
  54176. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54177. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54178. }
  54179. }
  54180. }
  54181. // if the particle intersections must be computed : update the bbInfo
  54182. if (this._particlesIntersect) {
  54183. var bInfo = this._particle._boundingInfo;
  54184. var bBox = bInfo.boundingBox;
  54185. var bSphere = bInfo.boundingSphere;
  54186. if (!this._bSphereOnly) {
  54187. // place, scale and rotate the particle bbox within the SPS local system, then update it
  54188. for (var b = 0; b < bBox.vectors.length; b++) {
  54189. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  54190. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  54191. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  54192. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54193. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54194. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54195. 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;
  54196. 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;
  54197. 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;
  54198. }
  54199. bBox._update(this.mesh._worldMatrix);
  54200. }
  54201. // place and scale the particle bouding sphere in the SPS local system, then update it
  54202. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  54203. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  54204. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  54205. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  54206. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  54207. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  54208. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  54209. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  54210. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  54211. 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));
  54212. bSphere._update(this.mesh._worldMatrix);
  54213. }
  54214. // increment indexes for the next particle
  54215. index = idx + 3;
  54216. colorIndex = colidx + 4;
  54217. uvIndex = uvidx + 2;
  54218. }
  54219. // if the VBO must be updated
  54220. if (update) {
  54221. if (this._computeParticleColor) {
  54222. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  54223. }
  54224. if (this._computeParticleTexture) {
  54225. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  54226. }
  54227. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54228. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  54229. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  54230. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  54231. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  54232. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  54233. for (var i = 0; i < this._normals32.length; i++) {
  54234. this._fixedNormal32[i] = this._normals32[i];
  54235. }
  54236. }
  54237. if (!this.mesh.areNormalsFrozen) {
  54238. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54239. }
  54240. }
  54241. if (this._depthSort && this._depthSortParticles) {
  54242. this.depthSortedParticles.sort(this._depthSortFunction);
  54243. var dspl = this.depthSortedParticles.length;
  54244. var sorted = 0;
  54245. var lind = 0;
  54246. var sind = 0;
  54247. var sid = 0;
  54248. for (sorted = 0; sorted < dspl; sorted++) {
  54249. lind = this.depthSortedParticles[sorted].indicesLength;
  54250. sind = this.depthSortedParticles[sorted].ind;
  54251. for (var i = 0; i < lind; i++) {
  54252. this._indices32[sid] = this._indices[sind + i];
  54253. sid++;
  54254. }
  54255. }
  54256. this.mesh.updateIndices(this._indices32);
  54257. }
  54258. }
  54259. if (this._computeBoundingBox) {
  54260. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54261. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54262. }
  54263. this.afterUpdateParticles(start, end, update);
  54264. return this;
  54265. };
  54266. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54267. this._halfroll = this._roll * 0.5;
  54268. this._halfpitch = this._pitch * 0.5;
  54269. this._halfyaw = this._yaw * 0.5;
  54270. this._sinRoll = Math.sin(this._halfroll);
  54271. this._cosRoll = Math.cos(this._halfroll);
  54272. this._sinPitch = Math.sin(this._halfpitch);
  54273. this._cosPitch = Math.cos(this._halfpitch);
  54274. this._sinYaw = Math.sin(this._halfyaw);
  54275. this._cosYaw = Math.cos(this._halfyaw);
  54276. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  54277. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  54278. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  54279. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  54280. };
  54281. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  54282. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  54283. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  54284. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  54285. this._rotMatrix.m[3] = 0;
  54286. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  54287. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  54288. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  54289. this._rotMatrix.m[7] = 0;
  54290. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  54291. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  54292. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  54293. this._rotMatrix.m[11] = 0;
  54294. this._rotMatrix.m[12] = 0;
  54295. this._rotMatrix.m[13] = 0;
  54296. this._rotMatrix.m[14] = 0;
  54297. this._rotMatrix.m[15] = 1.0;
  54298. };
  54299. /**
  54300. * Disposes the SPS.
  54301. */
  54302. SolidParticleSystem.prototype.dispose = function () {
  54303. this.mesh.dispose();
  54304. this.vars = null;
  54305. // drop references to internal big arrays for the GC
  54306. this._positions = null;
  54307. this._indices = null;
  54308. this._normals = null;
  54309. this._uvs = null;
  54310. this._colors = null;
  54311. this._indices32 = null;
  54312. this._positions32 = null;
  54313. this._normals32 = null;
  54314. this._fixedNormal32 = null;
  54315. this._uvs32 = null;
  54316. this._colors32 = null;
  54317. this.pickedParticles = null;
  54318. };
  54319. /**
  54320. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  54321. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54322. * @returns the SPS.
  54323. */
  54324. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  54325. if (!this._isVisibilityBoxLocked) {
  54326. this.mesh.refreshBoundingInfo();
  54327. }
  54328. return this;
  54329. };
  54330. /**
  54331. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  54332. * @param size the size (float) of the visibility box
  54333. * note : this doesn't lock the SPS mesh bounding box.
  54334. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54335. */
  54336. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  54337. var vis = size / 2;
  54338. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  54339. };
  54340. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  54341. /**
  54342. * Gets whether the SPS as always visible or not
  54343. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54344. */
  54345. get: function () {
  54346. return this._alwaysVisible;
  54347. },
  54348. /**
  54349. * Sets the SPS as always visible or not
  54350. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54351. */
  54352. set: function (val) {
  54353. this._alwaysVisible = val;
  54354. this.mesh.alwaysSelectAsActiveMesh = val;
  54355. },
  54356. enumerable: true,
  54357. configurable: true
  54358. });
  54359. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  54360. /**
  54361. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54362. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54363. */
  54364. get: function () {
  54365. return this._isVisibilityBoxLocked;
  54366. },
  54367. /**
  54368. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54369. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54370. */
  54371. set: function (val) {
  54372. this._isVisibilityBoxLocked = val;
  54373. var boundingInfo = this.mesh.getBoundingInfo();
  54374. boundingInfo.isLocked = val;
  54375. },
  54376. enumerable: true,
  54377. configurable: true
  54378. });
  54379. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  54380. /**
  54381. * Gets if `setParticles()` computes the particle rotations or not.
  54382. * Default value : true. The SPS is faster when it's set to false.
  54383. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54384. */
  54385. get: function () {
  54386. return this._computeParticleRotation;
  54387. },
  54388. /**
  54389. * Tells to `setParticles()` to compute the particle rotations or not.
  54390. * Default value : true. The SPS is faster when it's set to false.
  54391. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54392. */
  54393. set: function (val) {
  54394. this._computeParticleRotation = val;
  54395. },
  54396. enumerable: true,
  54397. configurable: true
  54398. });
  54399. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  54400. /**
  54401. * Gets if `setParticles()` computes the particle colors or not.
  54402. * Default value : true. The SPS is faster when it's set to false.
  54403. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54404. */
  54405. get: function () {
  54406. return this._computeParticleColor;
  54407. },
  54408. /**
  54409. * Tells to `setParticles()` to compute the particle colors or not.
  54410. * Default value : true. The SPS is faster when it's set to false.
  54411. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54412. */
  54413. set: function (val) {
  54414. this._computeParticleColor = val;
  54415. },
  54416. enumerable: true,
  54417. configurable: true
  54418. });
  54419. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  54420. /**
  54421. * Gets if `setParticles()` computes the particle textures or not.
  54422. * Default value : true. The SPS is faster when it's set to false.
  54423. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  54424. */
  54425. get: function () {
  54426. return this._computeParticleTexture;
  54427. },
  54428. set: function (val) {
  54429. this._computeParticleTexture = val;
  54430. },
  54431. enumerable: true,
  54432. configurable: true
  54433. });
  54434. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  54435. /**
  54436. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  54437. * Default value : false. The SPS is faster when it's set to false.
  54438. * Note : the particle custom vertex positions aren't stored values.
  54439. */
  54440. get: function () {
  54441. return this._computeParticleVertex;
  54442. },
  54443. /**
  54444. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  54445. * Default value : false. The SPS is faster when it's set to false.
  54446. * Note : the particle custom vertex positions aren't stored values.
  54447. */
  54448. set: function (val) {
  54449. this._computeParticleVertex = val;
  54450. },
  54451. enumerable: true,
  54452. configurable: true
  54453. });
  54454. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  54455. /**
  54456. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  54457. */
  54458. get: function () {
  54459. return this._computeBoundingBox;
  54460. },
  54461. /**
  54462. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  54463. */
  54464. set: function (val) {
  54465. this._computeBoundingBox = val;
  54466. },
  54467. enumerable: true,
  54468. configurable: true
  54469. });
  54470. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  54471. /**
  54472. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  54473. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54474. * Default : `true`
  54475. */
  54476. get: function () {
  54477. return this._depthSortParticles;
  54478. },
  54479. /**
  54480. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  54481. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54482. * Default : `true`
  54483. */
  54484. set: function (val) {
  54485. this._depthSortParticles = val;
  54486. },
  54487. enumerable: true,
  54488. configurable: true
  54489. });
  54490. // =======================================================================
  54491. // Particle behavior logic
  54492. // these following methods may be overwritten by the user to fit his needs
  54493. /**
  54494. * This function does nothing. It may be overwritten to set all the particle first values.
  54495. * The SPS doesn't call this function, you may have to call it by your own.
  54496. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54497. */
  54498. SolidParticleSystem.prototype.initParticles = function () {
  54499. };
  54500. /**
  54501. * This function does nothing. It may be overwritten to recycle a particle.
  54502. * The SPS doesn't call this function, you may have to call it by your own.
  54503. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54504. * @param particle The particle to recycle
  54505. * @returns the recycled particle
  54506. */
  54507. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  54508. return particle;
  54509. };
  54510. /**
  54511. * Updates a particle : this function should be overwritten by the user.
  54512. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  54513. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54514. * @example : just set a particle position or velocity and recycle conditions
  54515. * @param particle The particle to update
  54516. * @returns the updated particle
  54517. */
  54518. SolidParticleSystem.prototype.updateParticle = function (particle) {
  54519. return particle;
  54520. };
  54521. /**
  54522. * Updates a vertex of a particle : it can be overwritten by the user.
  54523. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  54524. * @param particle the current particle
  54525. * @param vertex the current index of the current particle
  54526. * @param pt the index of the current vertex in the particle shape
  54527. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  54528. * @example : just set a vertex particle position
  54529. * @returns the updated vertex
  54530. */
  54531. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  54532. return vertex;
  54533. };
  54534. /**
  54535. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  54536. * This does nothing and may be overwritten by the user.
  54537. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54538. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54539. * @param update the boolean update value actually passed to setParticles()
  54540. */
  54541. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  54542. };
  54543. /**
  54544. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  54545. * This will be passed three parameters.
  54546. * This does nothing and may be overwritten by the user.
  54547. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54548. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54549. * @param update the boolean update value actually passed to setParticles()
  54550. */
  54551. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  54552. };
  54553. return SolidParticleSystem;
  54554. }());
  54555. BABYLON.SolidParticleSystem = SolidParticleSystem;
  54556. })(BABYLON || (BABYLON = {}));
  54557. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  54558. var BABYLON;
  54559. (function (BABYLON) {
  54560. var ShaderMaterial = /** @class */ (function (_super) {
  54561. __extends(ShaderMaterial, _super);
  54562. function ShaderMaterial(name, scene, shaderPath, options) {
  54563. var _this = _super.call(this, name, scene) || this;
  54564. _this._textures = {};
  54565. _this._textureArrays = {};
  54566. _this._floats = {};
  54567. _this._ints = {};
  54568. _this._floatsArrays = {};
  54569. _this._colors3 = {};
  54570. _this._colors3Arrays = {};
  54571. _this._colors4 = {};
  54572. _this._vectors2 = {};
  54573. _this._vectors3 = {};
  54574. _this._vectors4 = {};
  54575. _this._matrices = {};
  54576. _this._matrices3x3 = {};
  54577. _this._matrices2x2 = {};
  54578. _this._vectors2Arrays = {};
  54579. _this._vectors3Arrays = {};
  54580. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  54581. _this._shaderPath = shaderPath;
  54582. options.needAlphaBlending = options.needAlphaBlending || false;
  54583. options.needAlphaTesting = options.needAlphaTesting || false;
  54584. options.attributes = options.attributes || ["position", "normal", "uv"];
  54585. options.uniforms = options.uniforms || ["worldViewProjection"];
  54586. options.uniformBuffers = options.uniformBuffers || [];
  54587. options.samplers = options.samplers || [];
  54588. options.defines = options.defines || [];
  54589. _this._options = options;
  54590. return _this;
  54591. }
  54592. ShaderMaterial.prototype.getClassName = function () {
  54593. return "ShaderMaterial";
  54594. };
  54595. ShaderMaterial.prototype.needAlphaBlending = function () {
  54596. return this._options.needAlphaBlending;
  54597. };
  54598. ShaderMaterial.prototype.needAlphaTesting = function () {
  54599. return this._options.needAlphaTesting;
  54600. };
  54601. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  54602. if (this._options.uniforms.indexOf(uniformName) === -1) {
  54603. this._options.uniforms.push(uniformName);
  54604. }
  54605. };
  54606. ShaderMaterial.prototype.setTexture = function (name, texture) {
  54607. if (this._options.samplers.indexOf(name) === -1) {
  54608. this._options.samplers.push(name);
  54609. }
  54610. this._textures[name] = texture;
  54611. return this;
  54612. };
  54613. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  54614. if (this._options.samplers.indexOf(name) === -1) {
  54615. this._options.samplers.push(name);
  54616. }
  54617. this._checkUniform(name);
  54618. this._textureArrays[name] = textures;
  54619. return this;
  54620. };
  54621. ShaderMaterial.prototype.setFloat = function (name, value) {
  54622. this._checkUniform(name);
  54623. this._floats[name] = value;
  54624. return this;
  54625. };
  54626. ShaderMaterial.prototype.setInt = function (name, value) {
  54627. this._checkUniform(name);
  54628. this._ints[name] = value;
  54629. return this;
  54630. };
  54631. ShaderMaterial.prototype.setFloats = function (name, value) {
  54632. this._checkUniform(name);
  54633. this._floatsArrays[name] = value;
  54634. return this;
  54635. };
  54636. ShaderMaterial.prototype.setColor3 = function (name, value) {
  54637. this._checkUniform(name);
  54638. this._colors3[name] = value;
  54639. return this;
  54640. };
  54641. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  54642. this._checkUniform(name);
  54643. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  54644. color.toArray(arr, arr.length);
  54645. return arr;
  54646. }, []);
  54647. return this;
  54648. };
  54649. ShaderMaterial.prototype.setColor4 = function (name, value) {
  54650. this._checkUniform(name);
  54651. this._colors4[name] = value;
  54652. return this;
  54653. };
  54654. ShaderMaterial.prototype.setVector2 = function (name, value) {
  54655. this._checkUniform(name);
  54656. this._vectors2[name] = value;
  54657. return this;
  54658. };
  54659. ShaderMaterial.prototype.setVector3 = function (name, value) {
  54660. this._checkUniform(name);
  54661. this._vectors3[name] = value;
  54662. return this;
  54663. };
  54664. ShaderMaterial.prototype.setVector4 = function (name, value) {
  54665. this._checkUniform(name);
  54666. this._vectors4[name] = value;
  54667. return this;
  54668. };
  54669. ShaderMaterial.prototype.setMatrix = function (name, value) {
  54670. this._checkUniform(name);
  54671. this._matrices[name] = value;
  54672. return this;
  54673. };
  54674. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  54675. this._checkUniform(name);
  54676. this._matrices3x3[name] = value;
  54677. return this;
  54678. };
  54679. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  54680. this._checkUniform(name);
  54681. this._matrices2x2[name] = value;
  54682. return this;
  54683. };
  54684. ShaderMaterial.prototype.setArray2 = function (name, value) {
  54685. this._checkUniform(name);
  54686. this._vectors2Arrays[name] = value;
  54687. return this;
  54688. };
  54689. ShaderMaterial.prototype.setArray3 = function (name, value) {
  54690. this._checkUniform(name);
  54691. this._vectors3Arrays[name] = value;
  54692. return this;
  54693. };
  54694. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  54695. if (!mesh) {
  54696. return true;
  54697. }
  54698. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  54699. return false;
  54700. }
  54701. return false;
  54702. };
  54703. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  54704. var scene = this.getScene();
  54705. var engine = scene.getEngine();
  54706. if (!this.checkReadyOnEveryCall) {
  54707. if (this._renderId === scene.getRenderId()) {
  54708. if (this._checkCache(scene, mesh, useInstances)) {
  54709. return true;
  54710. }
  54711. }
  54712. }
  54713. // Instances
  54714. var defines = [];
  54715. var attribs = [];
  54716. var fallbacks = new BABYLON.EffectFallbacks();
  54717. if (useInstances) {
  54718. defines.push("#define INSTANCES");
  54719. }
  54720. for (var index = 0; index < this._options.defines.length; index++) {
  54721. defines.push(this._options.defines[index]);
  54722. }
  54723. for (var index = 0; index < this._options.attributes.length; index++) {
  54724. attribs.push(this._options.attributes[index]);
  54725. }
  54726. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  54727. attribs.push(BABYLON.VertexBuffer.ColorKind);
  54728. defines.push("#define VERTEXCOLOR");
  54729. }
  54730. // Bones
  54731. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  54732. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54733. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54734. if (mesh.numBoneInfluencers > 4) {
  54735. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  54736. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  54737. }
  54738. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54739. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54740. fallbacks.addCPUSkinningFallback(0, mesh);
  54741. if (this._options.uniforms.indexOf("mBones") === -1) {
  54742. this._options.uniforms.push("mBones");
  54743. }
  54744. }
  54745. else {
  54746. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54747. }
  54748. // Textures
  54749. for (var name in this._textures) {
  54750. if (!this._textures[name].isReady()) {
  54751. return false;
  54752. }
  54753. }
  54754. // Alpha test
  54755. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  54756. defines.push("#define ALPHATEST");
  54757. }
  54758. var previousEffect = this._effect;
  54759. var join = defines.join("\n");
  54760. this._effect = engine.createEffect(this._shaderPath, {
  54761. attributes: attribs,
  54762. uniformsNames: this._options.uniforms,
  54763. uniformBuffersNames: this._options.uniformBuffers,
  54764. samplers: this._options.samplers,
  54765. defines: join,
  54766. fallbacks: fallbacks,
  54767. onCompiled: this.onCompiled,
  54768. onError: this.onError
  54769. }, engine);
  54770. if (!this._effect.isReady()) {
  54771. return false;
  54772. }
  54773. if (previousEffect !== this._effect) {
  54774. scene.resetCachedMaterial();
  54775. }
  54776. this._renderId = scene.getRenderId();
  54777. return true;
  54778. };
  54779. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  54780. var scene = this.getScene();
  54781. if (!this._effect) {
  54782. return;
  54783. }
  54784. if (this._options.uniforms.indexOf("world") !== -1) {
  54785. this._effect.setMatrix("world", world);
  54786. }
  54787. if (this._options.uniforms.indexOf("worldView") !== -1) {
  54788. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  54789. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  54790. }
  54791. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  54792. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  54793. }
  54794. };
  54795. ShaderMaterial.prototype.bind = function (world, mesh) {
  54796. // Std values
  54797. this.bindOnlyWorldMatrix(world);
  54798. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  54799. if (this._options.uniforms.indexOf("view") !== -1) {
  54800. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  54801. }
  54802. if (this._options.uniforms.indexOf("projection") !== -1) {
  54803. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  54804. }
  54805. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  54806. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  54807. }
  54808. // Bones
  54809. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  54810. var name;
  54811. // Texture
  54812. for (name in this._textures) {
  54813. this._effect.setTexture(name, this._textures[name]);
  54814. }
  54815. // Texture arrays
  54816. for (name in this._textureArrays) {
  54817. this._effect.setTextureArray(name, this._textureArrays[name]);
  54818. }
  54819. // Int
  54820. for (name in this._ints) {
  54821. this._effect.setInt(name, this._ints[name]);
  54822. }
  54823. // Float
  54824. for (name in this._floats) {
  54825. this._effect.setFloat(name, this._floats[name]);
  54826. }
  54827. // Floats
  54828. for (name in this._floatsArrays) {
  54829. this._effect.setArray(name, this._floatsArrays[name]);
  54830. }
  54831. // Color3
  54832. for (name in this._colors3) {
  54833. this._effect.setColor3(name, this._colors3[name]);
  54834. }
  54835. for (name in this._colors3Arrays) {
  54836. this._effect.setArray3(name, this._colors3Arrays[name]);
  54837. }
  54838. // Color4
  54839. for (name in this._colors4) {
  54840. var color = this._colors4[name];
  54841. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  54842. }
  54843. // Vector2
  54844. for (name in this._vectors2) {
  54845. this._effect.setVector2(name, this._vectors2[name]);
  54846. }
  54847. // Vector3
  54848. for (name in this._vectors3) {
  54849. this._effect.setVector3(name, this._vectors3[name]);
  54850. }
  54851. // Vector4
  54852. for (name in this._vectors4) {
  54853. this._effect.setVector4(name, this._vectors4[name]);
  54854. }
  54855. // Matrix
  54856. for (name in this._matrices) {
  54857. this._effect.setMatrix(name, this._matrices[name]);
  54858. }
  54859. // Matrix 3x3
  54860. for (name in this._matrices3x3) {
  54861. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  54862. }
  54863. // Matrix 2x2
  54864. for (name in this._matrices2x2) {
  54865. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  54866. }
  54867. // Vector2Array
  54868. for (name in this._vectors2Arrays) {
  54869. this._effect.setArray2(name, this._vectors2Arrays[name]);
  54870. }
  54871. // Vector3Array
  54872. for (name in this._vectors3Arrays) {
  54873. this._effect.setArray3(name, this._vectors3Arrays[name]);
  54874. }
  54875. }
  54876. this._afterBind(mesh);
  54877. };
  54878. ShaderMaterial.prototype.getActiveTextures = function () {
  54879. var activeTextures = _super.prototype.getActiveTextures.call(this);
  54880. for (var name in this._textures) {
  54881. activeTextures.push(this._textures[name]);
  54882. }
  54883. for (var name in this._textureArrays) {
  54884. var array = this._textureArrays[name];
  54885. for (var index = 0; index < array.length; index++) {
  54886. activeTextures.push(array[index]);
  54887. }
  54888. }
  54889. return activeTextures;
  54890. };
  54891. ShaderMaterial.prototype.hasTexture = function (texture) {
  54892. if (_super.prototype.hasTexture.call(this, texture)) {
  54893. return true;
  54894. }
  54895. for (var name in this._textures) {
  54896. if (this._textures[name] === texture) {
  54897. return true;
  54898. }
  54899. }
  54900. for (var name in this._textureArrays) {
  54901. var array = this._textureArrays[name];
  54902. for (var index = 0; index < array.length; index++) {
  54903. if (array[index] === texture) {
  54904. return true;
  54905. }
  54906. }
  54907. }
  54908. return false;
  54909. };
  54910. ShaderMaterial.prototype.clone = function (name) {
  54911. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  54912. return newShaderMaterial;
  54913. };
  54914. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54915. if (forceDisposeTextures) {
  54916. var name;
  54917. for (name in this._textures) {
  54918. this._textures[name].dispose();
  54919. }
  54920. for (name in this._textureArrays) {
  54921. var array = this._textureArrays[name];
  54922. for (var index = 0; index < array.length; index++) {
  54923. array[index].dispose();
  54924. }
  54925. }
  54926. }
  54927. this._textures = {};
  54928. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54929. };
  54930. ShaderMaterial.prototype.serialize = function () {
  54931. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54932. serializationObject.customType = "BABYLON.ShaderMaterial";
  54933. serializationObject.options = this._options;
  54934. serializationObject.shaderPath = this._shaderPath;
  54935. var name;
  54936. // Texture
  54937. serializationObject.textures = {};
  54938. for (name in this._textures) {
  54939. serializationObject.textures[name] = this._textures[name].serialize();
  54940. }
  54941. // Texture arrays
  54942. serializationObject.textureArrays = {};
  54943. for (name in this._textureArrays) {
  54944. serializationObject.textureArrays[name] = [];
  54945. var array = this._textureArrays[name];
  54946. for (var index = 0; index < array.length; index++) {
  54947. serializationObject.textureArrays[name].push(array[index].serialize());
  54948. }
  54949. }
  54950. // Float
  54951. serializationObject.floats = {};
  54952. for (name in this._floats) {
  54953. serializationObject.floats[name] = this._floats[name];
  54954. }
  54955. // Float s
  54956. serializationObject.FloatArrays = {};
  54957. for (name in this._floatsArrays) {
  54958. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  54959. }
  54960. // Color3
  54961. serializationObject.colors3 = {};
  54962. for (name in this._colors3) {
  54963. serializationObject.colors3[name] = this._colors3[name].asArray();
  54964. }
  54965. // Color3 array
  54966. serializationObject.colors3Arrays = {};
  54967. for (name in this._colors3Arrays) {
  54968. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  54969. }
  54970. // Color4
  54971. serializationObject.colors4 = {};
  54972. for (name in this._colors4) {
  54973. serializationObject.colors4[name] = this._colors4[name].asArray();
  54974. }
  54975. // Vector2
  54976. serializationObject.vectors2 = {};
  54977. for (name in this._vectors2) {
  54978. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  54979. }
  54980. // Vector3
  54981. serializationObject.vectors3 = {};
  54982. for (name in this._vectors3) {
  54983. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  54984. }
  54985. // Vector4
  54986. serializationObject.vectors4 = {};
  54987. for (name in this._vectors4) {
  54988. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  54989. }
  54990. // Matrix
  54991. serializationObject.matrices = {};
  54992. for (name in this._matrices) {
  54993. serializationObject.matrices[name] = this._matrices[name].asArray();
  54994. }
  54995. // Matrix 3x3
  54996. serializationObject.matrices3x3 = {};
  54997. for (name in this._matrices3x3) {
  54998. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  54999. }
  55000. // Matrix 2x2
  55001. serializationObject.matrices2x2 = {};
  55002. for (name in this._matrices2x2) {
  55003. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  55004. }
  55005. // Vector2Array
  55006. serializationObject.vectors2Arrays = {};
  55007. for (name in this._vectors2Arrays) {
  55008. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  55009. }
  55010. // Vector3Array
  55011. serializationObject.vectors3Arrays = {};
  55012. for (name in this._vectors3Arrays) {
  55013. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  55014. }
  55015. return serializationObject;
  55016. };
  55017. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  55018. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  55019. var name;
  55020. // Texture
  55021. for (name in source.textures) {
  55022. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  55023. }
  55024. // Texture arrays
  55025. for (name in source.textureArrays) {
  55026. var array = source.textureArrays[name];
  55027. var textureArray = new Array();
  55028. for (var index = 0; index < array.length; index++) {
  55029. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  55030. }
  55031. material.setTextureArray(name, textureArray);
  55032. }
  55033. // Float
  55034. for (name in source.floats) {
  55035. material.setFloat(name, source.floats[name]);
  55036. }
  55037. // Float s
  55038. for (name in source.floatsArrays) {
  55039. material.setFloats(name, source.floatsArrays[name]);
  55040. }
  55041. // Color3
  55042. for (name in source.colors3) {
  55043. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  55044. }
  55045. // Color3 arrays
  55046. for (name in source.colors3Arrays) {
  55047. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  55048. if (i % 3 === 0) {
  55049. arr.push([num]);
  55050. }
  55051. else {
  55052. arr[arr.length - 1].push(num);
  55053. }
  55054. return arr;
  55055. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  55056. material.setColor3Array(name, colors);
  55057. }
  55058. // Color4
  55059. for (name in source.colors4) {
  55060. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  55061. }
  55062. // Vector2
  55063. for (name in source.vectors2) {
  55064. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  55065. }
  55066. // Vector3
  55067. for (name in source.vectors3) {
  55068. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  55069. }
  55070. // Vector4
  55071. for (name in source.vectors4) {
  55072. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  55073. }
  55074. // Matrix
  55075. for (name in source.matrices) {
  55076. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  55077. }
  55078. // Matrix 3x3
  55079. for (name in source.matrices3x3) {
  55080. material.setMatrix3x3(name, source.matrices3x3[name]);
  55081. }
  55082. // Matrix 2x2
  55083. for (name in source.matrices2x2) {
  55084. material.setMatrix2x2(name, source.matrices2x2[name]);
  55085. }
  55086. // Vector2Array
  55087. for (name in source.vectors2Arrays) {
  55088. material.setArray2(name, source.vectors2Arrays[name]);
  55089. }
  55090. // Vector3Array
  55091. for (name in source.vectors3Arrays) {
  55092. material.setArray3(name, source.vectors3Arrays[name]);
  55093. }
  55094. return material;
  55095. };
  55096. return ShaderMaterial;
  55097. }(BABYLON.Material));
  55098. BABYLON.ShaderMaterial = ShaderMaterial;
  55099. })(BABYLON || (BABYLON = {}));
  55100. //# sourceMappingURL=babylon.shaderMaterial.js.map
  55101. var BABYLON;
  55102. (function (BABYLON) {
  55103. var GroundMesh = /** @class */ (function (_super) {
  55104. __extends(GroundMesh, _super);
  55105. function GroundMesh(name, scene) {
  55106. var _this = _super.call(this, name, scene) || this;
  55107. _this.generateOctree = false;
  55108. return _this;
  55109. }
  55110. GroundMesh.prototype.getClassName = function () {
  55111. return "GroundMesh";
  55112. };
  55113. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  55114. get: function () {
  55115. return Math.min(this._subdivisionsX, this._subdivisionsY);
  55116. },
  55117. enumerable: true,
  55118. configurable: true
  55119. });
  55120. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  55121. get: function () {
  55122. return this._subdivisionsX;
  55123. },
  55124. enumerable: true,
  55125. configurable: true
  55126. });
  55127. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  55128. get: function () {
  55129. return this._subdivisionsY;
  55130. },
  55131. enumerable: true,
  55132. configurable: true
  55133. });
  55134. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  55135. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  55136. this._subdivisionsX = chunksCount;
  55137. this._subdivisionsY = chunksCount;
  55138. this.subdivide(chunksCount);
  55139. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  55140. };
  55141. /**
  55142. * Returns a height (y) value in the Worl system :
  55143. * the ground altitude at the coordinates (x, z) expressed in the World system.
  55144. * Returns the ground y position if (x, z) are outside the ground surface.
  55145. */
  55146. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  55147. var world = this.getWorldMatrix();
  55148. var invMat = BABYLON.Tmp.Matrix[5];
  55149. world.invertToRef(invMat);
  55150. var tmpVect = BABYLON.Tmp.Vector3[8];
  55151. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  55152. x = tmpVect.x;
  55153. z = tmpVect.z;
  55154. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55155. return this.position.y;
  55156. }
  55157. if (!this._heightQuads || this._heightQuads.length == 0) {
  55158. this._initHeightQuads();
  55159. this._computeHeightQuads();
  55160. }
  55161. var facet = this._getFacetAt(x, z);
  55162. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  55163. // return y in the World system
  55164. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  55165. return tmpVect.y;
  55166. };
  55167. /**
  55168. * Returns a normalized vector (Vector3) orthogonal to the ground
  55169. * at the ground coordinates (x, z) expressed in the World system.
  55170. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  55171. */
  55172. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  55173. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  55174. this.getNormalAtCoordinatesToRef(x, z, normal);
  55175. return normal;
  55176. };
  55177. /**
  55178. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  55179. * at the ground coordinates (x, z) expressed in the World system.
  55180. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  55181. * Returns the GroundMesh.
  55182. */
  55183. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  55184. var world = this.getWorldMatrix();
  55185. var tmpMat = BABYLON.Tmp.Matrix[5];
  55186. world.invertToRef(tmpMat);
  55187. var tmpVect = BABYLON.Tmp.Vector3[8];
  55188. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  55189. x = tmpVect.x;
  55190. z = tmpVect.z;
  55191. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55192. return this;
  55193. }
  55194. if (!this._heightQuads || this._heightQuads.length == 0) {
  55195. this._initHeightQuads();
  55196. this._computeHeightQuads();
  55197. }
  55198. var facet = this._getFacetAt(x, z);
  55199. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  55200. return this;
  55201. };
  55202. /**
  55203. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  55204. * if the ground has been updated.
  55205. * This can be used in the render loop.
  55206. * Returns the GroundMesh.
  55207. */
  55208. GroundMesh.prototype.updateCoordinateHeights = function () {
  55209. if (!this._heightQuads || this._heightQuads.length == 0) {
  55210. this._initHeightQuads();
  55211. }
  55212. this._computeHeightQuads();
  55213. return this;
  55214. };
  55215. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  55216. GroundMesh.prototype._getFacetAt = function (x, z) {
  55217. // retrieve col and row from x, z coordinates in the ground local system
  55218. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  55219. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  55220. var quad = this._heightQuads[row * this._subdivisionsX + col];
  55221. var facet;
  55222. if (z < quad.slope.x * x + quad.slope.y) {
  55223. facet = quad.facet1;
  55224. }
  55225. else {
  55226. facet = quad.facet2;
  55227. }
  55228. return facet;
  55229. };
  55230. // Creates and populates the heightMap array with "facet" elements :
  55231. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  55232. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55233. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55234. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55235. // Returns the GroundMesh.
  55236. GroundMesh.prototype._initHeightQuads = function () {
  55237. var subdivisionsX = this._subdivisionsX;
  55238. var subdivisionsY = this._subdivisionsY;
  55239. this._heightQuads = new Array();
  55240. for (var row = 0; row < subdivisionsY; row++) {
  55241. for (var col = 0; col < subdivisionsX; col++) {
  55242. 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) };
  55243. this._heightQuads[row * subdivisionsX + col] = quad;
  55244. }
  55245. }
  55246. return this;
  55247. };
  55248. // Compute each quad element values and update the the heightMap array :
  55249. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55250. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55251. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55252. // Returns the GroundMesh.
  55253. GroundMesh.prototype._computeHeightQuads = function () {
  55254. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55255. if (!positions) {
  55256. return this;
  55257. }
  55258. var v1 = BABYLON.Tmp.Vector3[3];
  55259. var v2 = BABYLON.Tmp.Vector3[2];
  55260. var v3 = BABYLON.Tmp.Vector3[1];
  55261. var v4 = BABYLON.Tmp.Vector3[0];
  55262. var v1v2 = BABYLON.Tmp.Vector3[4];
  55263. var v1v3 = BABYLON.Tmp.Vector3[5];
  55264. var v1v4 = BABYLON.Tmp.Vector3[6];
  55265. var norm1 = BABYLON.Tmp.Vector3[7];
  55266. var norm2 = BABYLON.Tmp.Vector3[8];
  55267. var i = 0;
  55268. var j = 0;
  55269. var k = 0;
  55270. var cd = 0; // 2D slope coefficient : z = cd * x + h
  55271. var h = 0;
  55272. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  55273. var d2 = 0;
  55274. var subdivisionsX = this._subdivisionsX;
  55275. var subdivisionsY = this._subdivisionsY;
  55276. for (var row = 0; row < subdivisionsY; row++) {
  55277. for (var col = 0; col < subdivisionsX; col++) {
  55278. i = col * 3;
  55279. j = row * (subdivisionsX + 1) * 3;
  55280. k = (row + 1) * (subdivisionsX + 1) * 3;
  55281. v1.x = positions[j + i];
  55282. v1.y = positions[j + i + 1];
  55283. v1.z = positions[j + i + 2];
  55284. v2.x = positions[j + i + 3];
  55285. v2.y = positions[j + i + 4];
  55286. v2.z = positions[j + i + 5];
  55287. v3.x = positions[k + i];
  55288. v3.y = positions[k + i + 1];
  55289. v3.z = positions[k + i + 2];
  55290. v4.x = positions[k + i + 3];
  55291. v4.y = positions[k + i + 4];
  55292. v4.z = positions[k + i + 5];
  55293. // 2D slope V1V4
  55294. cd = (v4.z - v1.z) / (v4.x - v1.x);
  55295. h = v1.z - cd * v1.x; // v1 belongs to the slope
  55296. // facet equations :
  55297. // we compute each facet normal vector
  55298. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  55299. // we compute the value d by applying the equation to v1 which belongs to the plane
  55300. // then we store the facet equation in a Vector4
  55301. v2.subtractToRef(v1, v1v2);
  55302. v3.subtractToRef(v1, v1v3);
  55303. v4.subtractToRef(v1, v1v4);
  55304. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  55305. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  55306. norm1.normalize();
  55307. norm2.normalize();
  55308. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  55309. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  55310. var quad = this._heightQuads[row * subdivisionsX + col];
  55311. quad.slope.copyFromFloats(cd, h);
  55312. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  55313. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  55314. }
  55315. }
  55316. return this;
  55317. };
  55318. GroundMesh.prototype.serialize = function (serializationObject) {
  55319. _super.prototype.serialize.call(this, serializationObject);
  55320. serializationObject.subdivisionsX = this._subdivisionsX;
  55321. serializationObject.subdivisionsY = this._subdivisionsY;
  55322. serializationObject.minX = this._minX;
  55323. serializationObject.maxX = this._maxX;
  55324. serializationObject.minZ = this._minZ;
  55325. serializationObject.maxZ = this._maxZ;
  55326. serializationObject.width = this._width;
  55327. serializationObject.height = this._height;
  55328. };
  55329. GroundMesh.Parse = function (parsedMesh, scene) {
  55330. var result = new GroundMesh(parsedMesh.name, scene);
  55331. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  55332. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  55333. result._minX = parsedMesh.minX;
  55334. result._maxX = parsedMesh.maxX;
  55335. result._minZ = parsedMesh.minZ;
  55336. result._maxZ = parsedMesh.maxZ;
  55337. result._width = parsedMesh.width;
  55338. result._height = parsedMesh.height;
  55339. return result;
  55340. };
  55341. return GroundMesh;
  55342. }(BABYLON.Mesh));
  55343. BABYLON.GroundMesh = GroundMesh;
  55344. })(BABYLON || (BABYLON = {}));
  55345. //# sourceMappingURL=babylon.groundMesh.js.map
  55346. var BABYLON;
  55347. (function (BABYLON) {
  55348. /**
  55349. * Creates an instance based on a source mesh.
  55350. */
  55351. var InstancedMesh = /** @class */ (function (_super) {
  55352. __extends(InstancedMesh, _super);
  55353. function InstancedMesh(name, source) {
  55354. var _this = _super.call(this, name, source.getScene()) || this;
  55355. source.instances.push(_this);
  55356. _this._sourceMesh = source;
  55357. _this.position.copyFrom(source.position);
  55358. _this.rotation.copyFrom(source.rotation);
  55359. _this.scaling.copyFrom(source.scaling);
  55360. if (source.rotationQuaternion) {
  55361. _this.rotationQuaternion = source.rotationQuaternion.clone();
  55362. }
  55363. _this.infiniteDistance = source.infiniteDistance;
  55364. _this.setPivotMatrix(source.getPivotMatrix());
  55365. _this.refreshBoundingInfo();
  55366. _this._syncSubMeshes();
  55367. return _this;
  55368. }
  55369. /**
  55370. * Returns the string "InstancedMesh".
  55371. */
  55372. InstancedMesh.prototype.getClassName = function () {
  55373. return "InstancedMesh";
  55374. };
  55375. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  55376. // Methods
  55377. get: function () {
  55378. return this._sourceMesh.receiveShadows;
  55379. },
  55380. enumerable: true,
  55381. configurable: true
  55382. });
  55383. Object.defineProperty(InstancedMesh.prototype, "material", {
  55384. get: function () {
  55385. return this._sourceMesh.material;
  55386. },
  55387. enumerable: true,
  55388. configurable: true
  55389. });
  55390. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  55391. get: function () {
  55392. return this._sourceMesh.visibility;
  55393. },
  55394. enumerable: true,
  55395. configurable: true
  55396. });
  55397. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  55398. get: function () {
  55399. return this._sourceMesh.skeleton;
  55400. },
  55401. enumerable: true,
  55402. configurable: true
  55403. });
  55404. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  55405. get: function () {
  55406. return this._sourceMesh.renderingGroupId;
  55407. },
  55408. set: function (value) {
  55409. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  55410. return;
  55411. }
  55412. //no-op with warning
  55413. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  55414. },
  55415. enumerable: true,
  55416. configurable: true
  55417. });
  55418. /**
  55419. * Returns the total number of vertices (integer).
  55420. */
  55421. InstancedMesh.prototype.getTotalVertices = function () {
  55422. return this._sourceMesh.getTotalVertices();
  55423. };
  55424. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  55425. get: function () {
  55426. return this._sourceMesh;
  55427. },
  55428. enumerable: true,
  55429. configurable: true
  55430. });
  55431. /**
  55432. * Is this node ready to be used/rendered
  55433. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  55434. * @return {boolean} is it ready
  55435. */
  55436. InstancedMesh.prototype.isReady = function (completeCheck) {
  55437. if (completeCheck === void 0) { completeCheck = false; }
  55438. return this._sourceMesh.isReady(completeCheck, true);
  55439. };
  55440. /**
  55441. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  55442. */
  55443. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  55444. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  55445. };
  55446. /**
  55447. * Sets the vertex data of the mesh geometry for the requested `kind`.
  55448. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  55449. * The `data` are either a numeric array either a Float32Array.
  55450. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  55451. * 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).
  55452. * Note that a new underlying VertexBuffer object is created each call.
  55453. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  55454. *
  55455. * Possible `kind` values :
  55456. * - BABYLON.VertexBuffer.PositionKind
  55457. * - BABYLON.VertexBuffer.UVKind
  55458. * - BABYLON.VertexBuffer.UV2Kind
  55459. * - BABYLON.VertexBuffer.UV3Kind
  55460. * - BABYLON.VertexBuffer.UV4Kind
  55461. * - BABYLON.VertexBuffer.UV5Kind
  55462. * - BABYLON.VertexBuffer.UV6Kind
  55463. * - BABYLON.VertexBuffer.ColorKind
  55464. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55465. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55466. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55467. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55468. *
  55469. * Returns the Mesh.
  55470. */
  55471. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  55472. if (this.sourceMesh) {
  55473. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  55474. }
  55475. return this.sourceMesh;
  55476. };
  55477. /**
  55478. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  55479. * If the mesh has no geometry, it is simply returned as it is.
  55480. * The `data` are either a numeric array either a Float32Array.
  55481. * No new underlying VertexBuffer object is created.
  55482. * 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.
  55483. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  55484. *
  55485. * Possible `kind` values :
  55486. * - BABYLON.VertexBuffer.PositionKind
  55487. * - BABYLON.VertexBuffer.UVKind
  55488. * - BABYLON.VertexBuffer.UV2Kind
  55489. * - BABYLON.VertexBuffer.UV3Kind
  55490. * - BABYLON.VertexBuffer.UV4Kind
  55491. * - BABYLON.VertexBuffer.UV5Kind
  55492. * - BABYLON.VertexBuffer.UV6Kind
  55493. * - BABYLON.VertexBuffer.ColorKind
  55494. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55495. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55496. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55497. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55498. *
  55499. * Returns the Mesh.
  55500. */
  55501. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  55502. if (this.sourceMesh) {
  55503. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  55504. }
  55505. return this.sourceMesh;
  55506. };
  55507. /**
  55508. * Sets the mesh indices.
  55509. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  55510. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  55511. * This method creates a new index buffer each call.
  55512. * Returns the Mesh.
  55513. */
  55514. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  55515. if (totalVertices === void 0) { totalVertices = null; }
  55516. if (this.sourceMesh) {
  55517. this.sourceMesh.setIndices(indices, totalVertices);
  55518. }
  55519. return this.sourceMesh;
  55520. };
  55521. /**
  55522. * Boolean : True if the mesh owns the requested kind of data.
  55523. */
  55524. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  55525. return this._sourceMesh.isVerticesDataPresent(kind);
  55526. };
  55527. /**
  55528. * Returns an array of indices (IndicesArray).
  55529. */
  55530. InstancedMesh.prototype.getIndices = function () {
  55531. return this._sourceMesh.getIndices();
  55532. };
  55533. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  55534. get: function () {
  55535. return this._sourceMesh._positions;
  55536. },
  55537. enumerable: true,
  55538. configurable: true
  55539. });
  55540. /**
  55541. * Sets a new updated BoundingInfo to the mesh.
  55542. * Returns the mesh.
  55543. */
  55544. InstancedMesh.prototype.refreshBoundingInfo = function () {
  55545. var meshBB = this._sourceMesh.getBoundingInfo();
  55546. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  55547. this._updateBoundingInfo();
  55548. return this;
  55549. };
  55550. InstancedMesh.prototype._preActivate = function () {
  55551. if (this._currentLOD) {
  55552. this._currentLOD._preActivate();
  55553. }
  55554. return this;
  55555. };
  55556. InstancedMesh.prototype._activate = function (renderId) {
  55557. if (this._currentLOD) {
  55558. this._currentLOD._registerInstanceForRenderId(this, renderId);
  55559. }
  55560. return this;
  55561. };
  55562. /**
  55563. * Returns the current associated LOD AbstractMesh.
  55564. */
  55565. InstancedMesh.prototype.getLOD = function (camera) {
  55566. if (!camera) {
  55567. return this;
  55568. }
  55569. var boundingInfo = this.getBoundingInfo();
  55570. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  55571. if (this._currentLOD === this.sourceMesh) {
  55572. return this;
  55573. }
  55574. return this._currentLOD;
  55575. };
  55576. InstancedMesh.prototype._syncSubMeshes = function () {
  55577. this.releaseSubMeshes();
  55578. if (this._sourceMesh.subMeshes) {
  55579. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  55580. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  55581. }
  55582. }
  55583. return this;
  55584. };
  55585. InstancedMesh.prototype._generatePointsArray = function () {
  55586. return this._sourceMesh._generatePointsArray();
  55587. };
  55588. /**
  55589. * Creates a new InstancedMesh from the current mesh.
  55590. * - name (string) : the cloned mesh name
  55591. * - newParent (optional Node) : the optional Node to parent the clone to.
  55592. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  55593. *
  55594. * Returns the clone.
  55595. */
  55596. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55597. var result = this._sourceMesh.createInstance(name);
  55598. // Deep copy
  55599. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  55600. // Bounding info
  55601. this.refreshBoundingInfo();
  55602. // Parent
  55603. if (newParent) {
  55604. result.parent = newParent;
  55605. }
  55606. if (!doNotCloneChildren) {
  55607. // Children
  55608. for (var index = 0; index < this.getScene().meshes.length; index++) {
  55609. var mesh = this.getScene().meshes[index];
  55610. if (mesh.parent === this) {
  55611. mesh.clone(mesh.name, result);
  55612. }
  55613. }
  55614. }
  55615. result.computeWorldMatrix(true);
  55616. return result;
  55617. };
  55618. /**
  55619. * Disposes the InstancedMesh.
  55620. * Returns nothing.
  55621. */
  55622. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  55623. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  55624. // Remove from mesh
  55625. var index = this._sourceMesh.instances.indexOf(this);
  55626. this._sourceMesh.instances.splice(index, 1);
  55627. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  55628. };
  55629. return InstancedMesh;
  55630. }(BABYLON.AbstractMesh));
  55631. BABYLON.InstancedMesh = InstancedMesh;
  55632. })(BABYLON || (BABYLON = {}));
  55633. //# sourceMappingURL=babylon.instancedMesh.js.map
  55634. var BABYLON;
  55635. (function (BABYLON) {
  55636. var LinesMesh = /** @class */ (function (_super) {
  55637. __extends(LinesMesh, _super);
  55638. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  55639. if (scene === void 0) { scene = null; }
  55640. if (parent === void 0) { parent = null; }
  55641. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  55642. _this.useVertexColor = useVertexColor;
  55643. _this.useVertexAlpha = useVertexAlpha;
  55644. _this.color = new BABYLON.Color3(1, 1, 1);
  55645. _this.alpha = 1;
  55646. if (source) {
  55647. _this.color = source.color.clone();
  55648. _this.alpha = source.alpha;
  55649. _this.useVertexColor = source.useVertexColor;
  55650. _this.useVertexAlpha = source.useVertexAlpha;
  55651. }
  55652. _this._intersectionThreshold = 0.1;
  55653. var defines = [];
  55654. var options = {
  55655. attributes: [BABYLON.VertexBuffer.PositionKind],
  55656. uniforms: ["world", "viewProjection"],
  55657. needAlphaBlending: true,
  55658. defines: defines
  55659. };
  55660. if (useVertexAlpha === false) {
  55661. options.needAlphaBlending = false;
  55662. }
  55663. if (!useVertexColor) {
  55664. options.uniforms.push("color");
  55665. }
  55666. else {
  55667. options.defines.push("#define VERTEXCOLOR");
  55668. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  55669. }
  55670. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  55671. return _this;
  55672. }
  55673. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  55674. /**
  55675. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55676. * This margin is expressed in world space coordinates, so its value may vary.
  55677. * Default value is 0.1
  55678. * @returns the intersection Threshold value.
  55679. */
  55680. get: function () {
  55681. return this._intersectionThreshold;
  55682. },
  55683. /**
  55684. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55685. * This margin is expressed in world space coordinates, so its value may vary.
  55686. * @param value the new threshold to apply
  55687. */
  55688. set: function (value) {
  55689. if (this._intersectionThreshold === value) {
  55690. return;
  55691. }
  55692. this._intersectionThreshold = value;
  55693. if (this.geometry) {
  55694. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  55695. }
  55696. },
  55697. enumerable: true,
  55698. configurable: true
  55699. });
  55700. /**
  55701. * Returns the string "LineMesh"
  55702. */
  55703. LinesMesh.prototype.getClassName = function () {
  55704. return "LinesMesh";
  55705. };
  55706. Object.defineProperty(LinesMesh.prototype, "material", {
  55707. get: function () {
  55708. return this._colorShader;
  55709. },
  55710. set: function (value) {
  55711. // Do nothing
  55712. },
  55713. enumerable: true,
  55714. configurable: true
  55715. });
  55716. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  55717. get: function () {
  55718. return false;
  55719. },
  55720. enumerable: true,
  55721. configurable: true
  55722. });
  55723. LinesMesh.prototype.createInstance = function (name) {
  55724. throw new Error("LinesMeshes do not support createInstance.");
  55725. };
  55726. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  55727. if (!this._geometry) {
  55728. return this;
  55729. }
  55730. // VBOs
  55731. this._geometry._bind(this._colorShader.getEffect());
  55732. // Color
  55733. if (!this.useVertexColor) {
  55734. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  55735. }
  55736. return this;
  55737. };
  55738. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  55739. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  55740. return this;
  55741. }
  55742. var engine = this.getScene().getEngine();
  55743. // Draw order
  55744. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  55745. return this;
  55746. };
  55747. LinesMesh.prototype.dispose = function (doNotRecurse) {
  55748. this._colorShader.dispose();
  55749. _super.prototype.dispose.call(this, doNotRecurse);
  55750. };
  55751. /**
  55752. * Returns a new LineMesh object cloned from the current one.
  55753. */
  55754. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55755. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  55756. };
  55757. return LinesMesh;
  55758. }(BABYLON.Mesh));
  55759. BABYLON.LinesMesh = LinesMesh;
  55760. })(BABYLON || (BABYLON = {}));
  55761. //# sourceMappingURL=babylon.linesMesh.js.map
  55762. var BABYLON;
  55763. (function (BABYLON) {
  55764. var MeshBuilder = /** @class */ (function () {
  55765. function MeshBuilder() {
  55766. }
  55767. MeshBuilder.updateSideOrientation = function (orientation) {
  55768. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  55769. return BABYLON.Mesh.DOUBLESIDE;
  55770. }
  55771. if (orientation === undefined || orientation === null) {
  55772. return BABYLON.Mesh.FRONTSIDE;
  55773. }
  55774. return orientation;
  55775. };
  55776. /**
  55777. * Creates a box mesh.
  55778. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  55779. * The parameter `size` sets the size (float) of each box side (default 1).
  55780. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  55781. * 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).
  55782. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55783. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55784. * 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).
  55785. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55786. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55787. */
  55788. MeshBuilder.CreateBox = function (name, options, scene) {
  55789. if (scene === void 0) { scene = null; }
  55790. var box = new BABYLON.Mesh(name, scene);
  55791. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55792. box._originalBuilderSideOrientation = options.sideOrientation;
  55793. var vertexData = BABYLON.VertexData.CreateBox(options);
  55794. vertexData.applyToMesh(box, options.updatable);
  55795. return box;
  55796. };
  55797. /**
  55798. * Creates a sphere mesh.
  55799. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  55800. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  55801. * 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`).
  55802. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  55803. * 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
  55804. * 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).
  55805. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55806. * 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).
  55807. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55808. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55809. */
  55810. MeshBuilder.CreateSphere = function (name, options, scene) {
  55811. var sphere = new BABYLON.Mesh(name, scene);
  55812. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55813. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55814. var vertexData = BABYLON.VertexData.CreateSphere(options);
  55815. vertexData.applyToMesh(sphere, options.updatable);
  55816. return sphere;
  55817. };
  55818. /**
  55819. * Creates a plane polygonal mesh. By default, this is a disc.
  55820. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  55821. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  55822. * 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.
  55823. * 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
  55824. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55825. * 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).
  55826. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55827. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55828. */
  55829. MeshBuilder.CreateDisc = function (name, options, scene) {
  55830. if (scene === void 0) { scene = null; }
  55831. var disc = new BABYLON.Mesh(name, scene);
  55832. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55833. disc._originalBuilderSideOrientation = options.sideOrientation;
  55834. var vertexData = BABYLON.VertexData.CreateDisc(options);
  55835. vertexData.applyToMesh(disc, options.updatable);
  55836. return disc;
  55837. };
  55838. /**
  55839. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  55840. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  55841. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  55842. * 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`).
  55843. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  55844. * 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.
  55845. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55846. * 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).
  55847. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55848. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55849. */
  55850. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  55851. var sphere = new BABYLON.Mesh(name, scene);
  55852. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55853. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55854. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  55855. vertexData.applyToMesh(sphere, options.updatable);
  55856. return sphere;
  55857. };
  55858. ;
  55859. /**
  55860. * Creates a ribbon mesh.
  55861. * 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.
  55862. *
  55863. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  55864. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  55865. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  55866. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  55867. * 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.
  55868. * 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.
  55869. * 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
  55870. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55871. * 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).
  55872. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55873. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55874. * 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.
  55875. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  55876. * 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
  55877. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  55878. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  55879. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55880. */
  55881. MeshBuilder.CreateRibbon = function (name, options, scene) {
  55882. if (scene === void 0) { scene = null; }
  55883. var pathArray = options.pathArray;
  55884. var closeArray = options.closeArray;
  55885. var closePath = options.closePath;
  55886. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55887. var instance = options.instance;
  55888. var updatable = options.updatable;
  55889. if (instance) {
  55890. // positionFunction : ribbon case
  55891. // only pathArray and sideOrientation parameters are taken into account for positions update
  55892. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  55893. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  55894. var positionFunction = function (positions) {
  55895. var minlg = pathArray[0].length;
  55896. var i = 0;
  55897. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  55898. for (var si = 1; si <= ns; si++) {
  55899. for (var p = 0; p < pathArray.length; p++) {
  55900. var path = pathArray[p];
  55901. var l = path.length;
  55902. minlg = (minlg < l) ? minlg : l;
  55903. var j = 0;
  55904. while (j < minlg) {
  55905. positions[i] = path[j].x;
  55906. positions[i + 1] = path[j].y;
  55907. positions[i + 2] = path[j].z;
  55908. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  55909. BABYLON.Tmp.Vector3[0].x = path[j].x;
  55910. }
  55911. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  55912. BABYLON.Tmp.Vector3[1].x = path[j].x;
  55913. }
  55914. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  55915. BABYLON.Tmp.Vector3[0].y = path[j].y;
  55916. }
  55917. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  55918. BABYLON.Tmp.Vector3[1].y = path[j].y;
  55919. }
  55920. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  55921. BABYLON.Tmp.Vector3[0].z = path[j].z;
  55922. }
  55923. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  55924. BABYLON.Tmp.Vector3[1].z = path[j].z;
  55925. }
  55926. j++;
  55927. i += 3;
  55928. }
  55929. if (instance._closePath) {
  55930. positions[i] = path[0].x;
  55931. positions[i + 1] = path[0].y;
  55932. positions[i + 2] = path[0].z;
  55933. i += 3;
  55934. }
  55935. }
  55936. }
  55937. };
  55938. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55939. positionFunction(positions);
  55940. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  55941. instance._boundingInfo.update(instance._worldMatrix);
  55942. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55943. if (options.colors) {
  55944. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55945. for (var c = 0; c < options.colors.length; c++) {
  55946. colors[c * 4] = options.colors[c].r;
  55947. colors[c * 4 + 1] = options.colors[c].g;
  55948. colors[c * 4 + 2] = options.colors[c].b;
  55949. colors[c * 4 + 3] = options.colors[c].a;
  55950. }
  55951. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  55952. }
  55953. if (options.uvs) {
  55954. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55955. for (var i = 0; i < options.uvs.length; i++) {
  55956. uvs[i * 2] = options.uvs[i].x;
  55957. uvs[i * 2 + 1] = options.uvs[i].y;
  55958. }
  55959. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  55960. }
  55961. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  55962. var indices = instance.getIndices();
  55963. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55964. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  55965. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  55966. if (instance._closePath) {
  55967. var indexFirst = 0;
  55968. var indexLast = 0;
  55969. for (var p = 0; p < pathArray.length; p++) {
  55970. indexFirst = instance._idx[p] * 3;
  55971. if (p + 1 < pathArray.length) {
  55972. indexLast = (instance._idx[p + 1] - 1) * 3;
  55973. }
  55974. else {
  55975. indexLast = normals.length - 3;
  55976. }
  55977. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  55978. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  55979. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  55980. normals[indexLast] = normals[indexFirst];
  55981. normals[indexLast + 1] = normals[indexFirst + 1];
  55982. normals[indexLast + 2] = normals[indexFirst + 2];
  55983. }
  55984. }
  55985. if (!(instance.areNormalsFrozen)) {
  55986. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  55987. }
  55988. }
  55989. return instance;
  55990. }
  55991. else {
  55992. var ribbon = new BABYLON.Mesh(name, scene);
  55993. ribbon._originalBuilderSideOrientation = sideOrientation;
  55994. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  55995. if (closePath) {
  55996. ribbon._idx = vertexData._idx;
  55997. }
  55998. ribbon._closePath = closePath;
  55999. ribbon._closeArray = closeArray;
  56000. vertexData.applyToMesh(ribbon, updatable);
  56001. return ribbon;
  56002. }
  56003. };
  56004. /**
  56005. * Creates a cylinder or a cone mesh.
  56006. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  56007. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  56008. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  56009. * 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.
  56010. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  56011. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  56012. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  56013. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  56014. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  56015. * 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).
  56016. * 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
  56017. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  56018. * 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
  56019. * 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.
  56020. * If `enclose` is false, a ring surface is one element.
  56021. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  56022. * 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
  56023. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56024. * 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).
  56025. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56026. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56027. */
  56028. MeshBuilder.CreateCylinder = function (name, options, scene) {
  56029. var cylinder = new BABYLON.Mesh(name, scene);
  56030. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56031. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  56032. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  56033. vertexData.applyToMesh(cylinder, options.updatable);
  56034. return cylinder;
  56035. };
  56036. /**
  56037. * Creates a torus mesh.
  56038. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  56039. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  56040. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  56041. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  56042. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56043. * 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).
  56044. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56045. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56046. */
  56047. MeshBuilder.CreateTorus = function (name, options, scene) {
  56048. var torus = new BABYLON.Mesh(name, scene);
  56049. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56050. torus._originalBuilderSideOrientation = options.sideOrientation;
  56051. var vertexData = BABYLON.VertexData.CreateTorus(options);
  56052. vertexData.applyToMesh(torus, options.updatable);
  56053. return torus;
  56054. };
  56055. /**
  56056. * Creates a torus knot mesh.
  56057. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  56058. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  56059. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  56060. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  56061. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  56062. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56063. * 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).
  56064. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56065. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56066. */
  56067. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  56068. var torusKnot = new BABYLON.Mesh(name, scene);
  56069. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56070. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  56071. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  56072. vertexData.applyToMesh(torusKnot, options.updatable);
  56073. return torusKnot;
  56074. };
  56075. /**
  56076. * Creates a line system mesh.
  56077. * A line system is a pool of many lines gathered in a single mesh.
  56078. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  56079. * 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.
  56080. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  56081. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  56082. * 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
  56083. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  56084. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  56085. * 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
  56086. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  56087. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56088. */
  56089. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  56090. var instance = options.instance;
  56091. var lines = options.lines;
  56092. var colors = options.colors;
  56093. if (instance) {
  56094. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56095. var vertexColor;
  56096. var lineColors;
  56097. if (colors) {
  56098. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56099. }
  56100. var i = 0;
  56101. var c = 0;
  56102. for (var l = 0; l < lines.length; l++) {
  56103. var points = lines[l];
  56104. for (var p = 0; p < points.length; p++) {
  56105. positions[i] = points[p].x;
  56106. positions[i + 1] = points[p].y;
  56107. positions[i + 2] = points[p].z;
  56108. if (colors && vertexColor) {
  56109. lineColors = colors[l];
  56110. vertexColor[c] = lineColors[p].r;
  56111. vertexColor[c + 1] = lineColors[p].g;
  56112. vertexColor[c + 2] = lineColors[p].b;
  56113. vertexColor[c + 3] = lineColors[p].a;
  56114. c += 4;
  56115. }
  56116. i += 3;
  56117. }
  56118. }
  56119. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56120. if (colors && vertexColor) {
  56121. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  56122. }
  56123. return instance;
  56124. }
  56125. // line system creation
  56126. var useVertexColor = (colors) ? true : false;
  56127. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  56128. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  56129. vertexData.applyToMesh(lineSystem, options.updatable);
  56130. return lineSystem;
  56131. };
  56132. /**
  56133. * Creates a line mesh.
  56134. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  56135. * 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.
  56136. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56137. * The parameter `points` is an array successive Vector3.
  56138. * 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
  56139. * The optional parameter `colors` is an array of successive Color4, one per line point.
  56140. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  56141. * When updating an instance, remember that only point positions can change, not the number of points.
  56142. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56143. */
  56144. MeshBuilder.CreateLines = function (name, options, scene) {
  56145. if (scene === void 0) { scene = null; }
  56146. var colors = (options.colors) ? [options.colors] : null;
  56147. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  56148. return lines;
  56149. };
  56150. /**
  56151. * Creates a dashed line mesh.
  56152. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  56153. * 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.
  56154. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56155. * The parameter `points` is an array successive Vector3.
  56156. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  56157. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  56158. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  56159. * 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
  56160. * When updating an instance, remember that only point positions can change, not the number of points.
  56161. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56162. */
  56163. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  56164. if (scene === void 0) { scene = null; }
  56165. var points = options.points;
  56166. var instance = options.instance;
  56167. var gapSize = options.gapSize || 1;
  56168. var dashSize = options.dashSize || 3;
  56169. if (instance) {
  56170. var positionFunction = function (positions) {
  56171. var curvect = BABYLON.Vector3.Zero();
  56172. var nbSeg = positions.length / 6;
  56173. var lg = 0;
  56174. var nb = 0;
  56175. var shft = 0;
  56176. var dashshft = 0;
  56177. var curshft = 0;
  56178. var p = 0;
  56179. var i = 0;
  56180. var j = 0;
  56181. for (i = 0; i < points.length - 1; i++) {
  56182. points[i + 1].subtractToRef(points[i], curvect);
  56183. lg += curvect.length();
  56184. }
  56185. shft = lg / nbSeg;
  56186. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  56187. for (i = 0; i < points.length - 1; i++) {
  56188. points[i + 1].subtractToRef(points[i], curvect);
  56189. nb = Math.floor(curvect.length() / shft);
  56190. curvect.normalize();
  56191. j = 0;
  56192. while (j < nb && p < positions.length) {
  56193. curshft = shft * j;
  56194. positions[p] = points[i].x + curshft * curvect.x;
  56195. positions[p + 1] = points[i].y + curshft * curvect.y;
  56196. positions[p + 2] = points[i].z + curshft * curvect.z;
  56197. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  56198. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  56199. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  56200. p += 6;
  56201. j++;
  56202. }
  56203. }
  56204. while (p < positions.length) {
  56205. positions[p] = points[i].x;
  56206. positions[p + 1] = points[i].y;
  56207. positions[p + 2] = points[i].z;
  56208. p += 3;
  56209. }
  56210. };
  56211. instance.updateMeshPositions(positionFunction, false);
  56212. return instance;
  56213. }
  56214. // dashed lines creation
  56215. var dashedLines = new BABYLON.LinesMesh(name, scene);
  56216. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  56217. vertexData.applyToMesh(dashedLines, options.updatable);
  56218. dashedLines.dashSize = dashSize;
  56219. dashedLines.gapSize = gapSize;
  56220. return dashedLines;
  56221. };
  56222. /**
  56223. * Creates an extruded shape mesh.
  56224. * 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.
  56225. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  56226. *
  56227. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56228. * 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
  56229. * extruded along the Z axis.
  56230. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56231. * 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.
  56232. * The parameter `scale` (float, default 1) is the value to scale the shape.
  56233. * 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
  56234. * 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
  56235. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56236. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56237. * 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).
  56238. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56239. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56240. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56241. */
  56242. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  56243. if (scene === void 0) { scene = null; }
  56244. var path = options.path;
  56245. var shape = options.shape;
  56246. var scale = options.scale || 1;
  56247. var rotation = options.rotation || 0;
  56248. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56249. var updatable = options.updatable;
  56250. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56251. var instance = options.instance || null;
  56252. var invertUV = options.invertUV || false;
  56253. 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);
  56254. };
  56255. /**
  56256. * Creates an custom extruded shape mesh.
  56257. * 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.
  56258. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  56259. *
  56260. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56261. * 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
  56262. * extruded along the Z axis.
  56263. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56264. * 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
  56265. * and the distance of this point from the begining of the path :
  56266. * ```javascript
  56267. * var rotationFunction = function(i, distance) {
  56268. * // do things
  56269. * return rotationValue; }
  56270. * ```
  56271. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  56272. * 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
  56273. * and the distance of this point from the begining of the path :
  56274. * ```javascript
  56275. * var scaleFunction = function(i, distance) {
  56276. * // do things
  56277. * return scaleValue;}
  56278. * ```
  56279. * It must returns a float value that will be the scale value applied to the shape on each path point.
  56280. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  56281. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  56282. * 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
  56283. * 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
  56284. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56285. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56286. * 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).
  56287. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56288. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56289. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56290. */
  56291. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  56292. var path = options.path;
  56293. var shape = options.shape;
  56294. var scaleFunction = options.scaleFunction || (function () { return 1; });
  56295. var rotationFunction = options.rotationFunction || (function () { return 0; });
  56296. var ribbonCloseArray = options.ribbonCloseArray || false;
  56297. var ribbonClosePath = options.ribbonClosePath || false;
  56298. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56299. var updatable = options.updatable;
  56300. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56301. var instance = options.instance;
  56302. var invertUV = options.invertUV || false;
  56303. 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);
  56304. };
  56305. /**
  56306. * Creates lathe mesh.
  56307. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  56308. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  56309. *
  56310. * 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
  56311. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  56312. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  56313. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  56314. * 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.
  56315. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  56316. * 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
  56317. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56318. * 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).
  56319. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56320. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56321. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56322. */
  56323. MeshBuilder.CreateLathe = function (name, options, scene) {
  56324. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  56325. var closed = (options.closed === undefined) ? true : options.closed;
  56326. var shape = options.shape;
  56327. var radius = options.radius || 1;
  56328. var tessellation = options.tessellation || 64;
  56329. var updatable = options.updatable;
  56330. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56331. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56332. var pi2 = Math.PI * 2;
  56333. var paths = new Array();
  56334. var invertUV = options.invertUV || false;
  56335. var i = 0;
  56336. var p = 0;
  56337. var step = pi2 / tessellation * arc;
  56338. var rotated;
  56339. var path = new Array();
  56340. ;
  56341. for (i = 0; i <= tessellation; i++) {
  56342. var path = [];
  56343. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  56344. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  56345. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  56346. }
  56347. for (p = 0; p < shape.length; p++) {
  56348. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  56349. path.push(rotated);
  56350. }
  56351. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  56352. 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));
  56353. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  56354. }
  56355. paths.push(path);
  56356. }
  56357. // lathe ribbon
  56358. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56359. return lathe;
  56360. };
  56361. /**
  56362. * Creates a plane mesh.
  56363. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56364. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  56365. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  56366. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  56367. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56368. * 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).
  56369. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56370. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56371. */
  56372. MeshBuilder.CreatePlane = function (name, options, scene) {
  56373. var plane = new BABYLON.Mesh(name, scene);
  56374. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56375. plane._originalBuilderSideOrientation = options.sideOrientation;
  56376. var vertexData = BABYLON.VertexData.CreatePlane(options);
  56377. vertexData.applyToMesh(plane, options.updatable);
  56378. if (options.sourcePlane) {
  56379. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  56380. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  56381. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  56382. plane.rotate(vectorProduct, product);
  56383. }
  56384. return plane;
  56385. };
  56386. /**
  56387. * Creates a ground mesh.
  56388. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56389. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  56390. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  56391. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56392. */
  56393. MeshBuilder.CreateGround = function (name, options, scene) {
  56394. var ground = new BABYLON.GroundMesh(name, scene);
  56395. ground._setReady(false);
  56396. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  56397. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  56398. ground._width = options.width || 1;
  56399. ground._height = options.height || 1;
  56400. ground._maxX = ground._width / 2;
  56401. ground._maxZ = ground._height / 2;
  56402. ground._minX = -ground._maxX;
  56403. ground._minZ = -ground._maxZ;
  56404. var vertexData = BABYLON.VertexData.CreateGround(options);
  56405. vertexData.applyToMesh(ground, options.updatable);
  56406. ground._setReady(true);
  56407. return ground;
  56408. };
  56409. /**
  56410. * Creates a tiled ground mesh.
  56411. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  56412. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  56413. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  56414. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  56415. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  56416. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  56417. * numbers of subdivisions on the ground width and height of each tile.
  56418. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56419. */
  56420. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  56421. var tiledGround = new BABYLON.Mesh(name, scene);
  56422. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  56423. vertexData.applyToMesh(tiledGround, options.updatable);
  56424. return tiledGround;
  56425. };
  56426. /**
  56427. * Creates a ground mesh from a height map.
  56428. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  56429. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  56430. * The parameter `url` sets the URL of the height map image resource.
  56431. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  56432. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  56433. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  56434. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  56435. * 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.
  56436. * 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).
  56437. * This function is passed the newly built mesh :
  56438. * ```javascript
  56439. * function(mesh) { // do things
  56440. * return; }
  56441. * ```
  56442. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56443. */
  56444. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  56445. var width = options.width || 10.0;
  56446. var height = options.height || 10.0;
  56447. var subdivisions = options.subdivisions || 1 | 0;
  56448. var minHeight = options.minHeight || 0.0;
  56449. var maxHeight = options.maxHeight || 1.0;
  56450. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  56451. var updatable = options.updatable;
  56452. var onReady = options.onReady;
  56453. var ground = new BABYLON.GroundMesh(name, scene);
  56454. ground._subdivisionsX = subdivisions;
  56455. ground._subdivisionsY = subdivisions;
  56456. ground._width = width;
  56457. ground._height = height;
  56458. ground._maxX = ground._width / 2.0;
  56459. ground._maxZ = ground._height / 2.0;
  56460. ground._minX = -ground._maxX;
  56461. ground._minZ = -ground._maxZ;
  56462. ground._setReady(false);
  56463. var onload = function (img) {
  56464. // Getting height map data
  56465. var canvas = document.createElement("canvas");
  56466. var context = canvas.getContext("2d");
  56467. if (!context) {
  56468. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  56469. }
  56470. if (scene.isDisposed) {
  56471. return;
  56472. }
  56473. var bufferWidth = img.width;
  56474. var bufferHeight = img.height;
  56475. canvas.width = bufferWidth;
  56476. canvas.height = bufferHeight;
  56477. context.drawImage(img, 0, 0);
  56478. // Create VertexData from map data
  56479. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  56480. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  56481. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  56482. width: width, height: height,
  56483. subdivisions: subdivisions,
  56484. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  56485. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  56486. });
  56487. vertexData.applyToMesh(ground, updatable);
  56488. ground._setReady(true);
  56489. //execute ready callback, if set
  56490. if (onReady) {
  56491. onReady(ground);
  56492. }
  56493. };
  56494. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  56495. return ground;
  56496. };
  56497. /**
  56498. * Creates a polygon mesh.
  56499. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  56500. * 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.
  56501. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56502. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56503. * 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).
  56504. * Remember you can only change the shape positions, not their number when updating a polygon.
  56505. */
  56506. MeshBuilder.CreatePolygon = function (name, options, scene) {
  56507. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56508. var shape = options.shape;
  56509. var holes = options.holes || [];
  56510. var depth = options.depth || 0;
  56511. var contours = [];
  56512. var hole = [];
  56513. for (var i = 0; i < shape.length; i++) {
  56514. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  56515. }
  56516. var epsilon = 0.00000001;
  56517. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  56518. contours.pop();
  56519. }
  56520. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  56521. for (var hNb = 0; hNb < holes.length; hNb++) {
  56522. hole = [];
  56523. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  56524. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  56525. }
  56526. polygonTriangulation.addHole(hole);
  56527. }
  56528. var polygon = polygonTriangulation.build(options.updatable, depth);
  56529. polygon._originalBuilderSideOrientation = options.sideOrientation;
  56530. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  56531. vertexData.applyToMesh(polygon, options.updatable);
  56532. return polygon;
  56533. };
  56534. ;
  56535. /**
  56536. * Creates an extruded polygon mesh, with depth in the Y direction.
  56537. * 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).
  56538. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56539. */
  56540. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  56541. return MeshBuilder.CreatePolygon(name, options, scene);
  56542. };
  56543. ;
  56544. /**
  56545. * Creates a tube mesh.
  56546. * 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.
  56547. *
  56548. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  56549. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  56550. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  56551. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  56552. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  56553. * 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.
  56554. * It must return a radius value (positive float) :
  56555. * ```javascript
  56556. * var radiusFunction = function(i, distance) {
  56557. * // do things
  56558. * return radius; }
  56559. * ```
  56560. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  56561. * 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
  56562. * 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
  56563. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56564. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  56565. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56566. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56567. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56568. */
  56569. MeshBuilder.CreateTube = function (name, options, scene) {
  56570. var path = options.path;
  56571. var instance = options.instance;
  56572. var radius = 1.0;
  56573. if (instance) {
  56574. radius = instance.radius;
  56575. }
  56576. if (options.radius !== undefined) {
  56577. radius = options.radius;
  56578. }
  56579. ;
  56580. var tessellation = options.tessellation || 64 | 0;
  56581. var radiusFunction = options.radiusFunction || null;
  56582. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56583. var invertUV = options.invertUV || false;
  56584. var updatable = options.updatable;
  56585. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56586. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  56587. // tube geometry
  56588. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  56589. var tangents = path3D.getTangents();
  56590. var normals = path3D.getNormals();
  56591. var distances = path3D.getDistances();
  56592. var pi2 = Math.PI * 2;
  56593. var step = pi2 / tessellation * arc;
  56594. var returnRadius = function () { return radius; };
  56595. var radiusFunctionFinal = radiusFunction || returnRadius;
  56596. var circlePath;
  56597. var rad;
  56598. var normal;
  56599. var rotated;
  56600. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56601. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56602. for (var i = 0; i < path.length; i++) {
  56603. rad = radiusFunctionFinal(i, distances[i]); // current radius
  56604. circlePath = Array(); // current circle array
  56605. normal = normals[i]; // current normal
  56606. for (var t = 0; t < tessellation; t++) {
  56607. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  56608. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  56609. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  56610. rotated.scaleInPlace(rad).addInPlace(path[i]);
  56611. circlePath[t] = rotated;
  56612. }
  56613. circlePaths[index] = circlePath;
  56614. index++;
  56615. }
  56616. // cap
  56617. var capPath = function (nbPoints, pathIndex) {
  56618. var pointCap = Array();
  56619. for (var i = 0; i < nbPoints; i++) {
  56620. pointCap.push(path[pathIndex]);
  56621. }
  56622. return pointCap;
  56623. };
  56624. switch (cap) {
  56625. case BABYLON.Mesh.NO_CAP:
  56626. break;
  56627. case BABYLON.Mesh.CAP_START:
  56628. circlePaths[0] = capPath(tessellation, 0);
  56629. circlePaths[1] = circlePaths[2].slice(0);
  56630. break;
  56631. case BABYLON.Mesh.CAP_END:
  56632. circlePaths[index] = circlePaths[index - 1].slice(0);
  56633. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56634. break;
  56635. case BABYLON.Mesh.CAP_ALL:
  56636. circlePaths[0] = capPath(tessellation, 0);
  56637. circlePaths[1] = circlePaths[2].slice(0);
  56638. circlePaths[index] = circlePaths[index - 1].slice(0);
  56639. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56640. break;
  56641. default:
  56642. break;
  56643. }
  56644. return circlePaths;
  56645. };
  56646. var path3D;
  56647. var pathArray;
  56648. if (instance) {
  56649. var arc = options.arc || instance.arc;
  56650. path3D = (instance.path3D).update(path);
  56651. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  56652. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  56653. instance.path3D = path3D;
  56654. instance.pathArray = pathArray;
  56655. instance.arc = arc;
  56656. instance.radius = radius;
  56657. return instance;
  56658. }
  56659. // tube creation
  56660. path3D = new BABYLON.Path3D(path);
  56661. var newPathArray = new Array();
  56662. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56663. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  56664. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56665. tube.pathArray = pathArray;
  56666. tube.path3D = path3D;
  56667. tube.tessellation = tessellation;
  56668. tube.cap = cap;
  56669. tube.arc = options.arc;
  56670. tube.radius = radius;
  56671. return tube;
  56672. };
  56673. /**
  56674. * Creates a polyhedron mesh.
  56675. *
  56676. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  56677. * 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
  56678. * to choose the wanted type.
  56679. * The parameter `size` (positive float, default 1) sets the polygon size.
  56680. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  56681. * 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`.
  56682. * 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
  56683. * 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)`).
  56684. * 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
  56685. * 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.
  56686. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56687. * 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).
  56688. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56689. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56690. */
  56691. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  56692. var polyhedron = new BABYLON.Mesh(name, scene);
  56693. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56694. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  56695. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  56696. vertexData.applyToMesh(polyhedron, options.updatable);
  56697. return polyhedron;
  56698. };
  56699. /**
  56700. * Creates a decal mesh.
  56701. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  56702. * 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.
  56703. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  56704. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  56705. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  56706. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  56707. */
  56708. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  56709. var indices = sourceMesh.getIndices();
  56710. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56711. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56712. var position = options.position || BABYLON.Vector3.Zero();
  56713. var normal = options.normal || BABYLON.Vector3.Up();
  56714. var size = options.size || BABYLON.Vector3.One();
  56715. var angle = options.angle || 0;
  56716. // Getting correct rotation
  56717. if (!normal) {
  56718. var target = new BABYLON.Vector3(0, 0, 1);
  56719. var camera = sourceMesh.getScene().activeCamera;
  56720. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  56721. normal = camera.globalPosition.subtract(cameraWorldTarget);
  56722. }
  56723. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  56724. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  56725. var pitch = Math.atan2(normal.y, len);
  56726. // Matrix
  56727. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  56728. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  56729. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  56730. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  56731. var vertexData = new BABYLON.VertexData();
  56732. vertexData.indices = [];
  56733. vertexData.positions = [];
  56734. vertexData.normals = [];
  56735. vertexData.uvs = [];
  56736. var currentVertexDataIndex = 0;
  56737. var extractDecalVector3 = function (indexId) {
  56738. var result = new BABYLON.PositionNormalVertex();
  56739. if (!indices || !positions || !normals) {
  56740. return result;
  56741. }
  56742. var vertexId = indices[indexId];
  56743. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  56744. // Send vector to decal local world
  56745. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  56746. // Get normal
  56747. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  56748. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  56749. return result;
  56750. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  56751. var clip = function (vertices, axis) {
  56752. if (vertices.length === 0) {
  56753. return vertices;
  56754. }
  56755. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  56756. var clipVertices = function (v0, v1) {
  56757. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  56758. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  56759. };
  56760. var result = new Array();
  56761. for (var index = 0; index < vertices.length; index += 3) {
  56762. var v1Out;
  56763. var v2Out;
  56764. var v3Out;
  56765. var total = 0;
  56766. var nV1 = null;
  56767. var nV2 = null;
  56768. var nV3 = null;
  56769. var nV4 = null;
  56770. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  56771. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  56772. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  56773. v1Out = d1 > 0;
  56774. v2Out = d2 > 0;
  56775. v3Out = d3 > 0;
  56776. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  56777. switch (total) {
  56778. case 0:
  56779. result.push(vertices[index]);
  56780. result.push(vertices[index + 1]);
  56781. result.push(vertices[index + 2]);
  56782. break;
  56783. case 1:
  56784. if (v1Out) {
  56785. nV1 = vertices[index + 1];
  56786. nV2 = vertices[index + 2];
  56787. nV3 = clipVertices(vertices[index], nV1);
  56788. nV4 = clipVertices(vertices[index], nV2);
  56789. }
  56790. if (v2Out) {
  56791. nV1 = vertices[index];
  56792. nV2 = vertices[index + 2];
  56793. nV3 = clipVertices(vertices[index + 1], nV1);
  56794. nV4 = clipVertices(vertices[index + 1], nV2);
  56795. result.push(nV3);
  56796. result.push(nV2.clone());
  56797. result.push(nV1.clone());
  56798. result.push(nV2.clone());
  56799. result.push(nV3.clone());
  56800. result.push(nV4);
  56801. break;
  56802. }
  56803. if (v3Out) {
  56804. nV1 = vertices[index];
  56805. nV2 = vertices[index + 1];
  56806. nV3 = clipVertices(vertices[index + 2], nV1);
  56807. nV4 = clipVertices(vertices[index + 2], nV2);
  56808. }
  56809. if (nV1 && nV2 && nV3 && nV4) {
  56810. result.push(nV1.clone());
  56811. result.push(nV2.clone());
  56812. result.push(nV3);
  56813. result.push(nV4);
  56814. result.push(nV3.clone());
  56815. result.push(nV2.clone());
  56816. }
  56817. break;
  56818. case 2:
  56819. if (!v1Out) {
  56820. nV1 = vertices[index].clone();
  56821. nV2 = clipVertices(nV1, vertices[index + 1]);
  56822. nV3 = clipVertices(nV1, vertices[index + 2]);
  56823. result.push(nV1);
  56824. result.push(nV2);
  56825. result.push(nV3);
  56826. }
  56827. if (!v2Out) {
  56828. nV1 = vertices[index + 1].clone();
  56829. nV2 = clipVertices(nV1, vertices[index + 2]);
  56830. nV3 = clipVertices(nV1, vertices[index]);
  56831. result.push(nV1);
  56832. result.push(nV2);
  56833. result.push(nV3);
  56834. }
  56835. if (!v3Out) {
  56836. nV1 = vertices[index + 2].clone();
  56837. nV2 = clipVertices(nV1, vertices[index]);
  56838. nV3 = clipVertices(nV1, vertices[index + 1]);
  56839. result.push(nV1);
  56840. result.push(nV2);
  56841. result.push(nV3);
  56842. }
  56843. break;
  56844. case 3:
  56845. break;
  56846. }
  56847. }
  56848. return result;
  56849. };
  56850. for (var index = 0; index < indices.length; index += 3) {
  56851. var faceVertices = new Array();
  56852. faceVertices.push(extractDecalVector3(index));
  56853. faceVertices.push(extractDecalVector3(index + 1));
  56854. faceVertices.push(extractDecalVector3(index + 2));
  56855. // Clip
  56856. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  56857. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  56858. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  56859. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  56860. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  56861. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  56862. if (faceVertices.length === 0) {
  56863. continue;
  56864. }
  56865. // Add UVs and get back to world
  56866. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  56867. var vertex = faceVertices[vIndex];
  56868. //TODO check for Int32Array | Uint32Array | Uint16Array
  56869. vertexData.indices.push(currentVertexDataIndex);
  56870. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  56871. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  56872. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  56873. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  56874. currentVertexDataIndex++;
  56875. }
  56876. }
  56877. // Return mesh
  56878. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  56879. vertexData.applyToMesh(decal);
  56880. decal.position = position.clone();
  56881. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  56882. return decal;
  56883. };
  56884. // Privates
  56885. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  56886. // extrusion geometry
  56887. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  56888. var tangents = path3D.getTangents();
  56889. var normals = path3D.getNormals();
  56890. var binormals = path3D.getBinormals();
  56891. var distances = path3D.getDistances();
  56892. var angle = 0;
  56893. var returnScale = function () { return scale !== null ? scale : 1; };
  56894. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  56895. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  56896. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  56897. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56898. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56899. for (var i = 0; i < curve.length; i++) {
  56900. var shapePath = new Array();
  56901. var angleStep = rotate(i, distances[i]);
  56902. var scaleRatio = scl(i, distances[i]);
  56903. for (var p = 0; p < shape.length; p++) {
  56904. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  56905. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  56906. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  56907. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  56908. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  56909. shapePath[p] = rotated;
  56910. }
  56911. shapePaths[index] = shapePath;
  56912. angle += angleStep;
  56913. index++;
  56914. }
  56915. // cap
  56916. var capPath = function (shapePath) {
  56917. var pointCap = Array();
  56918. var barycenter = BABYLON.Vector3.Zero();
  56919. var i;
  56920. for (i = 0; i < shapePath.length; i++) {
  56921. barycenter.addInPlace(shapePath[i]);
  56922. }
  56923. barycenter.scaleInPlace(1.0 / shapePath.length);
  56924. for (i = 0; i < shapePath.length; i++) {
  56925. pointCap.push(barycenter);
  56926. }
  56927. return pointCap;
  56928. };
  56929. switch (cap) {
  56930. case BABYLON.Mesh.NO_CAP:
  56931. break;
  56932. case BABYLON.Mesh.CAP_START:
  56933. shapePaths[0] = capPath(shapePaths[2]);
  56934. shapePaths[1] = shapePaths[2];
  56935. break;
  56936. case BABYLON.Mesh.CAP_END:
  56937. shapePaths[index] = shapePaths[index - 1];
  56938. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56939. break;
  56940. case BABYLON.Mesh.CAP_ALL:
  56941. shapePaths[0] = capPath(shapePaths[2]);
  56942. shapePaths[1] = shapePaths[2];
  56943. shapePaths[index] = shapePaths[index - 1];
  56944. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56945. break;
  56946. default:
  56947. break;
  56948. }
  56949. return shapePaths;
  56950. };
  56951. var path3D;
  56952. var pathArray;
  56953. if (instance) {
  56954. path3D = (instance.path3D).update(curve);
  56955. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  56956. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  56957. return instance;
  56958. }
  56959. // extruded shape creation
  56960. path3D = new BABYLON.Path3D(curve);
  56961. var newShapePaths = new Array();
  56962. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56963. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  56964. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  56965. extrudedGeneric.pathArray = pathArray;
  56966. extrudedGeneric.path3D = path3D;
  56967. extrudedGeneric.cap = cap;
  56968. return extrudedGeneric;
  56969. };
  56970. return MeshBuilder;
  56971. }());
  56972. BABYLON.MeshBuilder = MeshBuilder;
  56973. })(BABYLON || (BABYLON = {}));
  56974. //# sourceMappingURL=babylon.meshBuilder.js.map
  56975. var BABYLON;
  56976. (function (BABYLON) {
  56977. /**
  56978. * Draco compression (https://google.github.io/draco/)
  56979. */
  56980. var DracoCompression = /** @class */ (function () {
  56981. /**
  56982. * Constructor
  56983. * @param numWorkers The number of workers for async operations
  56984. */
  56985. function DracoCompression(numWorkers) {
  56986. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  56987. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  56988. if (!workerBlobUrl || !Worker) {
  56989. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  56990. return;
  56991. }
  56992. var workers = new Array(numWorkers);
  56993. for (var i = 0; i < workers.length; i++) {
  56994. var worker = new Worker(workerBlobUrl);
  56995. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  56996. workers[i] = worker;
  56997. }
  56998. this._workerPool = new BABYLON.WorkerPool(workers);
  56999. }
  57000. /**
  57001. * Stop all async operations and release resources.
  57002. */
  57003. DracoCompression.prototype.dispose = function () {
  57004. this._workerPool.dispose();
  57005. delete this._workerPool;
  57006. };
  57007. /**
  57008. * Decode Draco compressed mesh data to vertex data.
  57009. * @param data The array buffer view for the Draco compression data
  57010. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  57011. * @returns A promise that resolves with the decoded vertex data
  57012. */
  57013. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  57014. var _this = this;
  57015. return new Promise(function (resolve, reject) {
  57016. _this._workerPool.push(function (worker, onComplete) {
  57017. var vertexData = new BABYLON.VertexData();
  57018. var onError = function (error) {
  57019. worker.removeEventListener("error", onError);
  57020. worker.removeEventListener("message", onMessage);
  57021. reject(error);
  57022. onComplete();
  57023. };
  57024. var onMessage = function (message) {
  57025. if (message.data === "done") {
  57026. worker.removeEventListener("error", onError);
  57027. worker.removeEventListener("message", onMessage);
  57028. resolve(vertexData);
  57029. onComplete();
  57030. }
  57031. else if (message.data.id === "indices") {
  57032. vertexData.indices = message.data.value;
  57033. }
  57034. else {
  57035. vertexData.set(message.data.value, message.data.id);
  57036. }
  57037. };
  57038. worker.addEventListener("error", onError);
  57039. worker.addEventListener("message", onMessage);
  57040. var dataCopy = new Uint8Array(data.byteLength);
  57041. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  57042. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  57043. });
  57044. });
  57045. };
  57046. /**
  57047. * The worker function that gets converted to a blob url to pass into a worker.
  57048. */
  57049. DracoCompression._Worker = function () {
  57050. // self is actually a DedicatedWorkerGlobalScope
  57051. var _self = self;
  57052. var decodeMesh = function (data, attributes) {
  57053. var dracoModule = new DracoDecoderModule();
  57054. var buffer = new dracoModule.DecoderBuffer();
  57055. buffer.Init(data, data.byteLength);
  57056. var decoder = new dracoModule.Decoder();
  57057. var geometry;
  57058. var status;
  57059. try {
  57060. var type = decoder.GetEncodedGeometryType(buffer);
  57061. switch (type) {
  57062. case dracoModule.TRIANGULAR_MESH:
  57063. geometry = new dracoModule.Mesh();
  57064. status = decoder.DecodeBufferToMesh(buffer, geometry);
  57065. break;
  57066. case dracoModule.POINT_CLOUD:
  57067. geometry = new dracoModule.PointCloud();
  57068. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  57069. break;
  57070. default:
  57071. throw new Error("Invalid geometry type " + type);
  57072. }
  57073. if (!status.ok() || !geometry.ptr) {
  57074. throw new Error(status.error_msg());
  57075. }
  57076. var numPoints = geometry.num_points();
  57077. if (type === dracoModule.TRIANGULAR_MESH) {
  57078. var numFaces = geometry.num_faces();
  57079. var faceIndices = new dracoModule.DracoInt32Array();
  57080. try {
  57081. var indices = new Uint32Array(numFaces * 3);
  57082. for (var i = 0; i < numFaces; i++) {
  57083. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  57084. var offset = i * 3;
  57085. indices[offset + 0] = faceIndices.GetValue(0);
  57086. indices[offset + 1] = faceIndices.GetValue(1);
  57087. indices[offset + 2] = faceIndices.GetValue(2);
  57088. }
  57089. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  57090. }
  57091. finally {
  57092. dracoModule.destroy(faceIndices);
  57093. }
  57094. }
  57095. for (var kind in attributes) {
  57096. var uniqueId = attributes[kind];
  57097. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  57098. var dracoData = new dracoModule.DracoFloat32Array();
  57099. try {
  57100. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  57101. var babylonData = new Float32Array(numPoints * attribute.num_components());
  57102. for (var i = 0; i < babylonData.length; i++) {
  57103. babylonData[i] = dracoData.GetValue(i);
  57104. }
  57105. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  57106. }
  57107. finally {
  57108. dracoModule.destroy(dracoData);
  57109. }
  57110. }
  57111. }
  57112. finally {
  57113. if (geometry) {
  57114. dracoModule.destroy(geometry);
  57115. }
  57116. dracoModule.destroy(decoder);
  57117. dracoModule.destroy(buffer);
  57118. }
  57119. _self.postMessage("done");
  57120. };
  57121. _self.onmessage = function (event) {
  57122. switch (event.data.id) {
  57123. case "initDecoder": {
  57124. importScripts(event.data.url);
  57125. break;
  57126. }
  57127. case "decodeMesh": {
  57128. decodeMesh(event.data.data, event.data.attributes);
  57129. break;
  57130. }
  57131. }
  57132. };
  57133. };
  57134. DracoCompression._GetDefaultDecoderUrl = function () {
  57135. if (!BABYLON.Tools.IsWindowObjectExist) {
  57136. return null;
  57137. }
  57138. for (var i = 0; i < document.scripts.length; i++) {
  57139. if (document.scripts[i].type === "text/x-draco-decoder") {
  57140. return document.scripts[i].src;
  57141. }
  57142. }
  57143. return null;
  57144. };
  57145. /**
  57146. * Gets the url to the draco decoder if available.
  57147. */
  57148. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  57149. return DracoCompression;
  57150. }());
  57151. BABYLON.DracoCompression = DracoCompression;
  57152. })(BABYLON || (BABYLON = {}));
  57153. //# sourceMappingURL=babylon.dracoCompression.js.map
  57154. var BABYLON;
  57155. (function (BABYLON) {
  57156. var AudioEngine = /** @class */ (function () {
  57157. function AudioEngine() {
  57158. this._audioContext = null;
  57159. this._audioContextInitialized = false;
  57160. this.canUseWebAudio = false;
  57161. this.WarnedWebAudioUnsupported = false;
  57162. this.unlocked = false;
  57163. this.isMP3supported = false;
  57164. this.isOGGsupported = false;
  57165. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  57166. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  57167. this.canUseWebAudio = true;
  57168. }
  57169. var audioElem = document.createElement('audio');
  57170. try {
  57171. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  57172. this.isMP3supported = true;
  57173. }
  57174. }
  57175. catch (e) {
  57176. // protect error during capability check.
  57177. }
  57178. try {
  57179. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  57180. this.isOGGsupported = true;
  57181. }
  57182. }
  57183. catch (e) {
  57184. // protect error during capability check.
  57185. }
  57186. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  57187. this._unlockiOSaudio();
  57188. }
  57189. else {
  57190. this.unlocked = true;
  57191. }
  57192. }
  57193. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  57194. get: function () {
  57195. if (!this._audioContextInitialized) {
  57196. this._initializeAudioContext();
  57197. }
  57198. return this._audioContext;
  57199. },
  57200. enumerable: true,
  57201. configurable: true
  57202. });
  57203. AudioEngine.prototype._unlockiOSaudio = function () {
  57204. var _this = this;
  57205. var unlockaudio = function () {
  57206. if (!_this.audioContext) {
  57207. return;
  57208. }
  57209. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  57210. var source = _this.audioContext.createBufferSource();
  57211. source.buffer = buffer;
  57212. source.connect(_this.audioContext.destination);
  57213. source.start(0);
  57214. setTimeout(function () {
  57215. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  57216. _this.unlocked = true;
  57217. window.removeEventListener('touchend', unlockaudio, false);
  57218. if (_this.onAudioUnlocked) {
  57219. _this.onAudioUnlocked();
  57220. }
  57221. }
  57222. }, 0);
  57223. };
  57224. window.addEventListener('touchend', unlockaudio, false);
  57225. };
  57226. AudioEngine.prototype._initializeAudioContext = function () {
  57227. try {
  57228. if (this.canUseWebAudio) {
  57229. this._audioContext = new AudioContext();
  57230. // create a global volume gain node
  57231. this.masterGain = this._audioContext.createGain();
  57232. this.masterGain.gain.value = 1;
  57233. this.masterGain.connect(this._audioContext.destination);
  57234. this._audioContextInitialized = true;
  57235. }
  57236. }
  57237. catch (e) {
  57238. this.canUseWebAudio = false;
  57239. BABYLON.Tools.Error("Web Audio: " + e.message);
  57240. }
  57241. };
  57242. AudioEngine.prototype.dispose = function () {
  57243. if (this.canUseWebAudio && this._audioContextInitialized) {
  57244. if (this._connectedAnalyser && this._audioContext) {
  57245. this._connectedAnalyser.stopDebugCanvas();
  57246. this._connectedAnalyser.dispose();
  57247. this.masterGain.disconnect();
  57248. this.masterGain.connect(this._audioContext.destination);
  57249. this._connectedAnalyser = null;
  57250. }
  57251. this.masterGain.gain.value = 1;
  57252. }
  57253. this.WarnedWebAudioUnsupported = false;
  57254. };
  57255. AudioEngine.prototype.getGlobalVolume = function () {
  57256. if (this.canUseWebAudio && this._audioContextInitialized) {
  57257. return this.masterGain.gain.value;
  57258. }
  57259. else {
  57260. return -1;
  57261. }
  57262. };
  57263. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  57264. if (this.canUseWebAudio && this._audioContextInitialized) {
  57265. this.masterGain.gain.value = newVolume;
  57266. }
  57267. };
  57268. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  57269. if (this._connectedAnalyser) {
  57270. this._connectedAnalyser.stopDebugCanvas();
  57271. }
  57272. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  57273. this._connectedAnalyser = analyser;
  57274. this.masterGain.disconnect();
  57275. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  57276. }
  57277. };
  57278. return AudioEngine;
  57279. }());
  57280. BABYLON.AudioEngine = AudioEngine;
  57281. })(BABYLON || (BABYLON = {}));
  57282. //# sourceMappingURL=babylon.audioEngine.js.map
  57283. var BABYLON;
  57284. (function (BABYLON) {
  57285. var Sound = /** @class */ (function () {
  57286. /**
  57287. * Create a sound and attach it to a scene
  57288. * @param name Name of your sound
  57289. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  57290. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  57291. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  57292. */
  57293. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  57294. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  57295. var _this = this;
  57296. this.autoplay = false;
  57297. this.loop = false;
  57298. this.useCustomAttenuation = false;
  57299. this.spatialSound = false;
  57300. this.refDistance = 1;
  57301. this.rolloffFactor = 1;
  57302. this.maxDistance = 100;
  57303. this.distanceModel = "linear";
  57304. this._panningModel = "equalpower";
  57305. this._playbackRate = 1;
  57306. this._streaming = false;
  57307. this._startTime = 0;
  57308. this._startOffset = 0;
  57309. this._position = BABYLON.Vector3.Zero();
  57310. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  57311. this._volume = 1;
  57312. this._isReadyToPlay = false;
  57313. this.isPlaying = false;
  57314. this.isPaused = false;
  57315. this._isDirectional = false;
  57316. // Used if you'd like to create a directional sound.
  57317. // If not set, the sound will be omnidirectional
  57318. this._coneInnerAngle = 360;
  57319. this._coneOuterAngle = 360;
  57320. this._coneOuterGain = 0;
  57321. this._isOutputConnected = false;
  57322. this._urlType = "Unknown";
  57323. this.name = name;
  57324. this._scene = scene;
  57325. this._readyToPlayCallback = readyToPlayCallback;
  57326. // Default custom attenuation function is a linear attenuation
  57327. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  57328. if (currentDistance < maxDistance) {
  57329. return currentVolume * (1 - currentDistance / maxDistance);
  57330. }
  57331. else {
  57332. return 0;
  57333. }
  57334. };
  57335. if (options) {
  57336. this.autoplay = options.autoplay || false;
  57337. this.loop = options.loop || false;
  57338. // if volume === 0, we need another way to check this option
  57339. if (options.volume !== undefined) {
  57340. this._volume = options.volume;
  57341. }
  57342. this.spatialSound = options.spatialSound || false;
  57343. this.maxDistance = options.maxDistance || 100;
  57344. this.useCustomAttenuation = options.useCustomAttenuation || false;
  57345. this.rolloffFactor = options.rolloffFactor || 1;
  57346. this.refDistance = options.refDistance || 1;
  57347. this.distanceModel = options.distanceModel || "linear";
  57348. this._playbackRate = options.playbackRate || 1;
  57349. this._streaming = options.streaming || false;
  57350. }
  57351. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57352. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  57353. this._soundGain.gain.value = this._volume;
  57354. this._inputAudioNode = this._soundGain;
  57355. this._ouputAudioNode = this._soundGain;
  57356. if (this.spatialSound) {
  57357. this._createSpatialParameters();
  57358. }
  57359. this._scene.mainSoundTrack.AddSound(this);
  57360. var validParameter = true;
  57361. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  57362. if (urlOrArrayBuffer) {
  57363. if (typeof (urlOrArrayBuffer) === "string")
  57364. this._urlType = "String";
  57365. if (Array.isArray(urlOrArrayBuffer))
  57366. this._urlType = "Array";
  57367. if (urlOrArrayBuffer instanceof ArrayBuffer)
  57368. this._urlType = "ArrayBuffer";
  57369. var urls = [];
  57370. var codecSupportedFound = false;
  57371. switch (this._urlType) {
  57372. case "ArrayBuffer":
  57373. if (urlOrArrayBuffer.byteLength > 0) {
  57374. codecSupportedFound = true;
  57375. this._soundLoaded(urlOrArrayBuffer);
  57376. }
  57377. break;
  57378. case "String":
  57379. urls.push(urlOrArrayBuffer);
  57380. case "Array":
  57381. if (urls.length === 0)
  57382. urls = urlOrArrayBuffer;
  57383. // If we found a supported format, we load it immediately and stop the loop
  57384. for (var i = 0; i < urls.length; i++) {
  57385. var url = urls[i];
  57386. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  57387. codecSupportedFound = true;
  57388. }
  57389. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  57390. codecSupportedFound = true;
  57391. }
  57392. if (url.indexOf(".wav", url.length - 4) !== -1) {
  57393. codecSupportedFound = true;
  57394. }
  57395. if (url.indexOf("blob:") !== -1) {
  57396. codecSupportedFound = true;
  57397. }
  57398. if (codecSupportedFound) {
  57399. // Loading sound using XHR2
  57400. if (!this._streaming) {
  57401. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  57402. }
  57403. else {
  57404. this._htmlAudioElement = new Audio(url);
  57405. this._htmlAudioElement.controls = false;
  57406. this._htmlAudioElement.loop = this.loop;
  57407. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  57408. this._htmlAudioElement.preload = "auto";
  57409. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  57410. _this._isReadyToPlay = true;
  57411. if (_this.autoplay) {
  57412. _this.play();
  57413. }
  57414. if (_this._readyToPlayCallback) {
  57415. _this._readyToPlayCallback();
  57416. }
  57417. });
  57418. document.body.appendChild(this._htmlAudioElement);
  57419. }
  57420. break;
  57421. }
  57422. }
  57423. break;
  57424. default:
  57425. validParameter = false;
  57426. break;
  57427. }
  57428. if (!validParameter) {
  57429. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  57430. }
  57431. else {
  57432. if (!codecSupportedFound) {
  57433. this._isReadyToPlay = true;
  57434. // Simulating a ready to play event to avoid breaking code path
  57435. if (this._readyToPlayCallback) {
  57436. window.setTimeout(function () {
  57437. if (_this._readyToPlayCallback) {
  57438. _this._readyToPlayCallback();
  57439. }
  57440. }, 1000);
  57441. }
  57442. }
  57443. }
  57444. }
  57445. }
  57446. else {
  57447. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  57448. this._scene.mainSoundTrack.AddSound(this);
  57449. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  57450. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  57451. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  57452. }
  57453. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  57454. if (this._readyToPlayCallback) {
  57455. window.setTimeout(function () {
  57456. if (_this._readyToPlayCallback) {
  57457. _this._readyToPlayCallback();
  57458. }
  57459. }, 1000);
  57460. }
  57461. }
  57462. }
  57463. Sound.prototype.dispose = function () {
  57464. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  57465. if (this.isPlaying) {
  57466. this.stop();
  57467. }
  57468. this._isReadyToPlay = false;
  57469. if (this.soundTrackId === -1) {
  57470. this._scene.mainSoundTrack.RemoveSound(this);
  57471. }
  57472. else {
  57473. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  57474. }
  57475. if (this._soundGain) {
  57476. this._soundGain.disconnect();
  57477. this._soundGain = null;
  57478. }
  57479. if (this._soundPanner) {
  57480. this._soundPanner.disconnect();
  57481. this._soundPanner = null;
  57482. }
  57483. if (this._soundSource) {
  57484. this._soundSource.disconnect();
  57485. this._soundSource = null;
  57486. }
  57487. this._audioBuffer = null;
  57488. if (this._htmlAudioElement) {
  57489. this._htmlAudioElement.pause();
  57490. this._htmlAudioElement.src = "";
  57491. document.body.removeChild(this._htmlAudioElement);
  57492. }
  57493. if (this._connectedMesh && this._registerFunc) {
  57494. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57495. this._connectedMesh = null;
  57496. }
  57497. }
  57498. };
  57499. Sound.prototype.isReady = function () {
  57500. return this._isReadyToPlay;
  57501. };
  57502. Sound.prototype._soundLoaded = function (audioData) {
  57503. var _this = this;
  57504. if (!BABYLON.Engine.audioEngine.audioContext) {
  57505. return;
  57506. }
  57507. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  57508. _this._audioBuffer = buffer;
  57509. _this._isReadyToPlay = true;
  57510. if (_this.autoplay) {
  57511. _this.play();
  57512. }
  57513. if (_this._readyToPlayCallback) {
  57514. _this._readyToPlayCallback();
  57515. }
  57516. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  57517. };
  57518. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  57519. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57520. this._audioBuffer = audioBuffer;
  57521. this._isReadyToPlay = true;
  57522. }
  57523. };
  57524. Sound.prototype.updateOptions = function (options) {
  57525. if (options) {
  57526. this.loop = options.loop || this.loop;
  57527. this.maxDistance = options.maxDistance || this.maxDistance;
  57528. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  57529. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  57530. this.refDistance = options.refDistance || this.refDistance;
  57531. this.distanceModel = options.distanceModel || this.distanceModel;
  57532. this._playbackRate = options.playbackRate || this._playbackRate;
  57533. this._updateSpatialParameters();
  57534. if (this.isPlaying) {
  57535. if (this._streaming) {
  57536. this._htmlAudioElement.playbackRate = this._playbackRate;
  57537. }
  57538. else {
  57539. if (this._soundSource) {
  57540. this._soundSource.playbackRate.value = this._playbackRate;
  57541. }
  57542. }
  57543. }
  57544. }
  57545. };
  57546. Sound.prototype._createSpatialParameters = function () {
  57547. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57548. if (this._scene.headphone) {
  57549. this._panningModel = "HRTF";
  57550. }
  57551. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  57552. this._updateSpatialParameters();
  57553. this._soundPanner.connect(this._ouputAudioNode);
  57554. this._inputAudioNode = this._soundPanner;
  57555. }
  57556. };
  57557. Sound.prototype._updateSpatialParameters = function () {
  57558. if (this.spatialSound && this._soundPanner) {
  57559. if (this.useCustomAttenuation) {
  57560. // Tricks to disable in a way embedded Web Audio attenuation
  57561. this._soundPanner.distanceModel = "linear";
  57562. this._soundPanner.maxDistance = Number.MAX_VALUE;
  57563. this._soundPanner.refDistance = 1;
  57564. this._soundPanner.rolloffFactor = 1;
  57565. this._soundPanner.panningModel = this._panningModel;
  57566. }
  57567. else {
  57568. this._soundPanner.distanceModel = this.distanceModel;
  57569. this._soundPanner.maxDistance = this.maxDistance;
  57570. this._soundPanner.refDistance = this.refDistance;
  57571. this._soundPanner.rolloffFactor = this.rolloffFactor;
  57572. this._soundPanner.panningModel = this._panningModel;
  57573. }
  57574. }
  57575. };
  57576. Sound.prototype.switchPanningModelToHRTF = function () {
  57577. this._panningModel = "HRTF";
  57578. this._switchPanningModel();
  57579. };
  57580. Sound.prototype.switchPanningModelToEqualPower = function () {
  57581. this._panningModel = "equalpower";
  57582. this._switchPanningModel();
  57583. };
  57584. Sound.prototype._switchPanningModel = function () {
  57585. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57586. this._soundPanner.panningModel = this._panningModel;
  57587. }
  57588. };
  57589. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  57590. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57591. if (this._isOutputConnected) {
  57592. this._ouputAudioNode.disconnect();
  57593. }
  57594. this._ouputAudioNode.connect(soundTrackAudioNode);
  57595. this._isOutputConnected = true;
  57596. }
  57597. };
  57598. /**
  57599. * Transform this sound into a directional source
  57600. * @param coneInnerAngle Size of the inner cone in degree
  57601. * @param coneOuterAngle Size of the outer cone in degree
  57602. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  57603. */
  57604. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  57605. if (coneOuterAngle < coneInnerAngle) {
  57606. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  57607. return;
  57608. }
  57609. this._coneInnerAngle = coneInnerAngle;
  57610. this._coneOuterAngle = coneOuterAngle;
  57611. this._coneOuterGain = coneOuterGain;
  57612. this._isDirectional = true;
  57613. if (this.isPlaying && this.loop) {
  57614. this.stop();
  57615. this.play();
  57616. }
  57617. };
  57618. Sound.prototype.setPosition = function (newPosition) {
  57619. this._position = newPosition;
  57620. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57621. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57622. }
  57623. };
  57624. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  57625. this._localDirection = newLocalDirection;
  57626. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  57627. this._updateDirection();
  57628. }
  57629. };
  57630. Sound.prototype._updateDirection = function () {
  57631. if (!this._connectedMesh || !this._soundPanner) {
  57632. return;
  57633. }
  57634. var mat = this._connectedMesh.getWorldMatrix();
  57635. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  57636. direction.normalize();
  57637. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  57638. };
  57639. Sound.prototype.updateDistanceFromListener = function () {
  57640. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  57641. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  57642. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  57643. }
  57644. };
  57645. Sound.prototype.setAttenuationFunction = function (callback) {
  57646. this._customAttenuationFunction = callback;
  57647. };
  57648. /**
  57649. * Play the sound
  57650. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  57651. * @param offset (optional) Start the sound setting it at a specific time
  57652. */
  57653. Sound.prototype.play = function (time, offset) {
  57654. var _this = this;
  57655. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  57656. try {
  57657. if (this._startOffset < 0) {
  57658. time = -this._startOffset;
  57659. this._startOffset = 0;
  57660. }
  57661. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57662. if (!this._soundSource || !this._streamingSource) {
  57663. if (this.spatialSound && this._soundPanner) {
  57664. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57665. if (this._isDirectional) {
  57666. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  57667. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  57668. this._soundPanner.coneOuterGain = this._coneOuterGain;
  57669. if (this._connectedMesh) {
  57670. this._updateDirection();
  57671. }
  57672. else {
  57673. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  57674. }
  57675. }
  57676. }
  57677. }
  57678. if (this._streaming) {
  57679. if (!this._streamingSource) {
  57680. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  57681. this._htmlAudioElement.onended = function () { _this._onended(); };
  57682. this._htmlAudioElement.playbackRate = this._playbackRate;
  57683. }
  57684. this._streamingSource.disconnect();
  57685. this._streamingSource.connect(this._inputAudioNode);
  57686. this._htmlAudioElement.play();
  57687. }
  57688. else {
  57689. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  57690. this._soundSource.buffer = this._audioBuffer;
  57691. this._soundSource.connect(this._inputAudioNode);
  57692. this._soundSource.loop = this.loop;
  57693. this._soundSource.playbackRate.value = this._playbackRate;
  57694. this._soundSource.onended = function () { _this._onended(); };
  57695. if (this._soundSource.buffer) {
  57696. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  57697. }
  57698. }
  57699. this._startTime = startTime;
  57700. this.isPlaying = true;
  57701. this.isPaused = false;
  57702. }
  57703. catch (ex) {
  57704. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  57705. }
  57706. }
  57707. };
  57708. Sound.prototype._onended = function () {
  57709. this.isPlaying = false;
  57710. if (this.onended) {
  57711. this.onended();
  57712. }
  57713. };
  57714. /**
  57715. * Stop the sound
  57716. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  57717. */
  57718. Sound.prototype.stop = function (time) {
  57719. if (this.isPlaying) {
  57720. if (this._streaming) {
  57721. this._htmlAudioElement.pause();
  57722. // Test needed for Firefox or it will generate an Invalid State Error
  57723. if (this._htmlAudioElement.currentTime > 0) {
  57724. this._htmlAudioElement.currentTime = 0;
  57725. }
  57726. }
  57727. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  57728. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57729. this._soundSource.stop(stopTime);
  57730. this._soundSource.onended = function () { };
  57731. if (!this.isPaused) {
  57732. this._startOffset = 0;
  57733. }
  57734. }
  57735. this.isPlaying = false;
  57736. }
  57737. };
  57738. Sound.prototype.pause = function () {
  57739. if (this.isPlaying) {
  57740. this.isPaused = true;
  57741. if (this._streaming) {
  57742. this._htmlAudioElement.pause();
  57743. }
  57744. else if (BABYLON.Engine.audioEngine.audioContext) {
  57745. this.stop(0);
  57746. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  57747. }
  57748. }
  57749. };
  57750. Sound.prototype.setVolume = function (newVolume, time) {
  57751. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  57752. if (time && BABYLON.Engine.audioEngine.audioContext) {
  57753. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  57754. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  57755. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  57756. }
  57757. else {
  57758. this._soundGain.gain.value = newVolume;
  57759. }
  57760. }
  57761. this._volume = newVolume;
  57762. };
  57763. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  57764. this._playbackRate = newPlaybackRate;
  57765. if (this.isPlaying) {
  57766. if (this._streaming) {
  57767. this._htmlAudioElement.playbackRate = this._playbackRate;
  57768. }
  57769. else if (this._soundSource) {
  57770. this._soundSource.playbackRate.value = this._playbackRate;
  57771. }
  57772. }
  57773. };
  57774. Sound.prototype.getVolume = function () {
  57775. return this._volume;
  57776. };
  57777. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  57778. var _this = this;
  57779. if (this._connectedMesh && this._registerFunc) {
  57780. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57781. this._registerFunc = null;
  57782. }
  57783. this._connectedMesh = meshToConnectTo;
  57784. if (!this.spatialSound) {
  57785. this.spatialSound = true;
  57786. this._createSpatialParameters();
  57787. if (this.isPlaying && this.loop) {
  57788. this.stop();
  57789. this.play();
  57790. }
  57791. }
  57792. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  57793. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  57794. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  57795. };
  57796. Sound.prototype.detachFromMesh = function () {
  57797. if (this._connectedMesh && this._registerFunc) {
  57798. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57799. this._registerFunc = null;
  57800. this._connectedMesh = null;
  57801. }
  57802. };
  57803. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  57804. if (!node.getBoundingInfo) {
  57805. return;
  57806. }
  57807. var mesh = node;
  57808. var boundingInfo = mesh.getBoundingInfo();
  57809. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  57810. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  57811. this._updateDirection();
  57812. }
  57813. };
  57814. Sound.prototype.clone = function () {
  57815. var _this = this;
  57816. if (!this._streaming) {
  57817. var setBufferAndRun = function () {
  57818. if (_this._isReadyToPlay) {
  57819. clonedSound._audioBuffer = _this.getAudioBuffer();
  57820. clonedSound._isReadyToPlay = true;
  57821. if (clonedSound.autoplay) {
  57822. clonedSound.play();
  57823. }
  57824. }
  57825. else {
  57826. window.setTimeout(setBufferAndRun, 300);
  57827. }
  57828. };
  57829. var currentOptions = {
  57830. autoplay: this.autoplay, loop: this.loop,
  57831. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  57832. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  57833. refDistance: this.refDistance, distanceModel: this.distanceModel
  57834. };
  57835. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  57836. if (this.useCustomAttenuation) {
  57837. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  57838. }
  57839. clonedSound.setPosition(this._position);
  57840. clonedSound.setPlaybackRate(this._playbackRate);
  57841. setBufferAndRun();
  57842. return clonedSound;
  57843. }
  57844. else {
  57845. return null;
  57846. }
  57847. };
  57848. Sound.prototype.getAudioBuffer = function () {
  57849. return this._audioBuffer;
  57850. };
  57851. Sound.prototype.serialize = function () {
  57852. var serializationObject = {
  57853. name: this.name,
  57854. url: this.name,
  57855. autoplay: this.autoplay,
  57856. loop: this.loop,
  57857. volume: this._volume,
  57858. spatialSound: this.spatialSound,
  57859. maxDistance: this.maxDistance,
  57860. rolloffFactor: this.rolloffFactor,
  57861. refDistance: this.refDistance,
  57862. distanceModel: this.distanceModel,
  57863. playbackRate: this._playbackRate,
  57864. panningModel: this._panningModel,
  57865. soundTrackId: this.soundTrackId
  57866. };
  57867. if (this.spatialSound) {
  57868. if (this._connectedMesh)
  57869. serializationObject.connectedMeshId = this._connectedMesh.id;
  57870. serializationObject.position = this._position.asArray();
  57871. serializationObject.refDistance = this.refDistance;
  57872. serializationObject.distanceModel = this.distanceModel;
  57873. serializationObject.isDirectional = this._isDirectional;
  57874. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  57875. serializationObject.coneInnerAngle = this._coneInnerAngle;
  57876. serializationObject.coneOuterAngle = this._coneOuterAngle;
  57877. serializationObject.coneOuterGain = this._coneOuterGain;
  57878. }
  57879. return serializationObject;
  57880. };
  57881. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  57882. var soundName = parsedSound.name;
  57883. var soundUrl;
  57884. if (parsedSound.url) {
  57885. soundUrl = rootUrl + parsedSound.url;
  57886. }
  57887. else {
  57888. soundUrl = rootUrl + soundName;
  57889. }
  57890. var options = {
  57891. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  57892. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  57893. rolloffFactor: parsedSound.rolloffFactor,
  57894. refDistance: parsedSound.refDistance,
  57895. distanceModel: parsedSound.distanceModel,
  57896. playbackRate: parsedSound.playbackRate
  57897. };
  57898. var newSound;
  57899. if (!sourceSound) {
  57900. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  57901. scene._addPendingData(newSound);
  57902. }
  57903. else {
  57904. var setBufferAndRun = function () {
  57905. if (sourceSound._isReadyToPlay) {
  57906. newSound._audioBuffer = sourceSound.getAudioBuffer();
  57907. newSound._isReadyToPlay = true;
  57908. if (newSound.autoplay) {
  57909. newSound.play();
  57910. }
  57911. }
  57912. else {
  57913. window.setTimeout(setBufferAndRun, 300);
  57914. }
  57915. };
  57916. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  57917. setBufferAndRun();
  57918. }
  57919. if (parsedSound.position) {
  57920. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  57921. newSound.setPosition(soundPosition);
  57922. }
  57923. if (parsedSound.isDirectional) {
  57924. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  57925. if (parsedSound.localDirectionToMesh) {
  57926. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  57927. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  57928. }
  57929. }
  57930. if (parsedSound.connectedMeshId) {
  57931. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  57932. if (connectedMesh) {
  57933. newSound.attachToMesh(connectedMesh);
  57934. }
  57935. }
  57936. return newSound;
  57937. };
  57938. return Sound;
  57939. }());
  57940. BABYLON.Sound = Sound;
  57941. })(BABYLON || (BABYLON = {}));
  57942. //# sourceMappingURL=babylon.sound.js.map
  57943. var BABYLON;
  57944. (function (BABYLON) {
  57945. var SoundTrack = /** @class */ (function () {
  57946. function SoundTrack(scene, options) {
  57947. this.id = -1;
  57948. this._isMainTrack = false;
  57949. this._isInitialized = false;
  57950. this._scene = scene;
  57951. this.soundCollection = new Array();
  57952. this._options = options;
  57953. if (!this._isMainTrack) {
  57954. this._scene.soundTracks.push(this);
  57955. this.id = this._scene.soundTracks.length - 1;
  57956. }
  57957. }
  57958. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  57959. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57960. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  57961. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  57962. if (this._options) {
  57963. if (this._options.volume) {
  57964. this._outputAudioNode.gain.value = this._options.volume;
  57965. }
  57966. if (this._options.mainTrack) {
  57967. this._isMainTrack = this._options.mainTrack;
  57968. }
  57969. }
  57970. this._isInitialized = true;
  57971. }
  57972. };
  57973. SoundTrack.prototype.dispose = function () {
  57974. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  57975. if (this._connectedAnalyser) {
  57976. this._connectedAnalyser.stopDebugCanvas();
  57977. }
  57978. while (this.soundCollection.length) {
  57979. this.soundCollection[0].dispose();
  57980. }
  57981. if (this._outputAudioNode) {
  57982. this._outputAudioNode.disconnect();
  57983. }
  57984. this._outputAudioNode = null;
  57985. }
  57986. };
  57987. SoundTrack.prototype.AddSound = function (sound) {
  57988. if (!this._isInitialized) {
  57989. this._initializeSoundTrackAudioGraph();
  57990. }
  57991. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57992. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  57993. }
  57994. if (sound.soundTrackId) {
  57995. if (sound.soundTrackId === -1) {
  57996. this._scene.mainSoundTrack.RemoveSound(sound);
  57997. }
  57998. else {
  57999. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  58000. }
  58001. }
  58002. this.soundCollection.push(sound);
  58003. sound.soundTrackId = this.id;
  58004. };
  58005. SoundTrack.prototype.RemoveSound = function (sound) {
  58006. var index = this.soundCollection.indexOf(sound);
  58007. if (index !== -1) {
  58008. this.soundCollection.splice(index, 1);
  58009. }
  58010. };
  58011. SoundTrack.prototype.setVolume = function (newVolume) {
  58012. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58013. this._outputAudioNode.gain.value = newVolume;
  58014. }
  58015. };
  58016. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  58017. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58018. for (var i = 0; i < this.soundCollection.length; i++) {
  58019. this.soundCollection[i].switchPanningModelToHRTF();
  58020. }
  58021. }
  58022. };
  58023. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  58024. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58025. for (var i = 0; i < this.soundCollection.length; i++) {
  58026. this.soundCollection[i].switchPanningModelToEqualPower();
  58027. }
  58028. }
  58029. };
  58030. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  58031. if (this._connectedAnalyser) {
  58032. this._connectedAnalyser.stopDebugCanvas();
  58033. }
  58034. this._connectedAnalyser = analyser;
  58035. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58036. this._outputAudioNode.disconnect();
  58037. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  58038. }
  58039. };
  58040. return SoundTrack;
  58041. }());
  58042. BABYLON.SoundTrack = SoundTrack;
  58043. })(BABYLON || (BABYLON = {}));
  58044. //# sourceMappingURL=babylon.soundtrack.js.map
  58045. var BABYLON;
  58046. (function (BABYLON) {
  58047. var Analyser = /** @class */ (function () {
  58048. function Analyser(scene) {
  58049. this.SMOOTHING = 0.75;
  58050. this.FFT_SIZE = 512;
  58051. this.BARGRAPHAMPLITUDE = 256;
  58052. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  58053. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  58054. this._scene = scene;
  58055. this._audioEngine = BABYLON.Engine.audioEngine;
  58056. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  58057. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  58058. this._webAudioAnalyser.minDecibels = -140;
  58059. this._webAudioAnalyser.maxDecibels = 0;
  58060. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58061. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58062. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  58063. }
  58064. }
  58065. Analyser.prototype.getFrequencyBinCount = function () {
  58066. if (this._audioEngine.canUseWebAudio) {
  58067. return this._webAudioAnalyser.frequencyBinCount;
  58068. }
  58069. else {
  58070. return 0;
  58071. }
  58072. };
  58073. Analyser.prototype.getByteFrequencyData = function () {
  58074. if (this._audioEngine.canUseWebAudio) {
  58075. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58076. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58077. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  58078. }
  58079. return this._byteFreqs;
  58080. };
  58081. Analyser.prototype.getByteTimeDomainData = function () {
  58082. if (this._audioEngine.canUseWebAudio) {
  58083. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58084. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58085. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  58086. }
  58087. return this._byteTime;
  58088. };
  58089. Analyser.prototype.getFloatFrequencyData = function () {
  58090. if (this._audioEngine.canUseWebAudio) {
  58091. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58092. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58093. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  58094. }
  58095. return this._floatFreqs;
  58096. };
  58097. Analyser.prototype.drawDebugCanvas = function () {
  58098. var _this = this;
  58099. if (this._audioEngine.canUseWebAudio) {
  58100. if (!this._debugCanvas) {
  58101. this._debugCanvas = document.createElement("canvas");
  58102. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  58103. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  58104. this._debugCanvas.style.position = "absolute";
  58105. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  58106. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  58107. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  58108. document.body.appendChild(this._debugCanvas);
  58109. this._registerFunc = function () {
  58110. _this.drawDebugCanvas();
  58111. };
  58112. this._scene.registerBeforeRender(this._registerFunc);
  58113. }
  58114. if (this._registerFunc && this._debugCanvasContext) {
  58115. var workingArray = this.getByteFrequencyData();
  58116. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  58117. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  58118. // Draw the frequency domain chart.
  58119. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  58120. var value = workingArray[i];
  58121. var percent = value / this.BARGRAPHAMPLITUDE;
  58122. var height = this.DEBUGCANVASSIZE.height * percent;
  58123. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  58124. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  58125. var hue = i / this.getFrequencyBinCount() * 360;
  58126. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  58127. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  58128. }
  58129. }
  58130. }
  58131. };
  58132. Analyser.prototype.stopDebugCanvas = function () {
  58133. if (this._debugCanvas) {
  58134. if (this._registerFunc) {
  58135. this._scene.unregisterBeforeRender(this._registerFunc);
  58136. this._registerFunc = null;
  58137. }
  58138. document.body.removeChild(this._debugCanvas);
  58139. this._debugCanvas = null;
  58140. this._debugCanvasContext = null;
  58141. }
  58142. };
  58143. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  58144. if (this._audioEngine.canUseWebAudio) {
  58145. inputAudioNode.connect(this._webAudioAnalyser);
  58146. this._webAudioAnalyser.connect(outputAudioNode);
  58147. }
  58148. };
  58149. Analyser.prototype.dispose = function () {
  58150. if (this._audioEngine.canUseWebAudio) {
  58151. this._webAudioAnalyser.disconnect();
  58152. }
  58153. };
  58154. return Analyser;
  58155. }());
  58156. BABYLON.Analyser = Analyser;
  58157. })(BABYLON || (BABYLON = {}));
  58158. //# sourceMappingURL=babylon.analyser.js.map
  58159. var BABYLON;
  58160. (function (BABYLON) {
  58161. var CubeTexture = /** @class */ (function (_super) {
  58162. __extends(CubeTexture, _super);
  58163. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  58164. if (extensions === void 0) { extensions = null; }
  58165. if (noMipmap === void 0) { noMipmap = false; }
  58166. if (files === void 0) { files = null; }
  58167. if (onLoad === void 0) { onLoad = null; }
  58168. if (onError === void 0) { onError = null; }
  58169. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58170. if (prefiltered === void 0) { prefiltered = false; }
  58171. if (forcedExtension === void 0) { forcedExtension = null; }
  58172. var _this = _super.call(this, scene) || this;
  58173. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58174. /**
  58175. * Gets or sets the center of the bounding box associated with the cube texture
  58176. * It must define where the camera used to render the texture was set
  58177. */
  58178. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58179. _this.name = rootUrl;
  58180. _this.url = rootUrl;
  58181. _this._noMipmap = noMipmap;
  58182. _this.hasAlpha = false;
  58183. _this._format = format;
  58184. _this._prefiltered = prefiltered;
  58185. _this.isCube = true;
  58186. _this._textureMatrix = BABYLON.Matrix.Identity();
  58187. if (prefiltered) {
  58188. _this.gammaSpace = false;
  58189. }
  58190. if (!rootUrl && !files) {
  58191. return _this;
  58192. }
  58193. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  58194. var lastDot = rootUrl.lastIndexOf(".");
  58195. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  58196. var isDDS = (extension === ".dds");
  58197. if (!files) {
  58198. if (!isDDS && !extensions) {
  58199. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  58200. }
  58201. files = [];
  58202. if (extensions) {
  58203. for (var index = 0; index < extensions.length; index++) {
  58204. files.push(rootUrl + extensions[index]);
  58205. }
  58206. }
  58207. }
  58208. _this._files = files;
  58209. if (!_this._texture) {
  58210. if (!scene.useDelayedTextureLoading) {
  58211. if (prefiltered) {
  58212. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  58213. }
  58214. else {
  58215. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  58216. }
  58217. }
  58218. else {
  58219. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58220. }
  58221. }
  58222. else if (onLoad) {
  58223. if (_this._texture.isReady) {
  58224. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  58225. }
  58226. else {
  58227. _this._texture.onLoadedObservable.add(onLoad);
  58228. }
  58229. }
  58230. return _this;
  58231. }
  58232. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  58233. get: function () {
  58234. return this._boundingBoxSize;
  58235. },
  58236. /**
  58237. * Gets or sets the size of the bounding box associated with the cube texture
  58238. * When defined, the cubemap will switch to local mode
  58239. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58240. * @example https://www.babylonjs-playground.com/#RNASML
  58241. */
  58242. set: function (value) {
  58243. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58244. return;
  58245. }
  58246. this._boundingBoxSize = value;
  58247. var scene = this.getScene();
  58248. if (scene) {
  58249. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58250. }
  58251. },
  58252. enumerable: true,
  58253. configurable: true
  58254. });
  58255. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  58256. var rootUrlKey = "";
  58257. files.forEach(function (url) { return rootUrlKey += url; });
  58258. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  58259. };
  58260. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  58261. if (forcedExtension === void 0) { forcedExtension = null; }
  58262. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  58263. };
  58264. // Methods
  58265. CubeTexture.prototype.delayLoad = function () {
  58266. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58267. return;
  58268. }
  58269. var scene = this.getScene();
  58270. if (!scene) {
  58271. return;
  58272. }
  58273. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58274. this._texture = this._getFromCache(this.url, this._noMipmap);
  58275. if (!this._texture) {
  58276. if (this._prefiltered) {
  58277. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  58278. }
  58279. else {
  58280. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  58281. }
  58282. }
  58283. };
  58284. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  58285. return this._textureMatrix;
  58286. };
  58287. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  58288. this._textureMatrix = value;
  58289. };
  58290. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58291. var texture = BABYLON.SerializationHelper.Parse(function () {
  58292. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  58293. }, parsedTexture, scene);
  58294. // Local Cubemaps
  58295. if (parsedTexture.boundingBoxPosition) {
  58296. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  58297. }
  58298. if (parsedTexture.boundingBoxSize) {
  58299. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  58300. }
  58301. // Animations
  58302. if (parsedTexture.animations) {
  58303. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  58304. var parsedAnimation = parsedTexture.animations[animationIndex];
  58305. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58306. }
  58307. }
  58308. return texture;
  58309. };
  58310. CubeTexture.prototype.clone = function () {
  58311. var _this = this;
  58312. return BABYLON.SerializationHelper.Clone(function () {
  58313. var scene = _this.getScene();
  58314. if (!scene) {
  58315. return _this;
  58316. }
  58317. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  58318. }, this);
  58319. };
  58320. return CubeTexture;
  58321. }(BABYLON.BaseTexture));
  58322. BABYLON.CubeTexture = CubeTexture;
  58323. })(BABYLON || (BABYLON = {}));
  58324. //# sourceMappingURL=babylon.cubeTexture.js.map
  58325. var BABYLON;
  58326. (function (BABYLON) {
  58327. var RenderTargetTexture = /** @class */ (function (_super) {
  58328. __extends(RenderTargetTexture, _super);
  58329. /**
  58330. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  58331. * or used a shadow, depth texture...
  58332. * @param name The friendly name of the texture
  58333. * @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)
  58334. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  58335. * @param generateMipMaps True if mip maps need to be generated after render.
  58336. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  58337. * @param type The type of the buffer in the RTT (int, half float, float...)
  58338. * @param isCube True if a cube texture needs to be created
  58339. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  58340. * @param generateDepthBuffer True to generate a depth buffer
  58341. * @param generateStencilBuffer True to generate a stencil buffer
  58342. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  58343. */
  58344. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  58345. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  58346. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58347. if (isCube === void 0) { isCube = false; }
  58348. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58349. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58350. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  58351. if (isMulti === void 0) { isMulti = false; }
  58352. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  58353. _this.isCube = isCube;
  58354. /**
  58355. * Use this list to define the list of mesh you want to render.
  58356. */
  58357. _this.renderList = new Array();
  58358. _this.renderParticles = true;
  58359. _this.renderSprites = false;
  58360. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  58361. _this.ignoreCameraViewport = false;
  58362. // Events
  58363. /**
  58364. * An event triggered when the texture is unbind.
  58365. * @type {BABYLON.Observable}
  58366. */
  58367. _this.onBeforeBindObservable = new BABYLON.Observable();
  58368. /**
  58369. * An event triggered when the texture is unbind.
  58370. * @type {BABYLON.Observable}
  58371. */
  58372. _this.onAfterUnbindObservable = new BABYLON.Observable();
  58373. /**
  58374. * An event triggered before rendering the texture
  58375. * @type {BABYLON.Observable}
  58376. */
  58377. _this.onBeforeRenderObservable = new BABYLON.Observable();
  58378. /**
  58379. * An event triggered after rendering the texture
  58380. * @type {BABYLON.Observable}
  58381. */
  58382. _this.onAfterRenderObservable = new BABYLON.Observable();
  58383. /**
  58384. * An event triggered after the texture clear
  58385. * @type {BABYLON.Observable}
  58386. */
  58387. _this.onClearObservable = new BABYLON.Observable();
  58388. _this._currentRefreshId = -1;
  58389. _this._refreshRate = 1;
  58390. _this._samples = 1;
  58391. /**
  58392. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  58393. * It must define where the camera used to render the texture is set
  58394. */
  58395. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58396. scene = _this.getScene();
  58397. if (!scene) {
  58398. return _this;
  58399. }
  58400. _this._engine = scene.getEngine();
  58401. _this.name = name;
  58402. _this.isRenderTarget = true;
  58403. _this._initialSizeParameter = size;
  58404. _this._processSizeParameter(size);
  58405. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  58406. });
  58407. _this._generateMipMaps = generateMipMaps ? true : false;
  58408. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  58409. // Rendering groups
  58410. _this._renderingManager = new BABYLON.RenderingManager(scene);
  58411. if (isMulti) {
  58412. return _this;
  58413. }
  58414. _this._renderTargetOptions = {
  58415. generateMipMaps: generateMipMaps,
  58416. type: type,
  58417. samplingMode: samplingMode,
  58418. generateDepthBuffer: generateDepthBuffer,
  58419. generateStencilBuffer: generateStencilBuffer
  58420. };
  58421. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  58422. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58423. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58424. }
  58425. if (isCube) {
  58426. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  58427. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  58428. _this._textureMatrix = BABYLON.Matrix.Identity();
  58429. }
  58430. else {
  58431. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  58432. }
  58433. return _this;
  58434. }
  58435. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  58436. get: function () {
  58437. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  58438. },
  58439. enumerable: true,
  58440. configurable: true
  58441. });
  58442. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  58443. get: function () {
  58444. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  58445. },
  58446. enumerable: true,
  58447. configurable: true
  58448. });
  58449. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  58450. get: function () {
  58451. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  58452. },
  58453. enumerable: true,
  58454. configurable: true
  58455. });
  58456. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  58457. set: function (callback) {
  58458. if (this._onAfterUnbindObserver) {
  58459. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  58460. }
  58461. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  58462. },
  58463. enumerable: true,
  58464. configurable: true
  58465. });
  58466. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  58467. set: function (callback) {
  58468. if (this._onBeforeRenderObserver) {
  58469. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  58470. }
  58471. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  58472. },
  58473. enumerable: true,
  58474. configurable: true
  58475. });
  58476. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  58477. set: function (callback) {
  58478. if (this._onAfterRenderObserver) {
  58479. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  58480. }
  58481. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  58482. },
  58483. enumerable: true,
  58484. configurable: true
  58485. });
  58486. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  58487. set: function (callback) {
  58488. if (this._onClearObserver) {
  58489. this.onClearObservable.remove(this._onClearObserver);
  58490. }
  58491. this._onClearObserver = this.onClearObservable.add(callback);
  58492. },
  58493. enumerable: true,
  58494. configurable: true
  58495. });
  58496. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  58497. get: function () {
  58498. return this._renderTargetOptions;
  58499. },
  58500. enumerable: true,
  58501. configurable: true
  58502. });
  58503. RenderTargetTexture.prototype._onRatioRescale = function () {
  58504. if (this._sizeRatio) {
  58505. this.resize(this._initialSizeParameter);
  58506. }
  58507. };
  58508. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  58509. get: function () {
  58510. return this._boundingBoxSize;
  58511. },
  58512. /**
  58513. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  58514. * When defined, the cubemap will switch to local mode
  58515. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58516. * @example https://www.babylonjs-playground.com/#RNASML
  58517. */
  58518. set: function (value) {
  58519. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58520. return;
  58521. }
  58522. this._boundingBoxSize = value;
  58523. var scene = this.getScene();
  58524. if (scene) {
  58525. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58526. }
  58527. },
  58528. enumerable: true,
  58529. configurable: true
  58530. });
  58531. /**
  58532. * Creates a depth stencil texture.
  58533. * This is only available in WebGL 2 or with the depth texture extension available.
  58534. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  58535. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  58536. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  58537. */
  58538. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  58539. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  58540. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  58541. if (generateStencil === void 0) { generateStencil = false; }
  58542. if (!this.getScene()) {
  58543. return;
  58544. }
  58545. var engine = this.getScene().getEngine();
  58546. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  58547. bilinearFiltering: bilinearFiltering,
  58548. comparisonFunction: comparisonFunction,
  58549. generateStencil: generateStencil,
  58550. isCube: this.isCube
  58551. });
  58552. engine.setFrameBufferDepthStencilTexture(this);
  58553. };
  58554. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  58555. if (size.ratio) {
  58556. this._sizeRatio = size.ratio;
  58557. this._size = {
  58558. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  58559. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  58560. };
  58561. }
  58562. else {
  58563. this._size = size;
  58564. }
  58565. };
  58566. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  58567. get: function () {
  58568. return this._samples;
  58569. },
  58570. set: function (value) {
  58571. if (this._samples === value) {
  58572. return;
  58573. }
  58574. var scene = this.getScene();
  58575. if (!scene) {
  58576. return;
  58577. }
  58578. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  58579. },
  58580. enumerable: true,
  58581. configurable: true
  58582. });
  58583. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  58584. this._currentRefreshId = -1;
  58585. };
  58586. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  58587. get: function () {
  58588. return this._refreshRate;
  58589. },
  58590. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  58591. set: function (value) {
  58592. this._refreshRate = value;
  58593. this.resetRefreshCounter();
  58594. },
  58595. enumerable: true,
  58596. configurable: true
  58597. });
  58598. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  58599. if (!this._postProcessManager) {
  58600. var scene = this.getScene();
  58601. if (!scene) {
  58602. return;
  58603. }
  58604. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  58605. this._postProcesses = new Array();
  58606. }
  58607. this._postProcesses.push(postProcess);
  58608. this._postProcesses[0].autoClear = false;
  58609. };
  58610. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  58611. if (!this._postProcesses) {
  58612. return;
  58613. }
  58614. if (dispose) {
  58615. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  58616. var postProcess = _a[_i];
  58617. postProcess.dispose();
  58618. }
  58619. }
  58620. this._postProcesses = [];
  58621. };
  58622. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  58623. if (!this._postProcesses) {
  58624. return;
  58625. }
  58626. var index = this._postProcesses.indexOf(postProcess);
  58627. if (index === -1) {
  58628. return;
  58629. }
  58630. this._postProcesses.splice(index, 1);
  58631. if (this._postProcesses.length > 0) {
  58632. this._postProcesses[0].autoClear = false;
  58633. }
  58634. };
  58635. RenderTargetTexture.prototype._shouldRender = function () {
  58636. if (this._currentRefreshId === -1) {
  58637. this._currentRefreshId = 1;
  58638. return true;
  58639. }
  58640. if (this.refreshRate === this._currentRefreshId) {
  58641. this._currentRefreshId = 1;
  58642. return true;
  58643. }
  58644. this._currentRefreshId++;
  58645. return false;
  58646. };
  58647. RenderTargetTexture.prototype.getRenderSize = function () {
  58648. if (this._size.width) {
  58649. return this._size.width;
  58650. }
  58651. return this._size;
  58652. };
  58653. RenderTargetTexture.prototype.getRenderWidth = function () {
  58654. if (this._size.width) {
  58655. return this._size.width;
  58656. }
  58657. return this._size;
  58658. };
  58659. RenderTargetTexture.prototype.getRenderHeight = function () {
  58660. if (this._size.width) {
  58661. return this._size.height;
  58662. }
  58663. return this._size;
  58664. };
  58665. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  58666. get: function () {
  58667. return true;
  58668. },
  58669. enumerable: true,
  58670. configurable: true
  58671. });
  58672. RenderTargetTexture.prototype.scale = function (ratio) {
  58673. var newSize = this.getRenderSize() * ratio;
  58674. this.resize(newSize);
  58675. };
  58676. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  58677. if (this.isCube) {
  58678. return this._textureMatrix;
  58679. }
  58680. return _super.prototype.getReflectionTextureMatrix.call(this);
  58681. };
  58682. RenderTargetTexture.prototype.resize = function (size) {
  58683. this.releaseInternalTexture();
  58684. var scene = this.getScene();
  58685. if (!scene) {
  58686. return;
  58687. }
  58688. this._processSizeParameter(size);
  58689. if (this.isCube) {
  58690. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  58691. }
  58692. else {
  58693. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  58694. }
  58695. };
  58696. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  58697. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  58698. if (dumpForDebug === void 0) { dumpForDebug = false; }
  58699. var scene = this.getScene();
  58700. if (!scene) {
  58701. return;
  58702. }
  58703. var engine = scene.getEngine();
  58704. if (this.useCameraPostProcesses !== undefined) {
  58705. useCameraPostProcess = this.useCameraPostProcesses;
  58706. }
  58707. if (this._waitingRenderList) {
  58708. this.renderList = [];
  58709. for (var index = 0; index < this._waitingRenderList.length; index++) {
  58710. var id = this._waitingRenderList[index];
  58711. var mesh_1 = scene.getMeshByID(id);
  58712. if (mesh_1) {
  58713. this.renderList.push(mesh_1);
  58714. }
  58715. }
  58716. delete this._waitingRenderList;
  58717. }
  58718. // Is predicate defined?
  58719. if (this.renderListPredicate) {
  58720. if (this.renderList) {
  58721. this.renderList.splice(0); // Clear previous renderList
  58722. }
  58723. else {
  58724. this.renderList = [];
  58725. }
  58726. var scene = this.getScene();
  58727. if (!scene) {
  58728. return;
  58729. }
  58730. var sceneMeshes = scene.meshes;
  58731. for (var index = 0; index < sceneMeshes.length; index++) {
  58732. var mesh = sceneMeshes[index];
  58733. if (this.renderListPredicate(mesh)) {
  58734. this.renderList.push(mesh);
  58735. }
  58736. }
  58737. }
  58738. this.onBeforeBindObservable.notifyObservers(this);
  58739. // Set custom projection.
  58740. // Needs to be before binding to prevent changing the aspect ratio.
  58741. var camera;
  58742. if (this.activeCamera) {
  58743. camera = this.activeCamera;
  58744. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58745. if (this.activeCamera !== scene.activeCamera) {
  58746. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  58747. }
  58748. }
  58749. else {
  58750. camera = scene.activeCamera;
  58751. if (camera) {
  58752. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58753. }
  58754. }
  58755. // Prepare renderingManager
  58756. this._renderingManager.reset();
  58757. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  58758. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  58759. var sceneRenderId = scene.getRenderId();
  58760. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  58761. var mesh = currentRenderList[meshIndex];
  58762. if (mesh) {
  58763. if (!mesh.isReady(this.refreshRate === 0)) {
  58764. this.resetRefreshCounter();
  58765. continue;
  58766. }
  58767. mesh._preActivateForIntermediateRendering(sceneRenderId);
  58768. var isMasked = void 0;
  58769. if (!this.renderList && camera) {
  58770. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  58771. }
  58772. else {
  58773. isMasked = false;
  58774. }
  58775. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  58776. mesh._activate(sceneRenderId);
  58777. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  58778. var subMesh = mesh.subMeshes[subIndex];
  58779. scene._activeIndices.addCount(subMesh.indexCount, false);
  58780. this._renderingManager.dispatch(subMesh, mesh);
  58781. }
  58782. }
  58783. }
  58784. }
  58785. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  58786. var particleSystem = scene.particleSystems[particleIndex];
  58787. var emitter = particleSystem.emitter;
  58788. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  58789. continue;
  58790. }
  58791. if (currentRenderList.indexOf(emitter) >= 0) {
  58792. this._renderingManager.dispatchParticles(particleSystem);
  58793. }
  58794. }
  58795. if (this.isCube) {
  58796. for (var face = 0; face < 6; face++) {
  58797. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58798. scene.incrementRenderId();
  58799. scene.resetCachedMaterial();
  58800. }
  58801. }
  58802. else {
  58803. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58804. }
  58805. this.onAfterUnbindObservable.notifyObservers(this);
  58806. if (scene.activeCamera) {
  58807. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  58808. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  58809. }
  58810. engine.setViewport(scene.activeCamera.viewport);
  58811. }
  58812. scene.resetCachedMaterial();
  58813. };
  58814. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  58815. var minimum = 128;
  58816. var x = renderDimension * scale;
  58817. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  58818. // Ensure we don't exceed the render dimension (while staying POT)
  58819. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  58820. };
  58821. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58822. var _this = this;
  58823. if (!this._texture) {
  58824. return;
  58825. }
  58826. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  58827. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58828. });
  58829. };
  58830. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  58831. var scene = this.getScene();
  58832. if (!scene) {
  58833. return;
  58834. }
  58835. var engine = scene.getEngine();
  58836. if (!this._texture) {
  58837. return;
  58838. }
  58839. // Bind
  58840. if (this._postProcessManager) {
  58841. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  58842. }
  58843. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  58844. if (this._texture) {
  58845. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  58846. }
  58847. }
  58848. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  58849. // Clear
  58850. if (this.onClearObservable.hasObservers()) {
  58851. this.onClearObservable.notifyObservers(engine);
  58852. }
  58853. else {
  58854. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  58855. }
  58856. if (!this._doNotChangeAspectRatio) {
  58857. scene.updateTransformMatrix(true);
  58858. }
  58859. // Render
  58860. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  58861. if (this._postProcessManager) {
  58862. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  58863. }
  58864. else if (useCameraPostProcess) {
  58865. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  58866. }
  58867. if (!this._doNotChangeAspectRatio) {
  58868. scene.updateTransformMatrix(true);
  58869. }
  58870. // Dump ?
  58871. if (dumpForDebug) {
  58872. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  58873. }
  58874. // Unbind
  58875. if (!this.isCube || faceIndex === 5) {
  58876. if (this.isCube) {
  58877. if (faceIndex === 5) {
  58878. engine.generateMipMapsForCubemap(this._texture);
  58879. }
  58880. }
  58881. this.unbindFrameBuffer(engine, faceIndex);
  58882. }
  58883. else {
  58884. this.onAfterRenderObservable.notifyObservers(faceIndex);
  58885. }
  58886. };
  58887. /**
  58888. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  58889. * This allowed control for front to back rendering or reversly depending of the special needs.
  58890. *
  58891. * @param renderingGroupId The rendering group id corresponding to its index
  58892. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  58893. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  58894. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  58895. */
  58896. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  58897. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  58898. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  58899. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  58900. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  58901. };
  58902. /**
  58903. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  58904. *
  58905. * @param renderingGroupId The rendering group id corresponding to its index
  58906. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  58907. */
  58908. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  58909. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  58910. };
  58911. RenderTargetTexture.prototype.clone = function () {
  58912. var textureSize = this.getSize();
  58913. 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);
  58914. // Base texture
  58915. newTexture.hasAlpha = this.hasAlpha;
  58916. newTexture.level = this.level;
  58917. // RenderTarget Texture
  58918. newTexture.coordinatesMode = this.coordinatesMode;
  58919. if (this.renderList) {
  58920. newTexture.renderList = this.renderList.slice(0);
  58921. }
  58922. return newTexture;
  58923. };
  58924. RenderTargetTexture.prototype.serialize = function () {
  58925. if (!this.name) {
  58926. return null;
  58927. }
  58928. var serializationObject = _super.prototype.serialize.call(this);
  58929. serializationObject.renderTargetSize = this.getRenderSize();
  58930. serializationObject.renderList = [];
  58931. if (this.renderList) {
  58932. for (var index = 0; index < this.renderList.length; index++) {
  58933. serializationObject.renderList.push(this.renderList[index].id);
  58934. }
  58935. }
  58936. return serializationObject;
  58937. };
  58938. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  58939. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  58940. var objBuffer = this.getInternalTexture();
  58941. var scene = this.getScene();
  58942. if (objBuffer && scene) {
  58943. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  58944. }
  58945. };
  58946. RenderTargetTexture.prototype.dispose = function () {
  58947. if (this._postProcessManager) {
  58948. this._postProcessManager.dispose();
  58949. this._postProcessManager = null;
  58950. }
  58951. this.clearPostProcesses(true);
  58952. if (this._resizeObserver) {
  58953. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  58954. this._resizeObserver = null;
  58955. }
  58956. this.renderList = null;
  58957. // Remove from custom render targets
  58958. var scene = this.getScene();
  58959. if (!scene) {
  58960. return;
  58961. }
  58962. var index = scene.customRenderTargets.indexOf(this);
  58963. if (index >= 0) {
  58964. scene.customRenderTargets.splice(index, 1);
  58965. }
  58966. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  58967. var camera = _a[_i];
  58968. index = camera.customRenderTargets.indexOf(this);
  58969. if (index >= 0) {
  58970. camera.customRenderTargets.splice(index, 1);
  58971. }
  58972. }
  58973. _super.prototype.dispose.call(this);
  58974. };
  58975. RenderTargetTexture.prototype._rebuild = function () {
  58976. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  58977. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  58978. }
  58979. if (this._postProcessManager) {
  58980. this._postProcessManager._rebuild();
  58981. }
  58982. };
  58983. /**
  58984. * Clear the info related to rendering groups preventing retention point in material dispose.
  58985. */
  58986. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  58987. if (this._renderingManager) {
  58988. this._renderingManager.freeRenderingGroups();
  58989. }
  58990. };
  58991. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  58992. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  58993. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  58994. return RenderTargetTexture;
  58995. }(BABYLON.Texture));
  58996. BABYLON.RenderTargetTexture = RenderTargetTexture;
  58997. })(BABYLON || (BABYLON = {}));
  58998. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  58999. var BABYLON;
  59000. (function (BABYLON) {
  59001. ;
  59002. var MultiRenderTarget = /** @class */ (function (_super) {
  59003. __extends(MultiRenderTarget, _super);
  59004. function MultiRenderTarget(name, size, count, scene, options) {
  59005. var _this = this;
  59006. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  59007. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  59008. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  59009. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  59010. _this._engine = scene.getEngine();
  59011. if (!_this.isSupported) {
  59012. _this.dispose();
  59013. return;
  59014. }
  59015. var types = [];
  59016. var samplingModes = [];
  59017. for (var i = 0; i < count; i++) {
  59018. if (options && options.types && options.types[i] !== undefined) {
  59019. types.push(options.types[i]);
  59020. }
  59021. else {
  59022. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59023. }
  59024. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  59025. samplingModes.push(options.samplingModes[i]);
  59026. }
  59027. else {
  59028. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59029. }
  59030. }
  59031. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  59032. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  59033. _this._size = size;
  59034. _this._multiRenderTargetOptions = {
  59035. samplingModes: samplingModes,
  59036. generateMipMaps: generateMipMaps,
  59037. generateDepthBuffer: generateDepthBuffer,
  59038. generateStencilBuffer: generateStencilBuffer,
  59039. generateDepthTexture: generateDepthTexture,
  59040. types: types,
  59041. textureCount: count
  59042. };
  59043. _this._createInternalTextures();
  59044. _this._createTextures();
  59045. return _this;
  59046. }
  59047. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  59048. get: function () {
  59049. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  59050. },
  59051. enumerable: true,
  59052. configurable: true
  59053. });
  59054. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  59055. get: function () {
  59056. return this._textures;
  59057. },
  59058. enumerable: true,
  59059. configurable: true
  59060. });
  59061. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  59062. get: function () {
  59063. return this._textures[this._textures.length - 1];
  59064. },
  59065. enumerable: true,
  59066. configurable: true
  59067. });
  59068. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  59069. set: function (wrap) {
  59070. if (this._textures) {
  59071. for (var i = 0; i < this._textures.length; i++) {
  59072. this._textures[i].wrapU = wrap;
  59073. }
  59074. }
  59075. },
  59076. enumerable: true,
  59077. configurable: true
  59078. });
  59079. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  59080. set: function (wrap) {
  59081. if (this._textures) {
  59082. for (var i = 0; i < this._textures.length; i++) {
  59083. this._textures[i].wrapV = wrap;
  59084. }
  59085. }
  59086. },
  59087. enumerable: true,
  59088. configurable: true
  59089. });
  59090. MultiRenderTarget.prototype._rebuild = function () {
  59091. this.releaseInternalTextures();
  59092. this._createInternalTextures();
  59093. for (var i = 0; i < this._internalTextures.length; i++) {
  59094. var texture = this._textures[i];
  59095. texture._texture = this._internalTextures[i];
  59096. }
  59097. // Keeps references to frame buffer and stencil/depth buffer
  59098. this._texture = this._internalTextures[0];
  59099. };
  59100. MultiRenderTarget.prototype._createInternalTextures = function () {
  59101. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  59102. };
  59103. MultiRenderTarget.prototype._createTextures = function () {
  59104. this._textures = [];
  59105. for (var i = 0; i < this._internalTextures.length; i++) {
  59106. var texture = new BABYLON.Texture(null, this.getScene());
  59107. texture._texture = this._internalTextures[i];
  59108. this._textures.push(texture);
  59109. }
  59110. // Keeps references to frame buffer and stencil/depth buffer
  59111. this._texture = this._internalTextures[0];
  59112. };
  59113. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  59114. get: function () {
  59115. return this._samples;
  59116. },
  59117. set: function (value) {
  59118. if (this._samples === value) {
  59119. return;
  59120. }
  59121. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  59122. },
  59123. enumerable: true,
  59124. configurable: true
  59125. });
  59126. MultiRenderTarget.prototype.resize = function (size) {
  59127. this.releaseInternalTextures();
  59128. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  59129. this._createInternalTextures();
  59130. };
  59131. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59132. var _this = this;
  59133. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  59134. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59135. });
  59136. };
  59137. MultiRenderTarget.prototype.dispose = function () {
  59138. this.releaseInternalTextures();
  59139. _super.prototype.dispose.call(this);
  59140. };
  59141. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  59142. if (!this._internalTextures) {
  59143. return;
  59144. }
  59145. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  59146. if (this._internalTextures[i] !== undefined) {
  59147. this._internalTextures[i].dispose();
  59148. this._internalTextures.splice(i, 1);
  59149. }
  59150. }
  59151. };
  59152. return MultiRenderTarget;
  59153. }(BABYLON.RenderTargetTexture));
  59154. BABYLON.MultiRenderTarget = MultiRenderTarget;
  59155. })(BABYLON || (BABYLON = {}));
  59156. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  59157. var BABYLON;
  59158. (function (BABYLON) {
  59159. var MirrorTexture = /** @class */ (function (_super) {
  59160. __extends(MirrorTexture, _super);
  59161. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  59162. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59163. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59164. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59165. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  59166. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  59167. _this._transformMatrix = BABYLON.Matrix.Zero();
  59168. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  59169. _this._adaptiveBlurKernel = 0;
  59170. _this._blurKernelX = 0;
  59171. _this._blurKernelY = 0;
  59172. _this._blurRatio = 1.0;
  59173. _this.ignoreCameraViewport = true;
  59174. _this.onBeforeRenderObservable.add(function () {
  59175. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  59176. _this._savedViewMatrix = scene.getViewMatrix();
  59177. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  59178. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  59179. scene.clipPlane = _this.mirrorPlane;
  59180. scene.getEngine().cullBackFaces = false;
  59181. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  59182. });
  59183. _this.onAfterRenderObservable.add(function () {
  59184. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  59185. scene.getEngine().cullBackFaces = true;
  59186. scene._mirroredCameraPosition = null;
  59187. delete scene.clipPlane;
  59188. });
  59189. return _this;
  59190. }
  59191. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  59192. get: function () {
  59193. return this._blurRatio;
  59194. },
  59195. set: function (value) {
  59196. if (this._blurRatio === value) {
  59197. return;
  59198. }
  59199. this._blurRatio = value;
  59200. this._preparePostProcesses();
  59201. },
  59202. enumerable: true,
  59203. configurable: true
  59204. });
  59205. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  59206. set: function (value) {
  59207. this._adaptiveBlurKernel = value;
  59208. this._autoComputeBlurKernel();
  59209. },
  59210. enumerable: true,
  59211. configurable: true
  59212. });
  59213. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  59214. set: function (value) {
  59215. this.blurKernelX = value;
  59216. this.blurKernelY = value;
  59217. },
  59218. enumerable: true,
  59219. configurable: true
  59220. });
  59221. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  59222. get: function () {
  59223. return this._blurKernelX;
  59224. },
  59225. set: function (value) {
  59226. if (this._blurKernelX === value) {
  59227. return;
  59228. }
  59229. this._blurKernelX = value;
  59230. this._preparePostProcesses();
  59231. },
  59232. enumerable: true,
  59233. configurable: true
  59234. });
  59235. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  59236. get: function () {
  59237. return this._blurKernelY;
  59238. },
  59239. set: function (value) {
  59240. if (this._blurKernelY === value) {
  59241. return;
  59242. }
  59243. this._blurKernelY = value;
  59244. this._preparePostProcesses();
  59245. },
  59246. enumerable: true,
  59247. configurable: true
  59248. });
  59249. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  59250. var engine = this.getScene().getEngine();
  59251. var dw = this.getRenderWidth() / engine.getRenderWidth();
  59252. var dh = this.getRenderHeight() / engine.getRenderHeight();
  59253. this.blurKernelX = this._adaptiveBlurKernel * dw;
  59254. this.blurKernelY = this._adaptiveBlurKernel * dh;
  59255. };
  59256. MirrorTexture.prototype._onRatioRescale = function () {
  59257. if (this._sizeRatio) {
  59258. this.resize(this._initialSizeParameter);
  59259. if (!this._adaptiveBlurKernel) {
  59260. this._preparePostProcesses();
  59261. }
  59262. }
  59263. if (this._adaptiveBlurKernel) {
  59264. this._autoComputeBlurKernel();
  59265. }
  59266. };
  59267. MirrorTexture.prototype._preparePostProcesses = function () {
  59268. this.clearPostProcesses(true);
  59269. if (this._blurKernelX && this._blurKernelY) {
  59270. var engine = this.getScene().getEngine();
  59271. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59272. 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);
  59273. this._blurX.autoClear = false;
  59274. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  59275. this._blurX.inputTexture = this._texture;
  59276. }
  59277. else {
  59278. this._blurX.alwaysForcePOT = true;
  59279. }
  59280. 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);
  59281. this._blurY.autoClear = false;
  59282. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  59283. this.addPostProcess(this._blurX);
  59284. this.addPostProcess(this._blurY);
  59285. }
  59286. else {
  59287. if (this._blurY) {
  59288. this.removePostProcess(this._blurY);
  59289. this._blurY.dispose();
  59290. this._blurY = null;
  59291. }
  59292. if (this._blurX) {
  59293. this.removePostProcess(this._blurX);
  59294. this._blurX.dispose();
  59295. this._blurX = null;
  59296. }
  59297. }
  59298. };
  59299. MirrorTexture.prototype.clone = function () {
  59300. var scene = this.getScene();
  59301. if (!scene) {
  59302. return this;
  59303. }
  59304. var textureSize = this.getSize();
  59305. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  59306. // Base texture
  59307. newTexture.hasAlpha = this.hasAlpha;
  59308. newTexture.level = this.level;
  59309. // Mirror Texture
  59310. newTexture.mirrorPlane = this.mirrorPlane.clone();
  59311. if (this.renderList) {
  59312. newTexture.renderList = this.renderList.slice(0);
  59313. }
  59314. return newTexture;
  59315. };
  59316. MirrorTexture.prototype.serialize = function () {
  59317. if (!this.name) {
  59318. return null;
  59319. }
  59320. var serializationObject = _super.prototype.serialize.call(this);
  59321. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  59322. return serializationObject;
  59323. };
  59324. return MirrorTexture;
  59325. }(BABYLON.RenderTargetTexture));
  59326. BABYLON.MirrorTexture = MirrorTexture;
  59327. })(BABYLON || (BABYLON = {}));
  59328. //# sourceMappingURL=babylon.mirrorTexture.js.map
  59329. var BABYLON;
  59330. (function (BABYLON) {
  59331. /**
  59332. * Creates a refraction texture used by refraction channel of the standard material.
  59333. * @param name the texture name
  59334. * @param size size of the underlying texture
  59335. * @param scene root scene
  59336. */
  59337. var RefractionTexture = /** @class */ (function (_super) {
  59338. __extends(RefractionTexture, _super);
  59339. function RefractionTexture(name, size, scene, generateMipMaps) {
  59340. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  59341. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  59342. _this.depth = 2.0;
  59343. _this.onBeforeRenderObservable.add(function () {
  59344. scene.clipPlane = _this.refractionPlane;
  59345. });
  59346. _this.onAfterRenderObservable.add(function () {
  59347. delete scene.clipPlane;
  59348. });
  59349. return _this;
  59350. }
  59351. RefractionTexture.prototype.clone = function () {
  59352. var scene = this.getScene();
  59353. if (!scene) {
  59354. return this;
  59355. }
  59356. var textureSize = this.getSize();
  59357. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  59358. // Base texture
  59359. newTexture.hasAlpha = this.hasAlpha;
  59360. newTexture.level = this.level;
  59361. // Refraction Texture
  59362. newTexture.refractionPlane = this.refractionPlane.clone();
  59363. if (this.renderList) {
  59364. newTexture.renderList = this.renderList.slice(0);
  59365. }
  59366. newTexture.depth = this.depth;
  59367. return newTexture;
  59368. };
  59369. RefractionTexture.prototype.serialize = function () {
  59370. if (!this.name) {
  59371. return null;
  59372. }
  59373. var serializationObject = _super.prototype.serialize.call(this);
  59374. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  59375. serializationObject.depth = this.depth;
  59376. return serializationObject;
  59377. };
  59378. return RefractionTexture;
  59379. }(BABYLON.RenderTargetTexture));
  59380. BABYLON.RefractionTexture = RefractionTexture;
  59381. })(BABYLON || (BABYLON = {}));
  59382. //# sourceMappingURL=babylon.refractionTexture.js.map
  59383. var BABYLON;
  59384. (function (BABYLON) {
  59385. var DynamicTexture = /** @class */ (function (_super) {
  59386. __extends(DynamicTexture, _super);
  59387. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  59388. if (scene === void 0) { scene = null; }
  59389. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59390. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  59391. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  59392. _this.name = name;
  59393. _this._engine = _this.getScene().getEngine();
  59394. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59395. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59396. _this._generateMipMaps = generateMipMaps;
  59397. if (options.getContext) {
  59398. _this._canvas = options;
  59399. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59400. }
  59401. else {
  59402. _this._canvas = document.createElement("canvas");
  59403. if (options.width) {
  59404. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59405. }
  59406. else {
  59407. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  59408. }
  59409. }
  59410. var textureSize = _this.getSize();
  59411. _this._canvas.width = textureSize.width;
  59412. _this._canvas.height = textureSize.height;
  59413. _this._context = _this._canvas.getContext("2d");
  59414. return _this;
  59415. }
  59416. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  59417. get: function () {
  59418. return true;
  59419. },
  59420. enumerable: true,
  59421. configurable: true
  59422. });
  59423. DynamicTexture.prototype._recreate = function (textureSize) {
  59424. this._canvas.width = textureSize.width;
  59425. this._canvas.height = textureSize.height;
  59426. this.releaseInternalTexture();
  59427. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  59428. };
  59429. DynamicTexture.prototype.scale = function (ratio) {
  59430. var textureSize = this.getSize();
  59431. textureSize.width *= ratio;
  59432. textureSize.height *= ratio;
  59433. this._recreate(textureSize);
  59434. };
  59435. DynamicTexture.prototype.scaleTo = function (width, height) {
  59436. var textureSize = this.getSize();
  59437. textureSize.width = width;
  59438. textureSize.height = height;
  59439. this._recreate(textureSize);
  59440. };
  59441. DynamicTexture.prototype.getContext = function () {
  59442. return this._context;
  59443. };
  59444. DynamicTexture.prototype.clear = function () {
  59445. var size = this.getSize();
  59446. this._context.fillRect(0, 0, size.width, size.height);
  59447. };
  59448. DynamicTexture.prototype.update = function (invertY) {
  59449. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  59450. };
  59451. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  59452. if (update === void 0) { update = true; }
  59453. var size = this.getSize();
  59454. if (clearColor) {
  59455. this._context.fillStyle = clearColor;
  59456. this._context.fillRect(0, 0, size.width, size.height);
  59457. }
  59458. this._context.font = font;
  59459. if (x === null || x === undefined) {
  59460. var textSize = this._context.measureText(text);
  59461. x = (size.width - textSize.width) / 2;
  59462. }
  59463. if (y === null || y === undefined) {
  59464. var fontSize = parseInt((font.replace(/\D/g, '')));
  59465. ;
  59466. y = (size.height / 2) + (fontSize / 3.65);
  59467. }
  59468. this._context.fillStyle = color;
  59469. this._context.fillText(text, x, y);
  59470. if (update) {
  59471. this.update(invertY);
  59472. }
  59473. };
  59474. DynamicTexture.prototype.clone = function () {
  59475. var scene = this.getScene();
  59476. if (!scene) {
  59477. return this;
  59478. }
  59479. var textureSize = this.getSize();
  59480. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  59481. // Base texture
  59482. newTexture.hasAlpha = this.hasAlpha;
  59483. newTexture.level = this.level;
  59484. // Dynamic Texture
  59485. newTexture.wrapU = this.wrapU;
  59486. newTexture.wrapV = this.wrapV;
  59487. return newTexture;
  59488. };
  59489. DynamicTexture.prototype._rebuild = function () {
  59490. this.update();
  59491. };
  59492. return DynamicTexture;
  59493. }(BABYLON.Texture));
  59494. BABYLON.DynamicTexture = DynamicTexture;
  59495. })(BABYLON || (BABYLON = {}));
  59496. //# sourceMappingURL=babylon.dynamicTexture.js.map
  59497. var BABYLON;
  59498. (function (BABYLON) {
  59499. var VideoTexture = /** @class */ (function (_super) {
  59500. __extends(VideoTexture, _super);
  59501. /**
  59502. * Creates a video texture.
  59503. * Sample : https://doc.babylonjs.com/how_to/video_texture
  59504. * @param {string | null} name optional name, will detect from video source, if not defined
  59505. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  59506. * @param {BABYLON.Scene} scene is obviously the current scene.
  59507. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  59508. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  59509. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  59510. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  59511. */
  59512. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  59513. if (generateMipMaps === void 0) { generateMipMaps = false; }
  59514. if (invertY === void 0) { invertY = false; }
  59515. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59516. if (settings === void 0) { settings = {
  59517. autoPlay: true,
  59518. loop: true,
  59519. autoUpdateTexture: true,
  59520. }; }
  59521. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59522. _this._createInternalTexture = function () {
  59523. if (_this._texture != null) {
  59524. return;
  59525. }
  59526. if (!_this._engine.needPOTTextures ||
  59527. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  59528. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59529. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59530. }
  59531. else {
  59532. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59533. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59534. _this._generateMipMaps = false;
  59535. }
  59536. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  59537. _this._texture.isReady = true;
  59538. _this._updateInternalTexture();
  59539. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  59540. _this.onLoadObservable.notifyObservers(_this);
  59541. }
  59542. };
  59543. _this.reset = function () {
  59544. if (_this._texture == null) {
  59545. return;
  59546. }
  59547. _this._texture.dispose();
  59548. _this._texture = null;
  59549. };
  59550. _this._updateInternalTexture = function (e) {
  59551. if (_this._texture == null || !_this._texture.isReady) {
  59552. return;
  59553. }
  59554. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  59555. return;
  59556. }
  59557. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  59558. };
  59559. _this._engine = _this.getScene().getEngine();
  59560. _this._generateMipMaps = generateMipMaps;
  59561. _this._samplingMode = samplingMode;
  59562. _this.autoUpdateTexture = settings.autoUpdateTexture;
  59563. _this.name = name || _this._getName(src);
  59564. _this.video = _this._getVideo(src);
  59565. if (settings.autoPlay !== undefined) {
  59566. _this.video.autoplay = settings.autoPlay;
  59567. }
  59568. if (settings.loop !== undefined) {
  59569. _this.video.loop = settings.loop;
  59570. }
  59571. _this.video.addEventListener("canplay", _this._createInternalTexture);
  59572. _this.video.addEventListener("paused", _this._updateInternalTexture);
  59573. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  59574. _this.video.addEventListener("emptied", _this.reset);
  59575. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  59576. _this._createInternalTexture();
  59577. }
  59578. return _this;
  59579. }
  59580. VideoTexture.prototype._getName = function (src) {
  59581. if (src instanceof HTMLVideoElement) {
  59582. return src.currentSrc;
  59583. }
  59584. if (typeof src === "object") {
  59585. return src.toString();
  59586. }
  59587. return src;
  59588. };
  59589. ;
  59590. VideoTexture.prototype._getVideo = function (src) {
  59591. if (src instanceof HTMLVideoElement) {
  59592. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  59593. return src;
  59594. }
  59595. var video = document.createElement("video");
  59596. if (typeof src === "string") {
  59597. BABYLON.Tools.SetCorsBehavior(src, video);
  59598. video.src = src;
  59599. }
  59600. else {
  59601. BABYLON.Tools.SetCorsBehavior(src[0], video);
  59602. src.forEach(function (url) {
  59603. var source = document.createElement("source");
  59604. source.src = url;
  59605. video.appendChild(source);
  59606. });
  59607. }
  59608. return video;
  59609. };
  59610. ;
  59611. /**
  59612. * Internal method to initiate `update`.
  59613. */
  59614. VideoTexture.prototype._rebuild = function () {
  59615. this.update();
  59616. };
  59617. /**
  59618. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  59619. */
  59620. VideoTexture.prototype.update = function () {
  59621. if (!this.autoUpdateTexture) {
  59622. // Expecting user to call `updateTexture` manually
  59623. return;
  59624. }
  59625. this.updateTexture(true);
  59626. };
  59627. /**
  59628. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  59629. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  59630. */
  59631. VideoTexture.prototype.updateTexture = function (isVisible) {
  59632. if (!isVisible) {
  59633. return;
  59634. }
  59635. if (this.video.paused) {
  59636. return;
  59637. }
  59638. this._updateInternalTexture();
  59639. };
  59640. /**
  59641. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  59642. * @param url New url.
  59643. */
  59644. VideoTexture.prototype.updateURL = function (url) {
  59645. this.video.src = url;
  59646. };
  59647. VideoTexture.prototype.dispose = function () {
  59648. _super.prototype.dispose.call(this);
  59649. this.video.removeEventListener("canplay", this._createInternalTexture);
  59650. this.video.removeEventListener("paused", this._updateInternalTexture);
  59651. this.video.removeEventListener("seeked", this._updateInternalTexture);
  59652. this.video.removeEventListener("emptied", this.reset);
  59653. this.video.pause();
  59654. };
  59655. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  59656. var video = document.createElement("video");
  59657. var constraintsDeviceId;
  59658. if (constraints && constraints.deviceId) {
  59659. constraintsDeviceId = {
  59660. exact: constraints.deviceId,
  59661. };
  59662. }
  59663. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  59664. if (navigator.mediaDevices) {
  59665. navigator.mediaDevices.getUserMedia({ video: constraints })
  59666. .then(function (stream) {
  59667. if (video.mozSrcObject !== undefined) {
  59668. // hack for Firefox < 19
  59669. video.mozSrcObject = stream;
  59670. }
  59671. else {
  59672. video.srcObject = stream;
  59673. }
  59674. var onPlaying = function () {
  59675. if (onReady) {
  59676. onReady(new VideoTexture("video", video, scene, true, true));
  59677. }
  59678. video.removeEventListener("playing", onPlaying);
  59679. };
  59680. video.addEventListener("playing", onPlaying);
  59681. video.play();
  59682. })
  59683. .catch(function (err) {
  59684. BABYLON.Tools.Error(err.name);
  59685. });
  59686. }
  59687. else {
  59688. navigator.getUserMedia =
  59689. navigator.getUserMedia ||
  59690. navigator.webkitGetUserMedia ||
  59691. navigator.mozGetUserMedia ||
  59692. navigator.msGetUserMedia;
  59693. if (navigator.getUserMedia) {
  59694. navigator.getUserMedia({
  59695. video: {
  59696. deviceId: constraintsDeviceId,
  59697. width: {
  59698. min: (constraints && constraints.minWidth) || 256,
  59699. max: (constraints && constraints.maxWidth) || 640,
  59700. },
  59701. height: {
  59702. min: (constraints && constraints.minHeight) || 256,
  59703. max: (constraints && constraints.maxHeight) || 480,
  59704. },
  59705. },
  59706. }, function (stream) {
  59707. if (video.mozSrcObject !== undefined) {
  59708. // hack for Firefox < 19
  59709. video.mozSrcObject = stream;
  59710. }
  59711. else {
  59712. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  59713. }
  59714. video.play();
  59715. if (onReady) {
  59716. onReady(new VideoTexture("video", video, scene, true, true));
  59717. }
  59718. }, function (e) {
  59719. BABYLON.Tools.Error(e.name);
  59720. });
  59721. }
  59722. }
  59723. };
  59724. return VideoTexture;
  59725. }(BABYLON.Texture));
  59726. BABYLON.VideoTexture = VideoTexture;
  59727. })(BABYLON || (BABYLON = {}));
  59728. //# sourceMappingURL=babylon.videoTexture.js.map
  59729. var BABYLON;
  59730. (function (BABYLON) {
  59731. var RawTexture = /** @class */ (function (_super) {
  59732. __extends(RawTexture, _super);
  59733. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  59734. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59735. if (invertY === void 0) { invertY = false; }
  59736. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59737. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59738. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59739. _this.format = format;
  59740. _this._engine = scene.getEngine();
  59741. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  59742. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59743. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59744. return _this;
  59745. }
  59746. RawTexture.prototype.update = function (data) {
  59747. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  59748. };
  59749. // Statics
  59750. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59751. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59752. if (invertY === void 0) { invertY = false; }
  59753. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59754. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  59755. };
  59756. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59757. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59758. if (invertY === void 0) { invertY = false; }
  59759. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59760. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59761. };
  59762. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59763. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59764. if (invertY === void 0) { invertY = false; }
  59765. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59766. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59767. };
  59768. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59769. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59770. if (invertY === void 0) { invertY = false; }
  59771. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59772. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59773. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  59774. };
  59775. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59776. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59777. if (invertY === void 0) { invertY = false; }
  59778. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59779. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59780. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  59781. };
  59782. return RawTexture;
  59783. }(BABYLON.Texture));
  59784. BABYLON.RawTexture = RawTexture;
  59785. })(BABYLON || (BABYLON = {}));
  59786. //# sourceMappingURL=babylon.rawTexture.js.map
  59787. var BABYLON;
  59788. (function (BABYLON) {
  59789. /**
  59790. * PostProcess can be used to apply a shader to a texture after it has been rendered
  59791. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  59792. */
  59793. var PostProcess = /** @class */ (function () {
  59794. /**
  59795. * Creates a new instance of @see PostProcess
  59796. * @param name The name of the PostProcess.
  59797. * @param fragmentUrl The url of the fragment shader to be used.
  59798. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  59799. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  59800. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  59801. * @param camera The camera to apply the render pass to.
  59802. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  59803. * @param engine The engine which the post process will be applied. (default: current engine)
  59804. * @param reusable If the post process can be reused on the same frame. (default: false)
  59805. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  59806. * @param textureType Type of textures used when performing the post process. (default: 0)
  59807. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  59808. * @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
  59809. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  59810. */
  59811. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  59812. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  59813. if (defines === void 0) { defines = null; }
  59814. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59815. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  59816. if (blockCompilation === void 0) { blockCompilation = false; }
  59817. this.name = name;
  59818. /**
  59819. * Width of the texture to apply the post process on
  59820. */
  59821. this.width = -1;
  59822. /**
  59823. * Height of the texture to apply the post process on
  59824. */
  59825. this.height = -1;
  59826. /**
  59827. * If the buffer needs to be cleared before applying the post process. (default: true)
  59828. * Should be set to false if shader will overwrite all previous pixels.
  59829. */
  59830. this.autoClear = true;
  59831. /**
  59832. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  59833. */
  59834. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  59835. /**
  59836. * Animations to be used for the post processing
  59837. */
  59838. this.animations = new Array();
  59839. /**
  59840. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  59841. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  59842. */
  59843. this.enablePixelPerfectMode = false;
  59844. /**
  59845. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  59846. */
  59847. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  59848. /**
  59849. * Force textures to be a power of two (default: false)
  59850. */
  59851. this.alwaysForcePOT = false;
  59852. /**
  59853. * Number of sample textures (default: 1)
  59854. */
  59855. this.samples = 1;
  59856. /**
  59857. * Modify the scale of the post process to be the same as the viewport (default: false)
  59858. */
  59859. this.adaptScaleToCurrentViewport = false;
  59860. this._reusable = false;
  59861. /**
  59862. * Smart array of input and output textures for the post process.
  59863. */
  59864. this._textures = new BABYLON.SmartArray(2);
  59865. /**
  59866. * The index in _textures that corresponds to the output texture.
  59867. */
  59868. this._currentRenderTextureInd = 0;
  59869. this._scaleRatio = new BABYLON.Vector2(1, 1);
  59870. this._texelSize = BABYLON.Vector2.Zero();
  59871. // Events
  59872. /**
  59873. * An event triggered when the postprocess is activated.
  59874. * @type {BABYLON.Observable}
  59875. */
  59876. this.onActivateObservable = new BABYLON.Observable();
  59877. /**
  59878. * An event triggered when the postprocess changes its size.
  59879. * @type {BABYLON.Observable}
  59880. */
  59881. this.onSizeChangedObservable = new BABYLON.Observable();
  59882. /**
  59883. * An event triggered when the postprocess applies its effect.
  59884. * @type {BABYLON.Observable}
  59885. */
  59886. this.onApplyObservable = new BABYLON.Observable();
  59887. /**
  59888. * An event triggered before rendering the postprocess
  59889. * @type {BABYLON.Observable}
  59890. */
  59891. this.onBeforeRenderObservable = new BABYLON.Observable();
  59892. /**
  59893. * An event triggered after rendering the postprocess
  59894. * @type {BABYLON.Observable}
  59895. */
  59896. this.onAfterRenderObservable = new BABYLON.Observable();
  59897. if (camera != null) {
  59898. this._camera = camera;
  59899. this._scene = camera.getScene();
  59900. camera.attachPostProcess(this);
  59901. this._engine = this._scene.getEngine();
  59902. this._scene.postProcesses.push(this);
  59903. }
  59904. else if (engine) {
  59905. this._engine = engine;
  59906. this._engine.postProcesses.push(this);
  59907. }
  59908. this._options = options;
  59909. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  59910. this._reusable = reusable || false;
  59911. this._textureType = textureType;
  59912. this._samplers = samplers || [];
  59913. this._samplers.push("textureSampler");
  59914. this._fragmentUrl = fragmentUrl;
  59915. this._vertexUrl = vertexUrl;
  59916. this._parameters = parameters || [];
  59917. this._parameters.push("scale");
  59918. this._indexParameters = indexParameters;
  59919. if (!blockCompilation) {
  59920. this.updateEffect(defines);
  59921. }
  59922. }
  59923. Object.defineProperty(PostProcess.prototype, "onActivate", {
  59924. /**
  59925. * A function that is added to the onActivateObservable
  59926. */
  59927. set: function (callback) {
  59928. if (this._onActivateObserver) {
  59929. this.onActivateObservable.remove(this._onActivateObserver);
  59930. }
  59931. if (callback) {
  59932. this._onActivateObserver = this.onActivateObservable.add(callback);
  59933. }
  59934. },
  59935. enumerable: true,
  59936. configurable: true
  59937. });
  59938. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  59939. /**
  59940. * A function that is added to the onSizeChangedObservable
  59941. */
  59942. set: function (callback) {
  59943. if (this._onSizeChangedObserver) {
  59944. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  59945. }
  59946. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  59947. },
  59948. enumerable: true,
  59949. configurable: true
  59950. });
  59951. Object.defineProperty(PostProcess.prototype, "onApply", {
  59952. /**
  59953. * A function that is added to the onApplyObservable
  59954. */
  59955. set: function (callback) {
  59956. if (this._onApplyObserver) {
  59957. this.onApplyObservable.remove(this._onApplyObserver);
  59958. }
  59959. this._onApplyObserver = this.onApplyObservable.add(callback);
  59960. },
  59961. enumerable: true,
  59962. configurable: true
  59963. });
  59964. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  59965. /**
  59966. * A function that is added to the onBeforeRenderObservable
  59967. */
  59968. set: function (callback) {
  59969. if (this._onBeforeRenderObserver) {
  59970. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59971. }
  59972. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59973. },
  59974. enumerable: true,
  59975. configurable: true
  59976. });
  59977. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  59978. /**
  59979. * A function that is added to the onAfterRenderObservable
  59980. */
  59981. set: function (callback) {
  59982. if (this._onAfterRenderObserver) {
  59983. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59984. }
  59985. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59986. },
  59987. enumerable: true,
  59988. configurable: true
  59989. });
  59990. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  59991. /**
  59992. * 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
  59993. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  59994. */
  59995. get: function () {
  59996. return this._textures.data[this._currentRenderTextureInd];
  59997. },
  59998. set: function (value) {
  59999. this._forcedOutputTexture = value;
  60000. },
  60001. enumerable: true,
  60002. configurable: true
  60003. });
  60004. /**
  60005. * Gets the camera which post process is applied to.
  60006. * @returns The camera the post process is applied to.
  60007. */
  60008. PostProcess.prototype.getCamera = function () {
  60009. return this._camera;
  60010. };
  60011. Object.defineProperty(PostProcess.prototype, "texelSize", {
  60012. /**
  60013. * Gets the texel size of the postprocess.
  60014. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  60015. */
  60016. get: function () {
  60017. if (this._shareOutputWithPostProcess) {
  60018. return this._shareOutputWithPostProcess.texelSize;
  60019. }
  60020. if (this._forcedOutputTexture) {
  60021. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  60022. }
  60023. return this._texelSize;
  60024. },
  60025. enumerable: true,
  60026. configurable: true
  60027. });
  60028. /**
  60029. * Gets the engine which this post process belongs to.
  60030. * @returns The engine the post process was enabled with.
  60031. */
  60032. PostProcess.prototype.getEngine = function () {
  60033. return this._engine;
  60034. };
  60035. /**
  60036. * The effect that is created when initializing the post process.
  60037. * @returns The created effect corrisponding the the postprocess.
  60038. */
  60039. PostProcess.prototype.getEffect = function () {
  60040. return this._effect;
  60041. };
  60042. /**
  60043. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  60044. * @param postProcess The post process to share the output with.
  60045. * @returns This post process.
  60046. */
  60047. PostProcess.prototype.shareOutputWith = function (postProcess) {
  60048. this._disposeTextures();
  60049. this._shareOutputWithPostProcess = postProcess;
  60050. return this;
  60051. };
  60052. /**
  60053. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  60054. * This should be called if the post process that shares output with this post process is disabled/disposed.
  60055. */
  60056. PostProcess.prototype.useOwnOutput = function () {
  60057. if (this._textures.length == 0) {
  60058. this._textures = new BABYLON.SmartArray(2);
  60059. }
  60060. this._shareOutputWithPostProcess = null;
  60061. };
  60062. /**
  60063. * Updates the effect with the current post process compile time values and recompiles the shader.
  60064. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  60065. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  60066. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  60067. * @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
  60068. * @param onCompiled Called when the shader has been compiled.
  60069. * @param onError Called if there is an error when compiling a shader.
  60070. */
  60071. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  60072. if (defines === void 0) { defines = null; }
  60073. if (uniforms === void 0) { uniforms = null; }
  60074. if (samplers === void 0) { samplers = null; }
  60075. 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);
  60076. };
  60077. /**
  60078. * The post process is reusable if it can be used multiple times within one frame.
  60079. * @returns If the post process is reusable
  60080. */
  60081. PostProcess.prototype.isReusable = function () {
  60082. return this._reusable;
  60083. };
  60084. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  60085. PostProcess.prototype.markTextureDirty = function () {
  60086. this.width = -1;
  60087. };
  60088. /**
  60089. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  60090. * 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.
  60091. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  60092. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  60093. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  60094. */
  60095. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  60096. var _this = this;
  60097. if (sourceTexture === void 0) { sourceTexture = null; }
  60098. camera = camera || this._camera;
  60099. var scene = camera.getScene();
  60100. var engine = scene.getEngine();
  60101. var maxSize = engine.getCaps().maxTextureSize;
  60102. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  60103. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  60104. // 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
  60105. var webVRCamera = camera.parent;
  60106. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  60107. requiredWidth /= 2;
  60108. }
  60109. var desiredWidth = (this._options.width || requiredWidth);
  60110. var desiredHeight = this._options.height || requiredHeight;
  60111. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  60112. if (this.adaptScaleToCurrentViewport) {
  60113. var currentViewport = engine.currentViewport;
  60114. if (currentViewport) {
  60115. desiredWidth *= currentViewport.width;
  60116. desiredHeight *= currentViewport.height;
  60117. }
  60118. }
  60119. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  60120. if (!this._options.width) {
  60121. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  60122. }
  60123. if (!this._options.height) {
  60124. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  60125. }
  60126. }
  60127. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  60128. if (this._textures.length > 0) {
  60129. for (var i = 0; i < this._textures.length; i++) {
  60130. this._engine._releaseTexture(this._textures.data[i]);
  60131. }
  60132. this._textures.reset();
  60133. }
  60134. this.width = desiredWidth;
  60135. this.height = desiredHeight;
  60136. var textureSize = { width: this.width, height: this.height };
  60137. var textureOptions = {
  60138. generateMipMaps: false,
  60139. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  60140. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  60141. samplingMode: this.renderTargetSamplingMode,
  60142. type: this._textureType
  60143. };
  60144. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60145. if (this._reusable) {
  60146. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60147. }
  60148. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  60149. this.onSizeChangedObservable.notifyObservers(this);
  60150. }
  60151. this._textures.forEach(function (texture) {
  60152. if (texture.samples !== _this.samples) {
  60153. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  60154. }
  60155. });
  60156. }
  60157. var target;
  60158. if (this._shareOutputWithPostProcess) {
  60159. target = this._shareOutputWithPostProcess.inputTexture;
  60160. }
  60161. else if (this._forcedOutputTexture) {
  60162. target = this._forcedOutputTexture;
  60163. this.width = this._forcedOutputTexture.width;
  60164. this.height = this._forcedOutputTexture.height;
  60165. }
  60166. else {
  60167. target = this.inputTexture;
  60168. }
  60169. // Bind the input of this post process to be used as the output of the previous post process.
  60170. if (this.enablePixelPerfectMode) {
  60171. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  60172. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  60173. }
  60174. else {
  60175. this._scaleRatio.copyFromFloats(1, 1);
  60176. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  60177. }
  60178. this.onActivateObservable.notifyObservers(camera);
  60179. // Clear
  60180. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  60181. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  60182. }
  60183. if (this._reusable) {
  60184. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  60185. }
  60186. };
  60187. Object.defineProperty(PostProcess.prototype, "isSupported", {
  60188. /**
  60189. * If the post process is supported.
  60190. */
  60191. get: function () {
  60192. return this._effect.isSupported;
  60193. },
  60194. enumerable: true,
  60195. configurable: true
  60196. });
  60197. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  60198. /**
  60199. * The aspect ratio of the output texture.
  60200. */
  60201. get: function () {
  60202. if (this._shareOutputWithPostProcess) {
  60203. return this._shareOutputWithPostProcess.aspectRatio;
  60204. }
  60205. if (this._forcedOutputTexture) {
  60206. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  60207. }
  60208. return this.width / this.height;
  60209. },
  60210. enumerable: true,
  60211. configurable: true
  60212. });
  60213. /**
  60214. * Get a value indicating if the post-process is ready to be used
  60215. * @returns true if the post-process is ready (shader is compiled)
  60216. */
  60217. PostProcess.prototype.isReady = function () {
  60218. return this._effect && this._effect.isReady();
  60219. };
  60220. /**
  60221. * Binds all textures and uniforms to the shader, this will be run on every pass.
  60222. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  60223. */
  60224. PostProcess.prototype.apply = function () {
  60225. // Check
  60226. if (!this._effect || !this._effect.isReady())
  60227. return null;
  60228. // States
  60229. this._engine.enableEffect(this._effect);
  60230. this._engine.setState(false);
  60231. this._engine.setDepthBuffer(false);
  60232. this._engine.setDepthWrite(false);
  60233. // Alpha
  60234. this._engine.setAlphaMode(this.alphaMode);
  60235. if (this.alphaConstants) {
  60236. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  60237. }
  60238. // Bind the output texture of the preivous post process as the input to this post process.
  60239. var source;
  60240. if (this._shareOutputWithPostProcess) {
  60241. source = this._shareOutputWithPostProcess.inputTexture;
  60242. }
  60243. else if (this._forcedOutputTexture) {
  60244. source = this._forcedOutputTexture;
  60245. }
  60246. else {
  60247. source = this.inputTexture;
  60248. }
  60249. this._effect._bindTexture("textureSampler", source);
  60250. // Parameters
  60251. this._effect.setVector2("scale", this._scaleRatio);
  60252. this.onApplyObservable.notifyObservers(this._effect);
  60253. return this._effect;
  60254. };
  60255. PostProcess.prototype._disposeTextures = function () {
  60256. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  60257. return;
  60258. }
  60259. if (this._textures.length > 0) {
  60260. for (var i = 0; i < this._textures.length; i++) {
  60261. this._engine._releaseTexture(this._textures.data[i]);
  60262. }
  60263. }
  60264. this._textures.dispose();
  60265. };
  60266. /**
  60267. * Disposes the post process.
  60268. * @param camera The camera to dispose the post process on.
  60269. */
  60270. PostProcess.prototype.dispose = function (camera) {
  60271. camera = camera || this._camera;
  60272. this._disposeTextures();
  60273. if (this._scene) {
  60274. var index_1 = this._scene.postProcesses.indexOf(this);
  60275. if (index_1 !== -1) {
  60276. this._scene.postProcesses.splice(index_1, 1);
  60277. }
  60278. }
  60279. else {
  60280. var index_2 = this._engine.postProcesses.indexOf(this);
  60281. if (index_2 !== -1) {
  60282. this._engine.postProcesses.splice(index_2, 1);
  60283. }
  60284. }
  60285. if (!camera) {
  60286. return;
  60287. }
  60288. camera.detachPostProcess(this);
  60289. var index = camera._postProcesses.indexOf(this);
  60290. if (index === 0 && camera._postProcesses.length > 0) {
  60291. var firstPostProcess = this._camera._getFirstPostProcess();
  60292. if (firstPostProcess) {
  60293. firstPostProcess.markTextureDirty();
  60294. }
  60295. }
  60296. this.onActivateObservable.clear();
  60297. this.onAfterRenderObservable.clear();
  60298. this.onApplyObservable.clear();
  60299. this.onBeforeRenderObservable.clear();
  60300. this.onSizeChangedObservable.clear();
  60301. };
  60302. return PostProcess;
  60303. }());
  60304. BABYLON.PostProcess = PostProcess;
  60305. })(BABYLON || (BABYLON = {}));
  60306. //# sourceMappingURL=babylon.postProcess.js.map
  60307. var BABYLON;
  60308. (function (BABYLON) {
  60309. var PassPostProcess = /** @class */ (function (_super) {
  60310. __extends(PassPostProcess, _super);
  60311. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  60312. if (camera === void 0) { camera = null; }
  60313. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60314. if (blockCompilation === void 0) { blockCompilation = false; }
  60315. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  60316. }
  60317. return PassPostProcess;
  60318. }(BABYLON.PostProcess));
  60319. BABYLON.PassPostProcess = PassPostProcess;
  60320. })(BABYLON || (BABYLON = {}));
  60321. //# sourceMappingURL=babylon.passPostProcess.js.map
  60322. var __assign = (this && this.__assign) || Object.assign || function(t) {
  60323. for (var s, i = 1, n = arguments.length; i < n; i++) {
  60324. s = arguments[i];
  60325. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  60326. t[p] = s[p];
  60327. }
  60328. return t;
  60329. };
  60330. var BABYLON;
  60331. (function (BABYLON) {
  60332. /**
  60333. * Default implementation of @see IShadowGenerator.
  60334. * This is the main object responsible of generating shadows in the framework.
  60335. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  60336. */
  60337. var ShadowGenerator = /** @class */ (function () {
  60338. /**
  60339. * Creates a ShadowGenerator object.
  60340. * A ShadowGenerator is the required tool to use the shadows.
  60341. * Each light casting shadows needs to use its own ShadowGenerator.
  60342. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  60343. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  60344. * @param light The light object generating the shadows.
  60345. * @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.
  60346. */
  60347. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  60348. this._bias = 0.00005;
  60349. this._normalBias = 0;
  60350. this._blurBoxOffset = 1;
  60351. this._blurScale = 2;
  60352. this._blurKernel = 1;
  60353. this._useKernelBlur = false;
  60354. this._filter = ShadowGenerator.FILTER_NONE;
  60355. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  60356. this._contactHardeningLightSizeUVRatio = 0.1;
  60357. this._darkness = 0;
  60358. this._transparencyShadow = false;
  60359. /**
  60360. * Controls the extent to which the shadows fade out at the edge of the frustum
  60361. * Used only by directionals and spots
  60362. */
  60363. this.frustumEdgeFalloff = 0;
  60364. /**
  60365. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  60366. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  60367. * It might on the other hand introduce peter panning.
  60368. */
  60369. this.forceBackFacesOnly = false;
  60370. this._lightDirection = BABYLON.Vector3.Zero();
  60371. this._viewMatrix = BABYLON.Matrix.Zero();
  60372. this._projectionMatrix = BABYLON.Matrix.Zero();
  60373. this._transformMatrix = BABYLON.Matrix.Zero();
  60374. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60375. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60376. this._currentFaceIndex = 0;
  60377. this._currentFaceIndexCache = 0;
  60378. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  60379. this._mapSize = mapSize;
  60380. this._light = light;
  60381. this._scene = light.getScene();
  60382. light._shadowGenerator = this;
  60383. // Texture type fallback from float to int if not supported.
  60384. var caps = this._scene.getEngine().getCaps();
  60385. if (!useFullFloatFirst) {
  60386. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60387. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60388. }
  60389. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60390. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60391. }
  60392. else {
  60393. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60394. }
  60395. }
  60396. else {
  60397. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60398. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60399. }
  60400. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60401. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60402. }
  60403. else {
  60404. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60405. }
  60406. }
  60407. this._initializeGenerator();
  60408. this._applyFilterValues();
  60409. }
  60410. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  60411. /**
  60412. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  60413. */
  60414. get: function () {
  60415. return this._bias;
  60416. },
  60417. /**
  60418. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  60419. */
  60420. set: function (bias) {
  60421. this._bias = bias;
  60422. },
  60423. enumerable: true,
  60424. configurable: true
  60425. });
  60426. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  60427. /**
  60428. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  60429. */
  60430. get: function () {
  60431. return this._normalBias;
  60432. },
  60433. /**
  60434. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  60435. */
  60436. set: function (normalBias) {
  60437. this._normalBias = normalBias;
  60438. },
  60439. enumerable: true,
  60440. configurable: true
  60441. });
  60442. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  60443. /**
  60444. * Gets the blur box offset: offset applied during the blur pass.
  60445. * Only usefull if useKernelBlur = false
  60446. */
  60447. get: function () {
  60448. return this._blurBoxOffset;
  60449. },
  60450. /**
  60451. * Sets the blur box offset: offset applied during the blur pass.
  60452. * Only usefull if useKernelBlur = false
  60453. */
  60454. set: function (value) {
  60455. if (this._blurBoxOffset === value) {
  60456. return;
  60457. }
  60458. this._blurBoxOffset = value;
  60459. this._disposeBlurPostProcesses();
  60460. },
  60461. enumerable: true,
  60462. configurable: true
  60463. });
  60464. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  60465. /**
  60466. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  60467. * 2 means half of the size.
  60468. */
  60469. get: function () {
  60470. return this._blurScale;
  60471. },
  60472. /**
  60473. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  60474. * 2 means half of the size.
  60475. */
  60476. set: function (value) {
  60477. if (this._blurScale === value) {
  60478. return;
  60479. }
  60480. this._blurScale = value;
  60481. this._disposeBlurPostProcesses();
  60482. },
  60483. enumerable: true,
  60484. configurable: true
  60485. });
  60486. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  60487. /**
  60488. * Gets the blur kernel: kernel size of the blur pass.
  60489. * Only usefull if useKernelBlur = true
  60490. */
  60491. get: function () {
  60492. return this._blurKernel;
  60493. },
  60494. /**
  60495. * Sets the blur kernel: kernel size of the blur pass.
  60496. * Only usefull if useKernelBlur = true
  60497. */
  60498. set: function (value) {
  60499. if (this._blurKernel === value) {
  60500. return;
  60501. }
  60502. this._blurKernel = value;
  60503. this._disposeBlurPostProcesses();
  60504. },
  60505. enumerable: true,
  60506. configurable: true
  60507. });
  60508. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  60509. /**
  60510. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  60511. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60512. */
  60513. get: function () {
  60514. return this._useKernelBlur;
  60515. },
  60516. /**
  60517. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  60518. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60519. */
  60520. set: function (value) {
  60521. if (this._useKernelBlur === value) {
  60522. return;
  60523. }
  60524. this._useKernelBlur = value;
  60525. this._disposeBlurPostProcesses();
  60526. },
  60527. enumerable: true,
  60528. configurable: true
  60529. });
  60530. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  60531. /**
  60532. * Gets the depth scale used in ESM mode.
  60533. */
  60534. get: function () {
  60535. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  60536. },
  60537. /**
  60538. * Sets the depth scale used in ESM mode.
  60539. * This can override the scale stored on the light.
  60540. */
  60541. set: function (value) {
  60542. this._depthScale = value;
  60543. },
  60544. enumerable: true,
  60545. configurable: true
  60546. });
  60547. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  60548. /**
  60549. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  60550. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60551. */
  60552. get: function () {
  60553. return this._filter;
  60554. },
  60555. /**
  60556. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  60557. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60558. */
  60559. set: function (value) {
  60560. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  60561. if (this._light.needCube()) {
  60562. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60563. this.useExponentialShadowMap = true;
  60564. return;
  60565. }
  60566. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60567. this.useCloseExponentialShadowMap = true;
  60568. return;
  60569. }
  60570. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  60571. this.usePoissonSampling = true;
  60572. return;
  60573. }
  60574. }
  60575. // Weblg1 fallback for PCF.
  60576. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  60577. if (this._scene.getEngine().webGLVersion === 1) {
  60578. this.usePoissonSampling = true;
  60579. return;
  60580. }
  60581. }
  60582. if (this._filter === value) {
  60583. return;
  60584. }
  60585. this._filter = value;
  60586. this._disposeBlurPostProcesses();
  60587. this._applyFilterValues();
  60588. this._light._markMeshesAsLightDirty();
  60589. },
  60590. enumerable: true,
  60591. configurable: true
  60592. });
  60593. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  60594. /**
  60595. * Gets if the current filter is set to Poisson Sampling.
  60596. */
  60597. get: function () {
  60598. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  60599. },
  60600. /**
  60601. * Sets the current filter to Poisson Sampling.
  60602. */
  60603. set: function (value) {
  60604. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  60605. return;
  60606. }
  60607. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  60608. },
  60609. enumerable: true,
  60610. configurable: true
  60611. });
  60612. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  60613. /**
  60614. * Gets if the current filter is set to VSM.
  60615. * DEPRECATED. Should use useExponentialShadowMap instead.
  60616. */
  60617. get: function () {
  60618. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60619. return this.useExponentialShadowMap;
  60620. },
  60621. /**
  60622. * Sets the current filter is to VSM.
  60623. * DEPRECATED. Should use useExponentialShadowMap instead.
  60624. */
  60625. set: function (value) {
  60626. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60627. this.useExponentialShadowMap = value;
  60628. },
  60629. enumerable: true,
  60630. configurable: true
  60631. });
  60632. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  60633. /**
  60634. * Gets if the current filter is set to blurred VSM.
  60635. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60636. */
  60637. get: function () {
  60638. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60639. return this.useBlurExponentialShadowMap;
  60640. },
  60641. /**
  60642. * Sets the current filter is to blurred VSM.
  60643. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60644. */
  60645. set: function (value) {
  60646. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60647. this.useBlurExponentialShadowMap = value;
  60648. },
  60649. enumerable: true,
  60650. configurable: true
  60651. });
  60652. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  60653. /**
  60654. * Gets if the current filter is set to ESM.
  60655. */
  60656. get: function () {
  60657. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  60658. },
  60659. /**
  60660. * Sets the current filter is to ESM.
  60661. */
  60662. set: function (value) {
  60663. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  60664. return;
  60665. }
  60666. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60667. },
  60668. enumerable: true,
  60669. configurable: true
  60670. });
  60671. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  60672. /**
  60673. * Gets if the current filter is set to filtered ESM.
  60674. */
  60675. get: function () {
  60676. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  60677. },
  60678. /**
  60679. * Gets if the current filter is set to filtered ESM.
  60680. */
  60681. set: function (value) {
  60682. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60683. return;
  60684. }
  60685. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60686. },
  60687. enumerable: true,
  60688. configurable: true
  60689. });
  60690. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  60691. /**
  60692. * Gets if the current filter is set to "close ESM" (using the inverse of the
  60693. * exponential to prevent steep falloff artifacts).
  60694. */
  60695. get: function () {
  60696. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  60697. },
  60698. /**
  60699. * Sets the current filter to "close ESM" (using the inverse of the
  60700. * exponential to prevent steep falloff artifacts).
  60701. */
  60702. set: function (value) {
  60703. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  60704. return;
  60705. }
  60706. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60707. },
  60708. enumerable: true,
  60709. configurable: true
  60710. });
  60711. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  60712. /**
  60713. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  60714. * exponential to prevent steep falloff artifacts).
  60715. */
  60716. get: function () {
  60717. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  60718. },
  60719. /**
  60720. * Sets the current filter to filtered "close ESM" (using the inverse of the
  60721. * exponential to prevent steep falloff artifacts).
  60722. */
  60723. set: function (value) {
  60724. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60725. return;
  60726. }
  60727. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60728. },
  60729. enumerable: true,
  60730. configurable: true
  60731. });
  60732. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  60733. /**
  60734. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  60735. */
  60736. get: function () {
  60737. return this.filter === ShadowGenerator.FILTER_PCF;
  60738. },
  60739. /**
  60740. * Sets the current filter to "PCF" (percentage closer filtering).
  60741. */
  60742. set: function (value) {
  60743. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  60744. return;
  60745. }
  60746. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  60747. },
  60748. enumerable: true,
  60749. configurable: true
  60750. });
  60751. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  60752. /**
  60753. * Gets the PCF or PCSS Quality.
  60754. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  60755. */
  60756. get: function () {
  60757. return this._filteringQuality;
  60758. },
  60759. /**
  60760. * Sets the PCF or PCSS Quality.
  60761. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  60762. */
  60763. set: function (filteringQuality) {
  60764. this._filteringQuality = filteringQuality;
  60765. },
  60766. enumerable: true,
  60767. configurable: true
  60768. });
  60769. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  60770. /**
  60771. * Gets if the current filter is set to "PCSS" (contact hardening).
  60772. */
  60773. get: function () {
  60774. return this.filter === ShadowGenerator.FILTER_PCSS;
  60775. },
  60776. /**
  60777. * Sets the current filter to "PCSS" (contact hardening).
  60778. */
  60779. set: function (value) {
  60780. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  60781. return;
  60782. }
  60783. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  60784. },
  60785. enumerable: true,
  60786. configurable: true
  60787. });
  60788. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  60789. /**
  60790. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  60791. * Using a ratio helps keeping shape stability independently of the map size.
  60792. *
  60793. * It does not account for the light projection as it was having too much
  60794. * instability during the light setup or during light position changes.
  60795. *
  60796. * Only valid if useContactHardeningShadow is true.
  60797. */
  60798. get: function () {
  60799. return this._contactHardeningLightSizeUVRatio;
  60800. },
  60801. /**
  60802. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  60803. * Using a ratio helps keeping shape stability independently of the map size.
  60804. *
  60805. * It does not account for the light projection as it was having too much
  60806. * instability during the light setup or during light position changes.
  60807. *
  60808. * Only valid if useContactHardeningShadow is true.
  60809. */
  60810. set: function (contactHardeningLightSizeUVRatio) {
  60811. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  60812. },
  60813. enumerable: true,
  60814. configurable: true
  60815. });
  60816. /**
  60817. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  60818. * 0 means strongest and 1 would means no shadow.
  60819. * @returns the darkness.
  60820. */
  60821. ShadowGenerator.prototype.getDarkness = function () {
  60822. return this._darkness;
  60823. };
  60824. /**
  60825. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  60826. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  60827. * @returns the shadow generator allowing fluent coding.
  60828. */
  60829. ShadowGenerator.prototype.setDarkness = function (darkness) {
  60830. if (darkness >= 1.0)
  60831. this._darkness = 1.0;
  60832. else if (darkness <= 0.0)
  60833. this._darkness = 0.0;
  60834. else
  60835. this._darkness = darkness;
  60836. return this;
  60837. };
  60838. /**
  60839. * Sets the ability to have transparent shadow (boolean).
  60840. * @param transparent True if transparent else False
  60841. * @returns the shadow generator allowing fluent coding
  60842. */
  60843. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  60844. this._transparencyShadow = transparent;
  60845. return this;
  60846. };
  60847. /**
  60848. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  60849. * @returns The render target texture if present otherwise, null
  60850. */
  60851. ShadowGenerator.prototype.getShadowMap = function () {
  60852. return this._shadowMap;
  60853. };
  60854. /**
  60855. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  60856. * @returns The render target texture if the shadow map is present otherwise, null
  60857. */
  60858. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  60859. if (this._shadowMap2) {
  60860. return this._shadowMap2;
  60861. }
  60862. return this._shadowMap;
  60863. };
  60864. /**
  60865. * Helper function to add a mesh and its descendants to the list of shadow casters.
  60866. * @param mesh Mesh to add
  60867. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  60868. * @returns the Shadow Generator itself
  60869. */
  60870. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  60871. if (includeDescendants === void 0) { includeDescendants = true; }
  60872. if (!this._shadowMap) {
  60873. return this;
  60874. }
  60875. if (!this._shadowMap.renderList) {
  60876. this._shadowMap.renderList = [];
  60877. }
  60878. this._shadowMap.renderList.push(mesh);
  60879. if (includeDescendants) {
  60880. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  60881. }
  60882. return this;
  60883. var _a;
  60884. };
  60885. /**
  60886. * Helper function to remove a mesh and its descendants from the list of shadow casters
  60887. * @param mesh Mesh to remove
  60888. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  60889. * @returns the Shadow Generator itself
  60890. */
  60891. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  60892. if (includeDescendants === void 0) { includeDescendants = true; }
  60893. if (!this._shadowMap || !this._shadowMap.renderList) {
  60894. return this;
  60895. }
  60896. var index = this._shadowMap.renderList.indexOf(mesh);
  60897. if (index !== -1) {
  60898. this._shadowMap.renderList.splice(index, 1);
  60899. }
  60900. if (includeDescendants) {
  60901. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  60902. var child = _a[_i];
  60903. this.removeShadowCaster(child);
  60904. }
  60905. }
  60906. return this;
  60907. };
  60908. /**
  60909. * Returns the associated light object.
  60910. * @returns the light generating the shadow
  60911. */
  60912. ShadowGenerator.prototype.getLight = function () {
  60913. return this._light;
  60914. };
  60915. ShadowGenerator.prototype._initializeGenerator = function () {
  60916. this._light._markMeshesAsLightDirty();
  60917. this._initializeShadowMap();
  60918. };
  60919. ShadowGenerator.prototype._initializeShadowMap = function () {
  60920. var _this = this;
  60921. // Render target
  60922. var engine = this._scene.getEngine();
  60923. if (engine.webGLVersion > 1) {
  60924. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  60925. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  60926. }
  60927. else {
  60928. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  60929. }
  60930. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60931. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60932. this._shadowMap.anisotropicFilteringLevel = 1;
  60933. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60934. this._shadowMap.renderParticles = false;
  60935. this._shadowMap.ignoreCameraViewport = true;
  60936. // Record Face Index before render.
  60937. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  60938. _this._currentFaceIndex = faceIndex;
  60939. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  60940. engine.setColorWrite(false);
  60941. }
  60942. });
  60943. // Custom render function.
  60944. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  60945. // Blur if required afer render.
  60946. this._shadowMap.onAfterUnbindObservable.add(function () {
  60947. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  60948. engine.setColorWrite(true);
  60949. }
  60950. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  60951. return;
  60952. }
  60953. var shadowMap = _this.getShadowMapForRendering();
  60954. if (shadowMap) {
  60955. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  60956. }
  60957. });
  60958. // Clear according to the chosen filter.
  60959. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  60960. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60961. this._shadowMap.onClearObservable.add(function (engine) {
  60962. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  60963. engine.clear(clearOne, false, true, false);
  60964. }
  60965. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  60966. engine.clear(clearZero, true, true, false);
  60967. }
  60968. else {
  60969. engine.clear(clearOne, true, true, false);
  60970. }
  60971. });
  60972. };
  60973. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  60974. var _this = this;
  60975. var engine = this._scene.getEngine();
  60976. var targetSize = this._mapSize / this.blurScale;
  60977. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  60978. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  60979. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60980. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60981. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60982. }
  60983. if (this.useKernelBlur) {
  60984. 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);
  60985. this._kernelBlurXPostprocess.width = targetSize;
  60986. this._kernelBlurXPostprocess.height = targetSize;
  60987. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  60988. effect.setTexture("textureSampler", _this._shadowMap);
  60989. });
  60990. 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);
  60991. this._kernelBlurXPostprocess.autoClear = false;
  60992. this._kernelBlurYPostprocess.autoClear = false;
  60993. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60994. this._kernelBlurXPostprocess.packedFloat = true;
  60995. this._kernelBlurYPostprocess.packedFloat = true;
  60996. }
  60997. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  60998. }
  60999. else {
  61000. 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);
  61001. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  61002. effect.setFloat2("screenSize", targetSize, targetSize);
  61003. effect.setTexture("textureSampler", _this._shadowMap);
  61004. });
  61005. this._boxBlurPostprocess.autoClear = false;
  61006. this._blurPostProcesses = [this._boxBlurPostprocess];
  61007. }
  61008. };
  61009. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61010. var index;
  61011. var engine = this._scene.getEngine();
  61012. if (depthOnlySubMeshes.length) {
  61013. engine.setColorWrite(false);
  61014. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61015. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  61016. }
  61017. engine.setColorWrite(true);
  61018. }
  61019. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61020. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  61021. }
  61022. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61023. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  61024. }
  61025. if (this._transparencyShadow) {
  61026. for (index = 0; index < transparentSubMeshes.length; index++) {
  61027. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  61028. }
  61029. }
  61030. };
  61031. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  61032. var _this = this;
  61033. var mesh = subMesh.getRenderingMesh();
  61034. var scene = this._scene;
  61035. var engine = scene.getEngine();
  61036. var material = subMesh.getMaterial();
  61037. if (!material) {
  61038. return;
  61039. }
  61040. // Culling
  61041. engine.setState(material.backFaceCulling);
  61042. // Managing instances
  61043. var batch = mesh._getInstancesRenderList(subMesh._id);
  61044. if (batch.mustReturn) {
  61045. return;
  61046. }
  61047. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  61048. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  61049. engine.enableEffect(this._effect);
  61050. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  61051. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  61052. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  61053. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61054. this._effect.setVector3("lightData", this._cachedDirection);
  61055. }
  61056. else {
  61057. this._effect.setVector3("lightData", this._cachedPosition);
  61058. }
  61059. if (scene.activeCamera) {
  61060. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  61061. }
  61062. // Alpha test
  61063. if (material && material.needAlphaTesting()) {
  61064. var alphaTexture = material.getAlphaTestTexture();
  61065. if (alphaTexture) {
  61066. this._effect.setTexture("diffuseSampler", alphaTexture);
  61067. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  61068. }
  61069. }
  61070. // Bones
  61071. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61072. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  61073. }
  61074. if (this.forceBackFacesOnly) {
  61075. engine.setState(true, 0, false, true);
  61076. }
  61077. // Draw
  61078. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61079. if (this.forceBackFacesOnly) {
  61080. engine.setState(true, 0, false, false);
  61081. }
  61082. }
  61083. else {
  61084. // Need to reset refresh rate of the shadowMap
  61085. if (this._shadowMap) {
  61086. this._shadowMap.resetRefreshCounter();
  61087. }
  61088. }
  61089. };
  61090. ShadowGenerator.prototype._applyFilterValues = function () {
  61091. if (!this._shadowMap) {
  61092. return;
  61093. }
  61094. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  61095. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61096. }
  61097. else {
  61098. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61099. }
  61100. };
  61101. /**
  61102. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61103. * @param onCompiled Callback triggered at the and of the effects compilation
  61104. * @param options Sets of optional options forcing the compilation with different modes
  61105. */
  61106. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  61107. var _this = this;
  61108. var localOptions = __assign({ useInstances: false }, options);
  61109. var shadowMap = this.getShadowMap();
  61110. if (!shadowMap) {
  61111. if (onCompiled) {
  61112. onCompiled(this);
  61113. }
  61114. return;
  61115. }
  61116. var renderList = shadowMap.renderList;
  61117. if (!renderList) {
  61118. if (onCompiled) {
  61119. onCompiled(this);
  61120. }
  61121. return;
  61122. }
  61123. var subMeshes = new Array();
  61124. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  61125. var mesh = renderList_1[_i];
  61126. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  61127. }
  61128. if (subMeshes.length === 0) {
  61129. if (onCompiled) {
  61130. onCompiled(this);
  61131. }
  61132. return;
  61133. }
  61134. var currentIndex = 0;
  61135. var checkReady = function () {
  61136. if (!_this._scene || !_this._scene.getEngine()) {
  61137. return;
  61138. }
  61139. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  61140. currentIndex++;
  61141. if (currentIndex >= subMeshes.length) {
  61142. if (onCompiled) {
  61143. onCompiled(_this);
  61144. }
  61145. return;
  61146. }
  61147. }
  61148. setTimeout(checkReady, 16);
  61149. };
  61150. checkReady();
  61151. };
  61152. /**
  61153. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61154. * @param options Sets of optional options forcing the compilation with different modes
  61155. * @returns A promise that resolves when the compilation completes
  61156. */
  61157. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  61158. var _this = this;
  61159. return new Promise(function (resolve) {
  61160. _this.forceCompilation(function () {
  61161. resolve();
  61162. }, options);
  61163. });
  61164. };
  61165. /**
  61166. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  61167. * @param subMesh The submesh we want to render in the shadow map
  61168. * @param useInstances Defines wether will draw in the map using instances
  61169. * @returns true if ready otherwise, false
  61170. */
  61171. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  61172. var defines = [];
  61173. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61174. defines.push("#define FLOAT");
  61175. }
  61176. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61177. defines.push("#define ESM");
  61178. }
  61179. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  61180. defines.push("#define DEPTHTEXTURE");
  61181. }
  61182. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61183. var mesh = subMesh.getMesh();
  61184. var material = subMesh.getMaterial();
  61185. // Normal bias.
  61186. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  61187. attribs.push(BABYLON.VertexBuffer.NormalKind);
  61188. defines.push("#define NORMAL");
  61189. if (mesh.nonUniformScaling) {
  61190. defines.push("#define NONUNIFORMSCALING");
  61191. }
  61192. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61193. defines.push("#define DIRECTIONINLIGHTDATA");
  61194. }
  61195. }
  61196. // Alpha test
  61197. if (material && material.needAlphaTesting()) {
  61198. var alphaTexture = material.getAlphaTestTexture();
  61199. if (alphaTexture) {
  61200. defines.push("#define ALPHATEST");
  61201. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61202. attribs.push(BABYLON.VertexBuffer.UVKind);
  61203. defines.push("#define UV1");
  61204. }
  61205. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61206. if (alphaTexture.coordinatesIndex === 1) {
  61207. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61208. defines.push("#define UV2");
  61209. }
  61210. }
  61211. }
  61212. }
  61213. // Bones
  61214. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61215. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61216. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61217. if (mesh.numBoneInfluencers > 4) {
  61218. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61219. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61220. }
  61221. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61222. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61223. }
  61224. else {
  61225. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61226. }
  61227. // Instances
  61228. if (useInstances) {
  61229. defines.push("#define INSTANCES");
  61230. attribs.push("world0");
  61231. attribs.push("world1");
  61232. attribs.push("world2");
  61233. attribs.push("world3");
  61234. }
  61235. // Get correct effect
  61236. var join = defines.join("\n");
  61237. if (this._cachedDefines !== join) {
  61238. this._cachedDefines = join;
  61239. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  61240. }
  61241. if (!this._effect.isReady()) {
  61242. return false;
  61243. }
  61244. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61245. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  61246. this._initializeBlurRTTAndPostProcesses();
  61247. }
  61248. }
  61249. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  61250. return false;
  61251. }
  61252. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  61253. return false;
  61254. }
  61255. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  61256. return false;
  61257. }
  61258. return true;
  61259. };
  61260. /**
  61261. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  61262. * @param defines Defines of the material we want to update
  61263. * @param lightIndex Index of the light in the enabled light list of the material
  61264. */
  61265. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  61266. var scene = this._scene;
  61267. var light = this._light;
  61268. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61269. return;
  61270. }
  61271. defines["SHADOW" + lightIndex] = true;
  61272. if (this.useContactHardeningShadow) {
  61273. defines["SHADOWPCSS" + lightIndex] = true;
  61274. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  61275. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  61276. }
  61277. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  61278. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  61279. }
  61280. // else default to high.
  61281. }
  61282. if (this.usePercentageCloserFiltering) {
  61283. defines["SHADOWPCF" + lightIndex] = true;
  61284. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  61285. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  61286. }
  61287. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  61288. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  61289. }
  61290. // else default to high.
  61291. }
  61292. else if (this.usePoissonSampling) {
  61293. defines["SHADOWPOISSON" + lightIndex] = true;
  61294. }
  61295. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61296. defines["SHADOWESM" + lightIndex] = true;
  61297. }
  61298. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61299. defines["SHADOWCLOSEESM" + lightIndex] = true;
  61300. }
  61301. if (light.needCube()) {
  61302. defines["SHADOWCUBE" + lightIndex] = true;
  61303. }
  61304. };
  61305. /**
  61306. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  61307. * defined in the generator but impacting the effect).
  61308. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  61309. * @param effect The effect we are binfing the information for
  61310. */
  61311. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  61312. var light = this._light;
  61313. var scene = this._scene;
  61314. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61315. return;
  61316. }
  61317. var camera = scene.activeCamera;
  61318. if (!camera) {
  61319. return;
  61320. }
  61321. var shadowMap = this.getShadowMap();
  61322. if (!shadowMap) {
  61323. return;
  61324. }
  61325. if (!light.needCube()) {
  61326. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  61327. }
  61328. // Only PCF uses depth stencil texture.
  61329. if (this._filter === ShadowGenerator.FILTER_PCF) {
  61330. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61331. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  61332. }
  61333. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  61334. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61335. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  61336. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  61337. }
  61338. else {
  61339. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61340. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  61341. }
  61342. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  61343. };
  61344. /**
  61345. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  61346. * (eq to shadow prjection matrix * light transform matrix)
  61347. * @returns The transform matrix used to create the shadow map
  61348. */
  61349. ShadowGenerator.prototype.getTransformMatrix = function () {
  61350. var scene = this._scene;
  61351. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  61352. return this._transformMatrix;
  61353. }
  61354. this._currentRenderID = scene.getRenderId();
  61355. this._currentFaceIndexCache = this._currentFaceIndex;
  61356. var lightPosition = this._light.position;
  61357. if (this._light.computeTransformedInformation()) {
  61358. lightPosition = this._light.transformedPosition;
  61359. }
  61360. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  61361. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  61362. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  61363. }
  61364. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  61365. this._cachedPosition.copyFrom(lightPosition);
  61366. this._cachedDirection.copyFrom(this._lightDirection);
  61367. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  61368. var shadowMap = this.getShadowMap();
  61369. if (shadowMap) {
  61370. var renderList = shadowMap.renderList;
  61371. if (renderList) {
  61372. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  61373. }
  61374. }
  61375. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  61376. }
  61377. return this._transformMatrix;
  61378. };
  61379. /**
  61380. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  61381. * Cube and 2D textures for instance.
  61382. */
  61383. ShadowGenerator.prototype.recreateShadowMap = function () {
  61384. var shadowMap = this._shadowMap;
  61385. if (!shadowMap) {
  61386. return;
  61387. }
  61388. // Track render list.
  61389. var renderList = shadowMap.renderList;
  61390. // Clean up existing data.
  61391. this._disposeRTTandPostProcesses();
  61392. // Reinitializes.
  61393. this._initializeGenerator();
  61394. // Reaffect the filter to ensure a correct fallback if necessary.
  61395. this.filter = this.filter;
  61396. // Reaffect the filter.
  61397. this._applyFilterValues();
  61398. // Reaffect Render List.
  61399. this._shadowMap.renderList = renderList;
  61400. };
  61401. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  61402. if (this._shadowMap2) {
  61403. this._shadowMap2.dispose();
  61404. this._shadowMap2 = null;
  61405. }
  61406. if (this._boxBlurPostprocess) {
  61407. this._boxBlurPostprocess.dispose();
  61408. this._boxBlurPostprocess = null;
  61409. }
  61410. if (this._kernelBlurXPostprocess) {
  61411. this._kernelBlurXPostprocess.dispose();
  61412. this._kernelBlurXPostprocess = null;
  61413. }
  61414. if (this._kernelBlurYPostprocess) {
  61415. this._kernelBlurYPostprocess.dispose();
  61416. this._kernelBlurYPostprocess = null;
  61417. }
  61418. this._blurPostProcesses = [];
  61419. };
  61420. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  61421. if (this._shadowMap) {
  61422. this._shadowMap.dispose();
  61423. this._shadowMap = null;
  61424. }
  61425. this._disposeBlurPostProcesses();
  61426. };
  61427. /**
  61428. * Disposes the ShadowGenerator.
  61429. * Returns nothing.
  61430. */
  61431. ShadowGenerator.prototype.dispose = function () {
  61432. this._disposeRTTandPostProcesses();
  61433. if (this._light) {
  61434. this._light._shadowGenerator = null;
  61435. this._light._markMeshesAsLightDirty();
  61436. }
  61437. };
  61438. /**
  61439. * Serializes the shadow generator setup to a json object.
  61440. * @returns The serialized JSON object
  61441. */
  61442. ShadowGenerator.prototype.serialize = function () {
  61443. var serializationObject = {};
  61444. var shadowMap = this.getShadowMap();
  61445. if (!shadowMap) {
  61446. return serializationObject;
  61447. }
  61448. serializationObject.lightId = this._light.id;
  61449. serializationObject.mapSize = shadowMap.getRenderSize();
  61450. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  61451. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  61452. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61453. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61454. serializationObject.usePoissonSampling = this.usePoissonSampling;
  61455. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  61456. serializationObject.depthScale = this.depthScale;
  61457. serializationObject.darkness = this.getDarkness();
  61458. serializationObject.blurBoxOffset = this.blurBoxOffset;
  61459. serializationObject.blurKernel = this.blurKernel;
  61460. serializationObject.blurScale = this.blurScale;
  61461. serializationObject.useKernelBlur = this.useKernelBlur;
  61462. serializationObject.transparencyShadow = this._transparencyShadow;
  61463. serializationObject.bias = this.bias;
  61464. serializationObject.normalBias = this.normalBias;
  61465. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  61466. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  61467. serializationObject.filteringQuality = this.filteringQuality;
  61468. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  61469. serializationObject.renderList = [];
  61470. if (shadowMap.renderList) {
  61471. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  61472. var mesh = shadowMap.renderList[meshIndex];
  61473. serializationObject.renderList.push(mesh.id);
  61474. }
  61475. }
  61476. return serializationObject;
  61477. };
  61478. /**
  61479. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  61480. * @param parsedShadowGenerator The JSON object to parse
  61481. * @param scene The scene to create the shadow map for
  61482. * @returns The parsed shadow generator
  61483. */
  61484. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  61485. //casting to point light, as light is missing the position attr and typescript complains.
  61486. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  61487. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  61488. var shadowMap = shadowGenerator.getShadowMap();
  61489. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  61490. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  61491. meshes.forEach(function (mesh) {
  61492. if (!shadowMap) {
  61493. return;
  61494. }
  61495. if (!shadowMap.renderList) {
  61496. shadowMap.renderList = [];
  61497. }
  61498. shadowMap.renderList.push(mesh);
  61499. });
  61500. }
  61501. if (parsedShadowGenerator.usePoissonSampling) {
  61502. shadowGenerator.usePoissonSampling = true;
  61503. }
  61504. else if (parsedShadowGenerator.useExponentialShadowMap) {
  61505. shadowGenerator.useExponentialShadowMap = true;
  61506. }
  61507. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  61508. shadowGenerator.useBlurExponentialShadowMap = true;
  61509. }
  61510. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  61511. shadowGenerator.useCloseExponentialShadowMap = true;
  61512. }
  61513. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  61514. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  61515. }
  61516. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  61517. shadowGenerator.usePercentageCloserFiltering = true;
  61518. }
  61519. else if (parsedShadowGenerator.useContactHardeningShadow) {
  61520. shadowGenerator.useContactHardeningShadow = true;
  61521. }
  61522. if (parsedShadowGenerator.filteringQuality) {
  61523. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  61524. }
  61525. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  61526. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  61527. }
  61528. else if (parsedShadowGenerator.useVarianceShadowMap) {
  61529. shadowGenerator.useExponentialShadowMap = true;
  61530. }
  61531. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  61532. shadowGenerator.useBlurExponentialShadowMap = true;
  61533. }
  61534. if (parsedShadowGenerator.depthScale) {
  61535. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  61536. }
  61537. if (parsedShadowGenerator.blurScale) {
  61538. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  61539. }
  61540. if (parsedShadowGenerator.blurBoxOffset) {
  61541. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  61542. }
  61543. if (parsedShadowGenerator.useKernelBlur) {
  61544. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  61545. }
  61546. if (parsedShadowGenerator.blurKernel) {
  61547. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  61548. }
  61549. if (parsedShadowGenerator.bias !== undefined) {
  61550. shadowGenerator.bias = parsedShadowGenerator.bias;
  61551. }
  61552. if (parsedShadowGenerator.normalBias !== undefined) {
  61553. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  61554. }
  61555. if (parsedShadowGenerator.darkness) {
  61556. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  61557. }
  61558. if (parsedShadowGenerator.transparencyShadow) {
  61559. shadowGenerator.setTransparencyShadow(true);
  61560. }
  61561. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  61562. return shadowGenerator;
  61563. };
  61564. /**
  61565. * Shadow generator mode None: no filtering applied.
  61566. */
  61567. ShadowGenerator.FILTER_NONE = 0;
  61568. /**
  61569. * Shadow generator mode ESM: Exponential Shadow Mapping.
  61570. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  61571. */
  61572. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  61573. /**
  61574. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  61575. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  61576. */
  61577. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  61578. /**
  61579. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  61580. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  61581. */
  61582. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  61583. /**
  61584. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  61585. * edge artifacts on steep falloff.
  61586. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  61587. */
  61588. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  61589. /**
  61590. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  61591. * edge artifacts on steep falloff.
  61592. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  61593. */
  61594. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  61595. /**
  61596. * Shadow generator mode PCF: Percentage Closer Filtering
  61597. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  61598. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  61599. */
  61600. ShadowGenerator.FILTER_PCF = 6;
  61601. /**
  61602. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  61603. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  61604. * Contact Hardening
  61605. */
  61606. ShadowGenerator.FILTER_PCSS = 7;
  61607. /**
  61608. * Reserved for PCF and PCSS
  61609. * Highest Quality.
  61610. *
  61611. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  61612. *
  61613. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  61614. */
  61615. ShadowGenerator.QUALITY_HIGH = 0;
  61616. /**
  61617. * Reserved for PCF and PCSS
  61618. * Good tradeoff for quality/perf cross devices
  61619. *
  61620. * Execute PCF on a 3*3 kernel.
  61621. *
  61622. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  61623. */
  61624. ShadowGenerator.QUALITY_MEDIUM = 1;
  61625. /**
  61626. * Reserved for PCF and PCSS
  61627. * The lowest quality but the fastest.
  61628. *
  61629. * Execute PCF on a 1*1 kernel.
  61630. *
  61631. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  61632. */
  61633. ShadowGenerator.QUALITY_LOW = 2;
  61634. return ShadowGenerator;
  61635. }());
  61636. BABYLON.ShadowGenerator = ShadowGenerator;
  61637. })(BABYLON || (BABYLON = {}));
  61638. //# sourceMappingURL=babylon.shadowGenerator.js.map
  61639. var BABYLON;
  61640. (function (BABYLON) {
  61641. var DefaultLoadingScreen = /** @class */ (function () {
  61642. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  61643. if (_loadingText === void 0) { _loadingText = ""; }
  61644. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  61645. var _this = this;
  61646. this._renderingCanvas = _renderingCanvas;
  61647. this._loadingText = _loadingText;
  61648. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  61649. // Resize
  61650. this._resizeLoadingUI = function () {
  61651. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  61652. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  61653. if (!_this._loadingDiv) {
  61654. return;
  61655. }
  61656. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  61657. _this._loadingDiv.style.left = canvasRect.left + "px";
  61658. _this._loadingDiv.style.top = canvasRect.top + "px";
  61659. _this._loadingDiv.style.width = canvasRect.width + "px";
  61660. _this._loadingDiv.style.height = canvasRect.height + "px";
  61661. };
  61662. }
  61663. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  61664. if (this._loadingDiv) {
  61665. // Do not add a loading screen if there is already one
  61666. return;
  61667. }
  61668. this._loadingDiv = document.createElement("div");
  61669. this._loadingDiv.id = "babylonjsLoadingDiv";
  61670. this._loadingDiv.style.opacity = "0";
  61671. this._loadingDiv.style.transition = "opacity 1.5s ease";
  61672. this._loadingDiv.style.pointerEvents = "none";
  61673. // Loading text
  61674. this._loadingTextDiv = document.createElement("div");
  61675. this._loadingTextDiv.style.position = "absolute";
  61676. this._loadingTextDiv.style.left = "0";
  61677. this._loadingTextDiv.style.top = "50%";
  61678. this._loadingTextDiv.style.marginTop = "80px";
  61679. this._loadingTextDiv.style.width = "100%";
  61680. this._loadingTextDiv.style.height = "20px";
  61681. this._loadingTextDiv.style.fontFamily = "Arial";
  61682. this._loadingTextDiv.style.fontSize = "14px";
  61683. this._loadingTextDiv.style.color = "white";
  61684. this._loadingTextDiv.style.textAlign = "center";
  61685. this._loadingTextDiv.innerHTML = "Loading";
  61686. this._loadingDiv.appendChild(this._loadingTextDiv);
  61687. //set the predefined text
  61688. this._loadingTextDiv.innerHTML = this._loadingText;
  61689. // Generating keyframes
  61690. var style = document.createElement('style');
  61691. style.type = 'text/css';
  61692. 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 }";
  61693. style.innerHTML = keyFrames;
  61694. document.getElementsByTagName('head')[0].appendChild(style);
  61695. // Loading img
  61696. var imgBack = new Image();
  61697. 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";
  61698. imgBack.style.position = "absolute";
  61699. imgBack.style.left = "50%";
  61700. imgBack.style.top = "50%";
  61701. imgBack.style.marginLeft = "-60px";
  61702. imgBack.style.marginTop = "-60px";
  61703. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  61704. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  61705. imgBack.style.transformOrigin = "50% 50%";
  61706. imgBack.style.webkitTransformOrigin = "50% 50%";
  61707. this._loadingDiv.appendChild(imgBack);
  61708. this._resizeLoadingUI();
  61709. window.addEventListener("resize", this._resizeLoadingUI);
  61710. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  61711. document.body.appendChild(this._loadingDiv);
  61712. this._loadingDiv.style.opacity = "1";
  61713. };
  61714. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  61715. var _this = this;
  61716. if (!this._loadingDiv) {
  61717. return;
  61718. }
  61719. var onTransitionEnd = function () {
  61720. if (!_this._loadingDiv) {
  61721. return;
  61722. }
  61723. document.body.removeChild(_this._loadingDiv);
  61724. window.removeEventListener("resize", _this._resizeLoadingUI);
  61725. _this._loadingDiv = null;
  61726. };
  61727. this._loadingDiv.style.opacity = "0";
  61728. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  61729. };
  61730. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  61731. set: function (text) {
  61732. this._loadingText = text;
  61733. if (this._loadingTextDiv) {
  61734. this._loadingTextDiv.innerHTML = this._loadingText;
  61735. }
  61736. },
  61737. enumerable: true,
  61738. configurable: true
  61739. });
  61740. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  61741. get: function () {
  61742. return this._loadingDivBackgroundColor;
  61743. },
  61744. set: function (color) {
  61745. this._loadingDivBackgroundColor = color;
  61746. if (!this._loadingDiv) {
  61747. return;
  61748. }
  61749. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  61750. },
  61751. enumerable: true,
  61752. configurable: true
  61753. });
  61754. return DefaultLoadingScreen;
  61755. }());
  61756. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  61757. })(BABYLON || (BABYLON = {}));
  61758. //# sourceMappingURL=babylon.loadingScreen.js.map
  61759. var BABYLON;
  61760. (function (BABYLON) {
  61761. var SceneLoaderProgressEvent = /** @class */ (function () {
  61762. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  61763. this.lengthComputable = lengthComputable;
  61764. this.loaded = loaded;
  61765. this.total = total;
  61766. }
  61767. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  61768. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  61769. };
  61770. return SceneLoaderProgressEvent;
  61771. }());
  61772. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  61773. var SceneLoader = /** @class */ (function () {
  61774. function SceneLoader() {
  61775. }
  61776. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  61777. get: function () {
  61778. return 0;
  61779. },
  61780. enumerable: true,
  61781. configurable: true
  61782. });
  61783. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  61784. get: function () {
  61785. return 1;
  61786. },
  61787. enumerable: true,
  61788. configurable: true
  61789. });
  61790. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  61791. get: function () {
  61792. return 2;
  61793. },
  61794. enumerable: true,
  61795. configurable: true
  61796. });
  61797. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  61798. get: function () {
  61799. return 3;
  61800. },
  61801. enumerable: true,
  61802. configurable: true
  61803. });
  61804. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  61805. get: function () {
  61806. return SceneLoader._ForceFullSceneLoadingForIncremental;
  61807. },
  61808. set: function (value) {
  61809. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  61810. },
  61811. enumerable: true,
  61812. configurable: true
  61813. });
  61814. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  61815. get: function () {
  61816. return SceneLoader._ShowLoadingScreen;
  61817. },
  61818. set: function (value) {
  61819. SceneLoader._ShowLoadingScreen = value;
  61820. },
  61821. enumerable: true,
  61822. configurable: true
  61823. });
  61824. Object.defineProperty(SceneLoader, "loggingLevel", {
  61825. get: function () {
  61826. return SceneLoader._loggingLevel;
  61827. },
  61828. set: function (value) {
  61829. SceneLoader._loggingLevel = value;
  61830. },
  61831. enumerable: true,
  61832. configurable: true
  61833. });
  61834. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  61835. get: function () {
  61836. return SceneLoader._CleanBoneMatrixWeights;
  61837. },
  61838. set: function (value) {
  61839. SceneLoader._CleanBoneMatrixWeights = value;
  61840. },
  61841. enumerable: true,
  61842. configurable: true
  61843. });
  61844. SceneLoader._getDefaultPlugin = function () {
  61845. return SceneLoader._registeredPlugins[".babylon"];
  61846. };
  61847. SceneLoader._getPluginForExtension = function (extension) {
  61848. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  61849. if (registeredPlugin) {
  61850. return registeredPlugin;
  61851. }
  61852. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  61853. return SceneLoader._getDefaultPlugin();
  61854. };
  61855. SceneLoader._getPluginForDirectLoad = function (data) {
  61856. for (var extension in SceneLoader._registeredPlugins) {
  61857. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  61858. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  61859. return SceneLoader._registeredPlugins[extension];
  61860. }
  61861. }
  61862. return SceneLoader._getDefaultPlugin();
  61863. };
  61864. SceneLoader._getPluginForFilename = function (sceneFilename) {
  61865. if (sceneFilename.name) {
  61866. sceneFilename = sceneFilename.name;
  61867. }
  61868. var queryStringPosition = sceneFilename.indexOf("?");
  61869. if (queryStringPosition !== -1) {
  61870. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  61871. }
  61872. var dotPosition = sceneFilename.lastIndexOf(".");
  61873. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  61874. return SceneLoader._getPluginForExtension(extension);
  61875. };
  61876. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  61877. SceneLoader._getDirectLoad = function (sceneFilename) {
  61878. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  61879. return sceneFilename.substr(5);
  61880. }
  61881. return null;
  61882. };
  61883. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  61884. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  61885. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  61886. var plugin;
  61887. if (registeredPlugin.plugin.createPlugin) {
  61888. plugin = registeredPlugin.plugin.createPlugin();
  61889. }
  61890. else {
  61891. plugin = registeredPlugin.plugin;
  61892. }
  61893. var useArrayBuffer = registeredPlugin.isBinary;
  61894. var database;
  61895. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  61896. var dataCallback = function (data, responseURL) {
  61897. if (scene.isDisposed) {
  61898. onError("Scene has been disposed");
  61899. return;
  61900. }
  61901. scene.database = database;
  61902. onSuccess(plugin, data, responseURL);
  61903. };
  61904. var request = null;
  61905. var pluginDisposed = false;
  61906. var onDisposeObservable = plugin.onDisposeObservable;
  61907. if (onDisposeObservable) {
  61908. onDisposeObservable.add(function () {
  61909. pluginDisposed = true;
  61910. if (request) {
  61911. request.abort();
  61912. request = null;
  61913. }
  61914. onDispose();
  61915. });
  61916. }
  61917. var manifestChecked = function () {
  61918. if (pluginDisposed) {
  61919. return;
  61920. }
  61921. var url = rootUrl + sceneFilename;
  61922. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  61923. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  61924. } : undefined, database, useArrayBuffer, function (request, exception) {
  61925. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  61926. });
  61927. };
  61928. if (directLoad) {
  61929. dataCallback(directLoad);
  61930. return plugin;
  61931. }
  61932. if (rootUrl.indexOf("file:") === -1) {
  61933. if (scene.getEngine().enableOfflineSupport) {
  61934. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  61935. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  61936. }
  61937. else {
  61938. manifestChecked();
  61939. }
  61940. }
  61941. else {
  61942. var fileOrString = sceneFilename;
  61943. if (fileOrString.name) {
  61944. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  61945. }
  61946. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  61947. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  61948. }
  61949. else {
  61950. onError("Unable to find file named " + sceneFilename);
  61951. }
  61952. }
  61953. return plugin;
  61954. };
  61955. // Public functions
  61956. SceneLoader.GetPluginForExtension = function (extension) {
  61957. return SceneLoader._getPluginForExtension(extension).plugin;
  61958. };
  61959. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  61960. return !!SceneLoader._registeredPlugins[extension];
  61961. };
  61962. SceneLoader.RegisterPlugin = function (plugin) {
  61963. if (typeof plugin.extensions === "string") {
  61964. var extension = plugin.extensions;
  61965. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61966. plugin: plugin,
  61967. isBinary: false
  61968. };
  61969. }
  61970. else {
  61971. var extensions = plugin.extensions;
  61972. Object.keys(extensions).forEach(function (extension) {
  61973. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61974. plugin: plugin,
  61975. isBinary: extensions[extension].isBinary
  61976. };
  61977. });
  61978. }
  61979. };
  61980. /**
  61981. * Import meshes into a scene
  61982. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61983. * @param rootUrl a string that defines the root url for scene and resources
  61984. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61985. * @param scene the instance of BABYLON.Scene to append to
  61986. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  61987. * @param onProgress a callback with a progress event for each file being loaded
  61988. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61989. * @param pluginExtension the extension used to determine the plugin
  61990. * @returns The loaded plugin
  61991. */
  61992. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61993. if (onSuccess === void 0) { onSuccess = null; }
  61994. if (onProgress === void 0) { onProgress = null; }
  61995. if (onError === void 0) { onError = null; }
  61996. if (pluginExtension === void 0) { pluginExtension = null; }
  61997. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61998. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61999. return null;
  62000. }
  62001. var loadingToken = {};
  62002. scene._addPendingData(loadingToken);
  62003. var disposeHandler = function () {
  62004. scene._removePendingData(loadingToken);
  62005. };
  62006. var errorHandler = function (message, exception) {
  62007. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  62008. if (onError) {
  62009. onError(scene, errorMessage, exception);
  62010. }
  62011. else {
  62012. BABYLON.Tools.Error(errorMessage);
  62013. // should the exception be thrown?
  62014. }
  62015. disposeHandler();
  62016. };
  62017. var progressHandler = onProgress ? function (event) {
  62018. try {
  62019. onProgress(event);
  62020. }
  62021. catch (e) {
  62022. errorHandler("Error in onProgress callback", e);
  62023. }
  62024. } : undefined;
  62025. var successHandler = function (meshes, particleSystems, skeletons) {
  62026. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  62027. if (onSuccess) {
  62028. try {
  62029. onSuccess(meshes, particleSystems, skeletons);
  62030. }
  62031. catch (e) {
  62032. errorHandler("Error in onSuccess callback", e);
  62033. }
  62034. }
  62035. scene._removePendingData(loadingToken);
  62036. };
  62037. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62038. if (plugin.rewriteRootURL) {
  62039. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  62040. }
  62041. if (sceneFilename === "") {
  62042. if (sceneFilename === "") {
  62043. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62044. }
  62045. }
  62046. if (plugin.importMesh) {
  62047. var syncedPlugin = plugin;
  62048. var meshes = new Array();
  62049. var particleSystems = new Array();
  62050. var skeletons = new Array();
  62051. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  62052. return;
  62053. }
  62054. scene.loadingPluginName = plugin.name;
  62055. successHandler(meshes, particleSystems, skeletons);
  62056. }
  62057. else {
  62058. var asyncedPlugin = plugin;
  62059. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  62060. scene.loadingPluginName = plugin.name;
  62061. successHandler(result.meshes, result.particleSystems, result.skeletons);
  62062. }).catch(function (error) {
  62063. errorHandler(error.message, error);
  62064. });
  62065. }
  62066. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62067. };
  62068. /**
  62069. * Import meshes into a scene
  62070. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62071. * @param rootUrl a string that defines the root url for scene and resources
  62072. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62073. * @param scene the instance of BABYLON.Scene to append to
  62074. * @param onProgress a callback with a progress event for each file being loaded
  62075. * @param pluginExtension the extension used to determine the plugin
  62076. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  62077. */
  62078. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62079. if (onProgress === void 0) { onProgress = null; }
  62080. if (pluginExtension === void 0) { pluginExtension = null; }
  62081. return new Promise(function (resolve, reject) {
  62082. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  62083. resolve({
  62084. meshes: meshes,
  62085. particleSystems: particleSystems,
  62086. skeletons: skeletons
  62087. });
  62088. }, onProgress, function (scene, message, exception) {
  62089. reject(exception || new Error(message));
  62090. });
  62091. });
  62092. };
  62093. /**
  62094. * Load a scene
  62095. * @param rootUrl a string that defines the root url for scene and resources
  62096. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62097. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62098. * @param onSuccess a callback with the scene when import succeeds
  62099. * @param onProgress a callback with a progress event for each file being loaded
  62100. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62101. * @param pluginExtension the extension used to determine the plugin
  62102. * @returns The loaded plugin
  62103. */
  62104. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  62105. if (onSuccess === void 0) { onSuccess = null; }
  62106. if (onProgress === void 0) { onProgress = null; }
  62107. if (onError === void 0) { onError = null; }
  62108. if (pluginExtension === void 0) { pluginExtension = null; }
  62109. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  62110. };
  62111. /**
  62112. * Load a scene
  62113. * @param rootUrl a string that defines the root url for scene and resources
  62114. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62115. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62116. * @param onProgress a callback with a progress event for each file being loaded
  62117. * @param pluginExtension the extension used to determine the plugin
  62118. * @returns The loaded scene
  62119. */
  62120. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  62121. if (onProgress === void 0) { onProgress = null; }
  62122. if (pluginExtension === void 0) { pluginExtension = null; }
  62123. return new Promise(function (resolve, reject) {
  62124. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  62125. resolve(scene);
  62126. }, onProgress, function (scene, message, exception) {
  62127. reject(exception || new Error(message));
  62128. }, pluginExtension);
  62129. });
  62130. };
  62131. /**
  62132. * Append a scene
  62133. * @param rootUrl a string that defines the root url for scene and resources
  62134. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62135. * @param scene is the instance of BABYLON.Scene to append to
  62136. * @param onSuccess a callback with the scene when import succeeds
  62137. * @param onProgress a callback with a progress event for each file being loaded
  62138. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62139. * @param pluginExtension the extension used to determine the plugin
  62140. * @returns The loaded plugin
  62141. */
  62142. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62143. if (onSuccess === void 0) { onSuccess = null; }
  62144. if (onProgress === void 0) { onProgress = null; }
  62145. if (onError === void 0) { onError = null; }
  62146. if (pluginExtension === void 0) { pluginExtension = null; }
  62147. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62148. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62149. return null;
  62150. }
  62151. if (SceneLoader.ShowLoadingScreen) {
  62152. scene.getEngine().displayLoadingUI();
  62153. }
  62154. var loadingToken = {};
  62155. scene._addPendingData(loadingToken);
  62156. var disposeHandler = function () {
  62157. scene._removePendingData(loadingToken);
  62158. scene.getEngine().hideLoadingUI();
  62159. };
  62160. var errorHandler = function (message, exception) {
  62161. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  62162. if (onError) {
  62163. onError(scene, errorMessage, exception);
  62164. }
  62165. else {
  62166. BABYLON.Tools.Error(errorMessage);
  62167. // should the exception be thrown?
  62168. }
  62169. disposeHandler();
  62170. };
  62171. var progressHandler = onProgress ? function (event) {
  62172. try {
  62173. onProgress(event);
  62174. }
  62175. catch (e) {
  62176. errorHandler("Error in onProgress callback", e);
  62177. }
  62178. } : undefined;
  62179. var successHandler = function () {
  62180. if (onSuccess) {
  62181. try {
  62182. onSuccess(scene);
  62183. }
  62184. catch (e) {
  62185. errorHandler("Error in onSuccess callback", e);
  62186. }
  62187. }
  62188. scene._removePendingData(loadingToken);
  62189. };
  62190. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62191. if (sceneFilename === "") {
  62192. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62193. }
  62194. if (plugin.load) {
  62195. var syncedPlugin = plugin;
  62196. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  62197. return;
  62198. }
  62199. scene.loadingPluginName = plugin.name;
  62200. successHandler();
  62201. }
  62202. else {
  62203. var asyncedPlugin = plugin;
  62204. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  62205. scene.loadingPluginName = plugin.name;
  62206. successHandler();
  62207. }).catch(function (error) {
  62208. errorHandler(error.message, error);
  62209. });
  62210. }
  62211. if (SceneLoader.ShowLoadingScreen) {
  62212. scene.executeWhenReady(function () {
  62213. scene.getEngine().hideLoadingUI();
  62214. });
  62215. }
  62216. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62217. };
  62218. /**
  62219. * Append a scene
  62220. * @param rootUrl a string that defines the root url for scene and resources
  62221. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62222. * @param scene is the instance of BABYLON.Scene to append to
  62223. * @param onProgress a callback with a progress event for each file being loaded
  62224. * @param pluginExtension the extension used to determine the plugin
  62225. * @returns The given scene
  62226. */
  62227. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62228. if (onProgress === void 0) { onProgress = null; }
  62229. if (pluginExtension === void 0) { pluginExtension = null; }
  62230. return new Promise(function (resolve, reject) {
  62231. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  62232. resolve(scene);
  62233. }, onProgress, function (scene, message, exception) {
  62234. reject(exception || new Error(message));
  62235. }, pluginExtension);
  62236. });
  62237. };
  62238. /**
  62239. * Load a scene into an asset container
  62240. * @param rootUrl a string that defines the root url for scene and resources
  62241. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62242. * @param scene is the instance of BABYLON.Scene to append to
  62243. * @param onSuccess a callback with the scene when import succeeds
  62244. * @param onProgress a callback with a progress event for each file being loaded
  62245. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62246. * @param pluginExtension the extension used to determine the plugin
  62247. * @returns The loaded plugin
  62248. */
  62249. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62250. if (onSuccess === void 0) { onSuccess = null; }
  62251. if (onProgress === void 0) { onProgress = null; }
  62252. if (onError === void 0) { onError = null; }
  62253. if (pluginExtension === void 0) { pluginExtension = null; }
  62254. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62255. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62256. return null;
  62257. }
  62258. var loadingToken = {};
  62259. scene._addPendingData(loadingToken);
  62260. var disposeHandler = function () {
  62261. scene._removePendingData(loadingToken);
  62262. };
  62263. var errorHandler = function (message, exception) {
  62264. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  62265. if (onError) {
  62266. onError(scene, errorMessage, exception);
  62267. }
  62268. else {
  62269. BABYLON.Tools.Error(errorMessage);
  62270. // should the exception be thrown?
  62271. }
  62272. disposeHandler();
  62273. };
  62274. var progressHandler = onProgress ? function (event) {
  62275. try {
  62276. onProgress(event);
  62277. }
  62278. catch (e) {
  62279. errorHandler("Error in onProgress callback", e);
  62280. }
  62281. } : undefined;
  62282. var successHandler = function (assets) {
  62283. if (onSuccess) {
  62284. try {
  62285. onSuccess(assets);
  62286. }
  62287. catch (e) {
  62288. errorHandler("Error in onSuccess callback", e);
  62289. }
  62290. }
  62291. scene._removePendingData(loadingToken);
  62292. };
  62293. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62294. if (plugin.loadAssetContainer) {
  62295. var syncedPlugin = plugin;
  62296. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  62297. if (!assetContainer) {
  62298. return;
  62299. }
  62300. scene.loadingPluginName = plugin.name;
  62301. successHandler(assetContainer);
  62302. }
  62303. else if (plugin.loadAssetContainerAsync) {
  62304. var asyncedPlugin = plugin;
  62305. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  62306. scene.loadingPluginName = plugin.name;
  62307. successHandler(assetContainer);
  62308. }).catch(function (error) {
  62309. errorHandler(error.message, error);
  62310. });
  62311. }
  62312. else {
  62313. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  62314. }
  62315. if (SceneLoader.ShowLoadingScreen) {
  62316. scene.executeWhenReady(function () {
  62317. scene.getEngine().hideLoadingUI();
  62318. });
  62319. }
  62320. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62321. };
  62322. /**
  62323. * Load a scene into an asset container
  62324. * @param rootUrl a string that defines the root url for scene and resources
  62325. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62326. * @param scene is the instance of BABYLON.Scene to append to
  62327. * @param onProgress a callback with a progress event for each file being loaded
  62328. * @param pluginExtension the extension used to determine the plugin
  62329. * @returns The loaded asset container
  62330. */
  62331. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62332. if (onProgress === void 0) { onProgress = null; }
  62333. if (pluginExtension === void 0) { pluginExtension = null; }
  62334. return new Promise(function (resolve, reject) {
  62335. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  62336. resolve(assetContainer);
  62337. }, onProgress, function (scene, message, exception) {
  62338. reject(exception || new Error(message));
  62339. }, pluginExtension);
  62340. });
  62341. };
  62342. // Flags
  62343. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  62344. SceneLoader._ShowLoadingScreen = true;
  62345. SceneLoader._CleanBoneMatrixWeights = false;
  62346. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  62347. // Members
  62348. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  62349. SceneLoader._registeredPlugins = {};
  62350. return SceneLoader;
  62351. }());
  62352. BABYLON.SceneLoader = SceneLoader;
  62353. ;
  62354. })(BABYLON || (BABYLON = {}));
  62355. //# sourceMappingURL=babylon.sceneLoader.js.map
  62356. var BABYLON;
  62357. (function (BABYLON) {
  62358. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  62359. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62360. var parsedMaterial = parsedData.materials[index];
  62361. if (parsedMaterial.id === id) {
  62362. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62363. }
  62364. }
  62365. return null;
  62366. };
  62367. var isDescendantOf = function (mesh, names, hierarchyIds) {
  62368. for (var i in names) {
  62369. if (mesh.name === names[i]) {
  62370. hierarchyIds.push(mesh.id);
  62371. return true;
  62372. }
  62373. }
  62374. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  62375. hierarchyIds.push(mesh.id);
  62376. return true;
  62377. }
  62378. return false;
  62379. };
  62380. var logOperation = function (operation, producer) {
  62381. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  62382. };
  62383. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  62384. if (addToScene === void 0) { addToScene = false; }
  62385. var container = new BABYLON.AssetContainer(scene);
  62386. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62387. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62388. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62389. // and avoid problems with multiple concurrent .babylon loads.
  62390. var log = "importScene has failed JSON parse";
  62391. try {
  62392. var parsedData = JSON.parse(data);
  62393. log = "";
  62394. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  62395. var index;
  62396. var cache;
  62397. // Lights
  62398. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  62399. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  62400. var parsedLight = parsedData.lights[index];
  62401. var light = BABYLON.Light.Parse(parsedLight, scene);
  62402. if (light) {
  62403. container.lights.push(light);
  62404. log += (index === 0 ? "\n\tLights:" : "");
  62405. log += "\n\t\t" + light.toString(fullDetails);
  62406. }
  62407. }
  62408. }
  62409. // Animations
  62410. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  62411. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  62412. var parsedAnimation = parsedData.animations[index];
  62413. var animation = BABYLON.Animation.Parse(parsedAnimation);
  62414. scene.animations.push(animation);
  62415. container.animations.push(animation);
  62416. log += (index === 0 ? "\n\tAnimations:" : "");
  62417. log += "\n\t\t" + animation.toString(fullDetails);
  62418. }
  62419. }
  62420. // Materials
  62421. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  62422. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62423. var parsedMaterial = parsedData.materials[index];
  62424. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62425. container.materials.push(mat);
  62426. log += (index === 0 ? "\n\tMaterials:" : "");
  62427. log += "\n\t\t" + mat.toString(fullDetails);
  62428. }
  62429. }
  62430. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62431. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  62432. var parsedMultiMaterial = parsedData.multiMaterials[index];
  62433. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62434. container.multiMaterials.push(mmat);
  62435. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  62436. log += "\n\t\t" + mmat.toString(fullDetails);
  62437. }
  62438. }
  62439. // Morph targets
  62440. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  62441. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  62442. var managerData = _a[_i];
  62443. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  62444. }
  62445. }
  62446. // Skeletons
  62447. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  62448. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  62449. var parsedSkeleton = parsedData.skeletons[index];
  62450. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  62451. container.skeletons.push(skeleton);
  62452. log += (index === 0 ? "\n\tSkeletons:" : "");
  62453. log += "\n\t\t" + skeleton.toString(fullDetails);
  62454. }
  62455. }
  62456. // Geometries
  62457. var geometries = parsedData.geometries;
  62458. if (geometries !== undefined && geometries !== null) {
  62459. var addedGeometry = new Array();
  62460. // Boxes
  62461. var boxes = geometries.boxes;
  62462. if (boxes !== undefined && boxes !== null) {
  62463. for (index = 0, cache = boxes.length; index < cache; index++) {
  62464. var parsedBox = boxes[index];
  62465. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  62466. }
  62467. }
  62468. // Spheres
  62469. var spheres = geometries.spheres;
  62470. if (spheres !== undefined && spheres !== null) {
  62471. for (index = 0, cache = spheres.length; index < cache; index++) {
  62472. var parsedSphere = spheres[index];
  62473. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  62474. }
  62475. }
  62476. // Cylinders
  62477. var cylinders = geometries.cylinders;
  62478. if (cylinders !== undefined && cylinders !== null) {
  62479. for (index = 0, cache = cylinders.length; index < cache; index++) {
  62480. var parsedCylinder = cylinders[index];
  62481. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  62482. }
  62483. }
  62484. // Toruses
  62485. var toruses = geometries.toruses;
  62486. if (toruses !== undefined && toruses !== null) {
  62487. for (index = 0, cache = toruses.length; index < cache; index++) {
  62488. var parsedTorus = toruses[index];
  62489. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  62490. }
  62491. }
  62492. // Grounds
  62493. var grounds = geometries.grounds;
  62494. if (grounds !== undefined && grounds !== null) {
  62495. for (index = 0, cache = grounds.length; index < cache; index++) {
  62496. var parsedGround = grounds[index];
  62497. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  62498. }
  62499. }
  62500. // Planes
  62501. var planes = geometries.planes;
  62502. if (planes !== undefined && planes !== null) {
  62503. for (index = 0, cache = planes.length; index < cache; index++) {
  62504. var parsedPlane = planes[index];
  62505. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  62506. }
  62507. }
  62508. // TorusKnots
  62509. var torusKnots = geometries.torusKnots;
  62510. if (torusKnots !== undefined && torusKnots !== null) {
  62511. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  62512. var parsedTorusKnot = torusKnots[index];
  62513. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  62514. }
  62515. }
  62516. // VertexData
  62517. var vertexData = geometries.vertexData;
  62518. if (vertexData !== undefined && vertexData !== null) {
  62519. for (index = 0, cache = vertexData.length; index < cache; index++) {
  62520. var parsedVertexData = vertexData[index];
  62521. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  62522. }
  62523. }
  62524. addedGeometry.forEach(function (g) {
  62525. if (g) {
  62526. container.geometries.push(g);
  62527. }
  62528. });
  62529. }
  62530. // Transform nodes
  62531. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  62532. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  62533. var parsedTransformNode = parsedData.transformNodes[index];
  62534. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  62535. container.transformNodes.push(node);
  62536. }
  62537. }
  62538. // Meshes
  62539. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  62540. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  62541. var parsedMesh = parsedData.meshes[index];
  62542. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  62543. container.meshes.push(mesh);
  62544. log += (index === 0 ? "\n\tMeshes:" : "");
  62545. log += "\n\t\t" + mesh.toString(fullDetails);
  62546. }
  62547. }
  62548. // Cameras
  62549. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  62550. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  62551. var parsedCamera = parsedData.cameras[index];
  62552. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  62553. container.cameras.push(camera);
  62554. log += (index === 0 ? "\n\tCameras:" : "");
  62555. log += "\n\t\t" + camera.toString(fullDetails);
  62556. }
  62557. }
  62558. // Browsing all the graph to connect the dots
  62559. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  62560. var camera = scene.cameras[index];
  62561. if (camera._waitingParentId) {
  62562. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  62563. camera._waitingParentId = null;
  62564. }
  62565. }
  62566. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  62567. var light_1 = scene.lights[index];
  62568. if (light_1 && light_1._waitingParentId) {
  62569. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  62570. light_1._waitingParentId = null;
  62571. }
  62572. }
  62573. // Sounds
  62574. // TODO: add sound
  62575. var loadedSounds = [];
  62576. var loadedSound;
  62577. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  62578. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  62579. var parsedSound = parsedData.sounds[index];
  62580. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62581. if (!parsedSound.url)
  62582. parsedSound.url = parsedSound.name;
  62583. if (!loadedSounds[parsedSound.url]) {
  62584. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  62585. loadedSounds[parsedSound.url] = loadedSound;
  62586. container.sounds.push(loadedSound);
  62587. }
  62588. else {
  62589. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  62590. }
  62591. }
  62592. else {
  62593. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  62594. }
  62595. }
  62596. }
  62597. loadedSounds = [];
  62598. // Connect parents & children and parse actions
  62599. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  62600. var transformNode = scene.transformNodes[index];
  62601. if (transformNode._waitingParentId) {
  62602. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  62603. transformNode._waitingParentId = null;
  62604. }
  62605. }
  62606. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62607. var mesh = scene.meshes[index];
  62608. if (mesh._waitingParentId) {
  62609. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  62610. mesh._waitingParentId = null;
  62611. }
  62612. if (mesh._waitingActions) {
  62613. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  62614. mesh._waitingActions = null;
  62615. }
  62616. }
  62617. // freeze world matrix application
  62618. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62619. var currentMesh = scene.meshes[index];
  62620. if (currentMesh._waitingFreezeWorldMatrix) {
  62621. currentMesh.freezeWorldMatrix();
  62622. currentMesh._waitingFreezeWorldMatrix = null;
  62623. }
  62624. else {
  62625. currentMesh.computeWorldMatrix(true);
  62626. }
  62627. }
  62628. // Particles Systems
  62629. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62630. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62631. var parsedParticleSystem = parsedData.particleSystems[index];
  62632. if (parsedParticleSystem.activeParticleCount) {
  62633. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62634. container.particleSystems.push(ps);
  62635. }
  62636. else {
  62637. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62638. container.particleSystems.push(ps);
  62639. }
  62640. }
  62641. }
  62642. // Lens flares
  62643. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  62644. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  62645. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  62646. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  62647. container.lensFlareSystems.push(lf);
  62648. }
  62649. }
  62650. // Shadows
  62651. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  62652. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  62653. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  62654. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  62655. container.shadowGenerators.push(sg);
  62656. }
  62657. }
  62658. // Lights exclusions / inclusions
  62659. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  62660. var light_2 = scene.lights[index];
  62661. // Excluded check
  62662. if (light_2._excludedMeshesIds.length > 0) {
  62663. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  62664. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  62665. if (excludedMesh) {
  62666. light_2.excludedMeshes.push(excludedMesh);
  62667. }
  62668. }
  62669. light_2._excludedMeshesIds = [];
  62670. }
  62671. // Included check
  62672. if (light_2._includedOnlyMeshesIds.length > 0) {
  62673. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  62674. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  62675. if (includedOnlyMesh) {
  62676. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  62677. }
  62678. }
  62679. light_2._includedOnlyMeshesIds = [];
  62680. }
  62681. }
  62682. // Actions (scene)
  62683. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  62684. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  62685. }
  62686. if (!addToScene) {
  62687. container.removeAllFromScene();
  62688. }
  62689. }
  62690. catch (err) {
  62691. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  62692. if (onError) {
  62693. onError(msg, err);
  62694. }
  62695. else {
  62696. BABYLON.Tools.Log(msg);
  62697. throw err;
  62698. }
  62699. }
  62700. finally {
  62701. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62702. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62703. }
  62704. }
  62705. return container;
  62706. };
  62707. BABYLON.SceneLoader.RegisterPlugin({
  62708. name: "babylon.js",
  62709. extensions: ".babylon",
  62710. canDirectLoad: function (data) {
  62711. if (data.indexOf("babylon") !== -1) {
  62712. return true;
  62713. }
  62714. return false;
  62715. },
  62716. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  62717. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62718. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62719. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62720. // and avoid problems with multiple concurrent .babylon loads.
  62721. var log = "importMesh has failed JSON parse";
  62722. try {
  62723. var parsedData = JSON.parse(data);
  62724. log = "";
  62725. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  62726. if (!meshesNames) {
  62727. meshesNames = null;
  62728. }
  62729. else if (!Array.isArray(meshesNames)) {
  62730. meshesNames = [meshesNames];
  62731. }
  62732. var hierarchyIds = new Array();
  62733. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  62734. var loadedSkeletonsIds = [];
  62735. var loadedMaterialsIds = [];
  62736. var index;
  62737. var cache;
  62738. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  62739. var parsedMesh = parsedData.meshes[index];
  62740. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  62741. if (meshesNames !== null) {
  62742. // Remove found mesh name from list.
  62743. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  62744. }
  62745. //Geometry?
  62746. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  62747. //does the file contain geometries?
  62748. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  62749. //find the correct geometry and add it to the scene
  62750. var found = false;
  62751. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  62752. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  62753. return;
  62754. }
  62755. else {
  62756. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  62757. if (parsedGeometryData.id === parsedMesh.geometryId) {
  62758. switch (geometryType) {
  62759. case "boxes":
  62760. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  62761. break;
  62762. case "spheres":
  62763. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  62764. break;
  62765. case "cylinders":
  62766. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  62767. break;
  62768. case "toruses":
  62769. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  62770. break;
  62771. case "grounds":
  62772. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  62773. break;
  62774. case "planes":
  62775. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  62776. break;
  62777. case "torusKnots":
  62778. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  62779. break;
  62780. case "vertexData":
  62781. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  62782. break;
  62783. }
  62784. found = true;
  62785. }
  62786. });
  62787. }
  62788. });
  62789. if (found === false) {
  62790. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  62791. }
  62792. }
  62793. }
  62794. // Material ?
  62795. if (parsedMesh.materialId) {
  62796. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  62797. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62798. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  62799. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  62800. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  62801. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  62802. var subMatId = parsedMultiMaterial.materials[matIndex];
  62803. loadedMaterialsIds.push(subMatId);
  62804. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  62805. if (mat) {
  62806. log += "\n\tMaterial " + mat.toString(fullDetails);
  62807. }
  62808. }
  62809. loadedMaterialsIds.push(parsedMultiMaterial.id);
  62810. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62811. if (mmat) {
  62812. materialFound = true;
  62813. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  62814. }
  62815. break;
  62816. }
  62817. }
  62818. }
  62819. if (materialFound === false) {
  62820. loadedMaterialsIds.push(parsedMesh.materialId);
  62821. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  62822. if (!mat) {
  62823. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  62824. }
  62825. else {
  62826. log += "\n\tMaterial " + mat.toString(fullDetails);
  62827. }
  62828. }
  62829. }
  62830. // Skeleton ?
  62831. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  62832. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  62833. if (skeletonAlreadyLoaded === false) {
  62834. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  62835. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  62836. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  62837. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  62838. skeletons.push(skeleton);
  62839. loadedSkeletonsIds.push(parsedSkeleton.id);
  62840. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  62841. }
  62842. }
  62843. }
  62844. }
  62845. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  62846. meshes.push(mesh);
  62847. log += "\n\tMesh " + mesh.toString(fullDetails);
  62848. }
  62849. }
  62850. // Connecting parents
  62851. var currentMesh;
  62852. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62853. currentMesh = scene.meshes[index];
  62854. if (currentMesh._waitingParentId) {
  62855. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  62856. currentMesh._waitingParentId = null;
  62857. }
  62858. }
  62859. // freeze and compute world matrix application
  62860. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62861. currentMesh = scene.meshes[index];
  62862. if (currentMesh._waitingFreezeWorldMatrix) {
  62863. currentMesh.freezeWorldMatrix();
  62864. currentMesh._waitingFreezeWorldMatrix = null;
  62865. }
  62866. else {
  62867. currentMesh.computeWorldMatrix(true);
  62868. }
  62869. }
  62870. }
  62871. // Particles
  62872. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62873. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62874. var parsedParticleSystem = parsedData.particleSystems[index];
  62875. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  62876. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  62877. }
  62878. }
  62879. }
  62880. return true;
  62881. }
  62882. catch (err) {
  62883. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  62884. if (onError) {
  62885. onError(msg, err);
  62886. }
  62887. else {
  62888. BABYLON.Tools.Log(msg);
  62889. throw err;
  62890. }
  62891. }
  62892. finally {
  62893. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62894. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62895. }
  62896. }
  62897. return false;
  62898. },
  62899. load: function (scene, data, rootUrl, onError) {
  62900. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62901. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62902. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62903. // and avoid problems with multiple concurrent .babylon loads.
  62904. var log = "importScene has failed JSON parse";
  62905. try {
  62906. var parsedData = JSON.parse(data);
  62907. log = "";
  62908. // Scene
  62909. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  62910. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  62911. }
  62912. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  62913. scene.autoClear = parsedData.autoClear;
  62914. }
  62915. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  62916. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  62917. }
  62918. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  62919. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  62920. }
  62921. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  62922. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  62923. }
  62924. // Fog
  62925. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  62926. scene.fogMode = parsedData.fogMode;
  62927. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  62928. scene.fogStart = parsedData.fogStart;
  62929. scene.fogEnd = parsedData.fogEnd;
  62930. scene.fogDensity = parsedData.fogDensity;
  62931. log += "\tFog mode for scene: ";
  62932. switch (scene.fogMode) {
  62933. // getters not compiling, so using hardcoded
  62934. case 1:
  62935. log += "exp\n";
  62936. break;
  62937. case 2:
  62938. log += "exp2\n";
  62939. break;
  62940. case 3:
  62941. log += "linear\n";
  62942. break;
  62943. }
  62944. }
  62945. //Physics
  62946. if (parsedData.physicsEnabled) {
  62947. var physicsPlugin;
  62948. if (parsedData.physicsEngine === "cannon") {
  62949. physicsPlugin = new BABYLON.CannonJSPlugin();
  62950. }
  62951. else if (parsedData.physicsEngine === "oimo") {
  62952. physicsPlugin = new BABYLON.OimoJSPlugin();
  62953. }
  62954. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  62955. //else - default engine, which is currently oimo
  62956. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  62957. scene.enablePhysics(physicsGravity, physicsPlugin);
  62958. }
  62959. // Metadata
  62960. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  62961. scene.metadata = parsedData.metadata;
  62962. }
  62963. //collisions, if defined. otherwise, default is true
  62964. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  62965. scene.collisionsEnabled = parsedData.collisionsEnabled;
  62966. }
  62967. scene.workerCollisions = !!parsedData.workerCollisions;
  62968. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  62969. if (!container) {
  62970. return false;
  62971. }
  62972. if (parsedData.autoAnimate) {
  62973. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  62974. }
  62975. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  62976. scene.setActiveCameraByID(parsedData.activeCameraID);
  62977. }
  62978. // Environment texture
  62979. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  62980. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  62981. if (parsedData.createDefaultSkybox === true) {
  62982. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  62983. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  62984. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  62985. }
  62986. }
  62987. // Finish
  62988. return true;
  62989. }
  62990. catch (err) {
  62991. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  62992. if (onError) {
  62993. onError(msg, err);
  62994. }
  62995. else {
  62996. BABYLON.Tools.Log(msg);
  62997. throw err;
  62998. }
  62999. }
  63000. finally {
  63001. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63002. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63003. }
  63004. }
  63005. return false;
  63006. },
  63007. loadAssetContainer: function (scene, data, rootUrl, onError) {
  63008. var container = loadAssetContainer(scene, data, rootUrl, onError);
  63009. return container;
  63010. }
  63011. });
  63012. })(BABYLON || (BABYLON = {}));
  63013. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  63014. var BABYLON;
  63015. (function (BABYLON) {
  63016. var FilesInput = /** @class */ (function () {
  63017. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  63018. this.onProcessFileCallback = function () { return true; };
  63019. this._engine = engine;
  63020. this._currentScene = scene;
  63021. this._sceneLoadedCallback = sceneLoadedCallback;
  63022. this._progressCallback = progressCallback;
  63023. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  63024. this._textureLoadingCallback = textureLoadingCallback;
  63025. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  63026. this._onReloadCallback = onReloadCallback;
  63027. this._errorCallback = errorCallback;
  63028. }
  63029. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  63030. var _this = this;
  63031. if (elementToMonitor) {
  63032. this._elementToMonitor = elementToMonitor;
  63033. this._dragEnterHandler = function (e) { _this.drag(e); };
  63034. this._dragOverHandler = function (e) { _this.drag(e); };
  63035. this._dropHandler = function (e) { _this.drop(e); };
  63036. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  63037. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  63038. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  63039. }
  63040. };
  63041. FilesInput.prototype.dispose = function () {
  63042. if (!this._elementToMonitor) {
  63043. return;
  63044. }
  63045. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  63046. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  63047. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  63048. };
  63049. FilesInput.prototype.renderFunction = function () {
  63050. if (this._additionalRenderLoopLogicCallback) {
  63051. this._additionalRenderLoopLogicCallback();
  63052. }
  63053. if (this._currentScene) {
  63054. if (this._textureLoadingCallback) {
  63055. var remaining = this._currentScene.getWaitingItemsCount();
  63056. if (remaining > 0) {
  63057. this._textureLoadingCallback(remaining);
  63058. }
  63059. }
  63060. this._currentScene.render();
  63061. }
  63062. };
  63063. FilesInput.prototype.drag = function (e) {
  63064. e.stopPropagation();
  63065. e.preventDefault();
  63066. };
  63067. FilesInput.prototype.drop = function (eventDrop) {
  63068. eventDrop.stopPropagation();
  63069. eventDrop.preventDefault();
  63070. this.loadFiles(eventDrop);
  63071. };
  63072. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  63073. var _this = this;
  63074. var reader = folder.createReader();
  63075. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  63076. reader.readEntries(function (entries) {
  63077. remaining.count += entries.length;
  63078. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  63079. var entry = entries_1[_i];
  63080. if (entry.isFile) {
  63081. entry.file(function (file) {
  63082. file.correctName = relativePath + file.name;
  63083. files.push(file);
  63084. if (--remaining.count === 0) {
  63085. callback();
  63086. }
  63087. });
  63088. }
  63089. else if (entry.isDirectory) {
  63090. _this._traverseFolder(entry, files, remaining, callback);
  63091. }
  63092. }
  63093. if (--remaining.count) {
  63094. callback();
  63095. }
  63096. });
  63097. };
  63098. FilesInput.prototype._processFiles = function (files) {
  63099. for (var i = 0; i < files.length; i++) {
  63100. var name = files[i].correctName.toLowerCase();
  63101. var extension = name.split('.').pop();
  63102. if (!this.onProcessFileCallback(files[i], name, extension)) {
  63103. continue;
  63104. }
  63105. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  63106. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  63107. this._sceneFileToLoad = files[i];
  63108. }
  63109. else {
  63110. FilesInput.FilesToLoad[name] = files[i];
  63111. }
  63112. }
  63113. };
  63114. FilesInput.prototype.loadFiles = function (event) {
  63115. var _this = this;
  63116. if (this._startingProcessingFilesCallback)
  63117. this._startingProcessingFilesCallback();
  63118. // Handling data transfer via drag'n'drop
  63119. if (event && event.dataTransfer && event.dataTransfer.files) {
  63120. this._filesToLoad = event.dataTransfer.files;
  63121. }
  63122. // Handling files from input files
  63123. if (event && event.target && event.target.files) {
  63124. this._filesToLoad = event.target.files;
  63125. }
  63126. if (this._filesToLoad && this._filesToLoad.length > 0) {
  63127. var files_1 = new Array();
  63128. var folders = [];
  63129. var items = event.dataTransfer ? event.dataTransfer.items : null;
  63130. for (var i = 0; i < this._filesToLoad.length; i++) {
  63131. var fileToLoad = this._filesToLoad[i];
  63132. var name_1 = fileToLoad.name.toLowerCase();
  63133. var entry = void 0;
  63134. fileToLoad.correctName = name_1;
  63135. if (items) {
  63136. var item = items[i];
  63137. if (item.getAsEntry) {
  63138. entry = item.getAsEntry();
  63139. }
  63140. else if (item.webkitGetAsEntry) {
  63141. entry = item.webkitGetAsEntry();
  63142. }
  63143. }
  63144. if (!entry) {
  63145. files_1.push(fileToLoad);
  63146. }
  63147. else {
  63148. if (entry.isDirectory) {
  63149. folders.push(entry);
  63150. }
  63151. else {
  63152. files_1.push(fileToLoad);
  63153. }
  63154. }
  63155. }
  63156. if (folders.length === 0) {
  63157. this._processFiles(files_1);
  63158. this._processReload();
  63159. }
  63160. else {
  63161. var remaining = { count: folders.length };
  63162. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  63163. var folder = folders_1[_i];
  63164. this._traverseFolder(folder, files_1, remaining, function () {
  63165. _this._processFiles(files_1);
  63166. if (remaining.count === 0) {
  63167. _this._processReload();
  63168. }
  63169. });
  63170. }
  63171. }
  63172. }
  63173. };
  63174. FilesInput.prototype._processReload = function () {
  63175. if (this._onReloadCallback) {
  63176. this._onReloadCallback(this._sceneFileToLoad);
  63177. }
  63178. else {
  63179. this.reload();
  63180. }
  63181. };
  63182. FilesInput.prototype.reload = function () {
  63183. var _this = this;
  63184. // If a scene file has been provided
  63185. if (this._sceneFileToLoad) {
  63186. if (this._currentScene) {
  63187. if (BABYLON.Tools.errorsCount > 0) {
  63188. BABYLON.Tools.ClearLogCache();
  63189. }
  63190. this._engine.stopRenderLoop();
  63191. this._currentScene.dispose();
  63192. }
  63193. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  63194. if (_this._progressCallback) {
  63195. _this._progressCallback(progress);
  63196. }
  63197. }).then(function (scene) {
  63198. _this._currentScene = scene;
  63199. if (_this._sceneLoadedCallback) {
  63200. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  63201. }
  63202. // Wait for textures and shaders to be ready
  63203. _this._currentScene.executeWhenReady(function () {
  63204. _this._engine.runRenderLoop(function () {
  63205. _this.renderFunction();
  63206. });
  63207. });
  63208. }).catch(function (error) {
  63209. if (_this._errorCallback) {
  63210. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  63211. }
  63212. });
  63213. }
  63214. else {
  63215. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  63216. }
  63217. };
  63218. FilesInput.FilesToLoad = {};
  63219. return FilesInput;
  63220. }());
  63221. BABYLON.FilesInput = FilesInput;
  63222. })(BABYLON || (BABYLON = {}));
  63223. //# sourceMappingURL=babylon.filesInput.js.map
  63224. var BABYLON;
  63225. (function (BABYLON) {
  63226. /**
  63227. * This class implement a typical dictionary using a string as key and the generic type T as value.
  63228. * The underlying implementation relies on an associative array to ensure the best performances.
  63229. * The value can be anything including 'null' but except 'undefined'
  63230. */
  63231. var StringDictionary = /** @class */ (function () {
  63232. function StringDictionary() {
  63233. this._count = 0;
  63234. this._data = {};
  63235. }
  63236. /**
  63237. * This will clear this dictionary and copy the content from the 'source' one.
  63238. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  63239. * @param source the dictionary to take the content from and copy to this dictionary
  63240. */
  63241. StringDictionary.prototype.copyFrom = function (source) {
  63242. var _this = this;
  63243. this.clear();
  63244. source.forEach(function (t, v) { return _this.add(t, v); });
  63245. };
  63246. /**
  63247. * Get a value based from its key
  63248. * @param key the given key to get the matching value from
  63249. * @return the value if found, otherwise undefined is returned
  63250. */
  63251. StringDictionary.prototype.get = function (key) {
  63252. var val = this._data[key];
  63253. if (val !== undefined) {
  63254. return val;
  63255. }
  63256. return undefined;
  63257. };
  63258. /**
  63259. * Get a value from its key or add it if it doesn't exist.
  63260. * This method will ensure you that a given key/data will be present in the dictionary.
  63261. * @param key the given key to get the matching value from
  63262. * @param factory the factory that will create the value if the key is not present in the dictionary.
  63263. * The factory will only be invoked if there's no data for the given key.
  63264. * @return the value corresponding to the key.
  63265. */
  63266. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  63267. var val = this.get(key);
  63268. if (val !== undefined) {
  63269. return val;
  63270. }
  63271. val = factory(key);
  63272. if (val) {
  63273. this.add(key, val);
  63274. }
  63275. return val;
  63276. };
  63277. /**
  63278. * Get a value from its key if present in the dictionary otherwise add it
  63279. * @param key the key to get the value from
  63280. * @param val if there's no such key/value pair in the dictionary add it with this value
  63281. * @return the value corresponding to the key
  63282. */
  63283. StringDictionary.prototype.getOrAdd = function (key, val) {
  63284. var curVal = this.get(key);
  63285. if (curVal !== undefined) {
  63286. return curVal;
  63287. }
  63288. this.add(key, val);
  63289. return val;
  63290. };
  63291. /**
  63292. * Check if there's a given key in the dictionary
  63293. * @param key the key to check for
  63294. * @return true if the key is present, false otherwise
  63295. */
  63296. StringDictionary.prototype.contains = function (key) {
  63297. return this._data[key] !== undefined;
  63298. };
  63299. /**
  63300. * Add a new key and its corresponding value
  63301. * @param key the key to add
  63302. * @param value the value corresponding to the key
  63303. * @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
  63304. */
  63305. StringDictionary.prototype.add = function (key, value) {
  63306. if (this._data[key] !== undefined) {
  63307. return false;
  63308. }
  63309. this._data[key] = value;
  63310. ++this._count;
  63311. return true;
  63312. };
  63313. StringDictionary.prototype.set = function (key, value) {
  63314. if (this._data[key] === undefined) {
  63315. return false;
  63316. }
  63317. this._data[key] = value;
  63318. return true;
  63319. };
  63320. /**
  63321. * Get the element of the given key and remove it from the dictionary
  63322. * @param key
  63323. */
  63324. StringDictionary.prototype.getAndRemove = function (key) {
  63325. var val = this.get(key);
  63326. if (val !== undefined) {
  63327. delete this._data[key];
  63328. --this._count;
  63329. return val;
  63330. }
  63331. return null;
  63332. };
  63333. /**
  63334. * Remove a key/value from the dictionary.
  63335. * @param key the key to remove
  63336. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  63337. */
  63338. StringDictionary.prototype.remove = function (key) {
  63339. if (this.contains(key)) {
  63340. delete this._data[key];
  63341. --this._count;
  63342. return true;
  63343. }
  63344. return false;
  63345. };
  63346. /**
  63347. * Clear the whole content of the dictionary
  63348. */
  63349. StringDictionary.prototype.clear = function () {
  63350. this._data = {};
  63351. this._count = 0;
  63352. };
  63353. Object.defineProperty(StringDictionary.prototype, "count", {
  63354. get: function () {
  63355. return this._count;
  63356. },
  63357. enumerable: true,
  63358. configurable: true
  63359. });
  63360. /**
  63361. * Execute a callback on each key/val of the dictionary.
  63362. * Note that you can remove any element in this dictionary in the callback implementation
  63363. * @param callback the callback to execute on a given key/value pair
  63364. */
  63365. StringDictionary.prototype.forEach = function (callback) {
  63366. for (var cur in this._data) {
  63367. var val = this._data[cur];
  63368. callback(cur, val);
  63369. }
  63370. };
  63371. /**
  63372. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  63373. * If the callback returns null or undefined the method will iterate to the next key/value pair
  63374. * Note that you can remove any element in this dictionary in the callback implementation
  63375. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  63376. */
  63377. StringDictionary.prototype.first = function (callback) {
  63378. for (var cur in this._data) {
  63379. var val = this._data[cur];
  63380. var res = callback(cur, val);
  63381. if (res) {
  63382. return res;
  63383. }
  63384. }
  63385. return null;
  63386. };
  63387. return StringDictionary;
  63388. }());
  63389. BABYLON.StringDictionary = StringDictionary;
  63390. })(BABYLON || (BABYLON = {}));
  63391. //# sourceMappingURL=babylon.stringDictionary.js.map
  63392. var BABYLON;
  63393. (function (BABYLON) {
  63394. var Tags = /** @class */ (function () {
  63395. function Tags() {
  63396. }
  63397. Tags.EnableFor = function (obj) {
  63398. obj._tags = obj._tags || {};
  63399. obj.hasTags = function () {
  63400. return Tags.HasTags(obj);
  63401. };
  63402. obj.addTags = function (tagsString) {
  63403. return Tags.AddTagsTo(obj, tagsString);
  63404. };
  63405. obj.removeTags = function (tagsString) {
  63406. return Tags.RemoveTagsFrom(obj, tagsString);
  63407. };
  63408. obj.matchesTagsQuery = function (tagsQuery) {
  63409. return Tags.MatchesQuery(obj, tagsQuery);
  63410. };
  63411. };
  63412. Tags.DisableFor = function (obj) {
  63413. delete obj._tags;
  63414. delete obj.hasTags;
  63415. delete obj.addTags;
  63416. delete obj.removeTags;
  63417. delete obj.matchesTagsQuery;
  63418. };
  63419. Tags.HasTags = function (obj) {
  63420. if (!obj._tags) {
  63421. return false;
  63422. }
  63423. return !BABYLON.Tools.IsEmpty(obj._tags);
  63424. };
  63425. Tags.GetTags = function (obj, asString) {
  63426. if (asString === void 0) { asString = true; }
  63427. if (!obj._tags) {
  63428. return null;
  63429. }
  63430. if (asString) {
  63431. var tagsArray = [];
  63432. for (var tag in obj._tags) {
  63433. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  63434. tagsArray.push(tag);
  63435. }
  63436. }
  63437. return tagsArray.join(" ");
  63438. }
  63439. else {
  63440. return obj._tags;
  63441. }
  63442. };
  63443. // the tags 'true' and 'false' are reserved and cannot be used as tags
  63444. // a tag cannot start with '||', '&&', and '!'
  63445. // it cannot contain whitespaces
  63446. Tags.AddTagsTo = function (obj, tagsString) {
  63447. if (!tagsString) {
  63448. return;
  63449. }
  63450. if (typeof tagsString !== "string") {
  63451. return;
  63452. }
  63453. var tags = tagsString.split(" ");
  63454. tags.forEach(function (tag, index, array) {
  63455. Tags._AddTagTo(obj, tag);
  63456. });
  63457. };
  63458. Tags._AddTagTo = function (obj, tag) {
  63459. tag = tag.trim();
  63460. if (tag === "" || tag === "true" || tag === "false") {
  63461. return;
  63462. }
  63463. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  63464. return;
  63465. }
  63466. Tags.EnableFor(obj);
  63467. obj._tags[tag] = true;
  63468. };
  63469. Tags.RemoveTagsFrom = function (obj, tagsString) {
  63470. if (!Tags.HasTags(obj)) {
  63471. return;
  63472. }
  63473. var tags = tagsString.split(" ");
  63474. for (var t in tags) {
  63475. Tags._RemoveTagFrom(obj, tags[t]);
  63476. }
  63477. };
  63478. Tags._RemoveTagFrom = function (obj, tag) {
  63479. delete obj._tags[tag];
  63480. };
  63481. Tags.MatchesQuery = function (obj, tagsQuery) {
  63482. if (tagsQuery === undefined) {
  63483. return true;
  63484. }
  63485. if (tagsQuery === "") {
  63486. return Tags.HasTags(obj);
  63487. }
  63488. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  63489. };
  63490. return Tags;
  63491. }());
  63492. BABYLON.Tags = Tags;
  63493. })(BABYLON || (BABYLON = {}));
  63494. //# sourceMappingURL=babylon.tags.js.map
  63495. var BABYLON;
  63496. (function (BABYLON) {
  63497. var AndOrNotEvaluator = /** @class */ (function () {
  63498. function AndOrNotEvaluator() {
  63499. }
  63500. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  63501. if (!query.match(/\([^\(\)]*\)/g)) {
  63502. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  63503. }
  63504. else {
  63505. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  63506. // remove parenthesis
  63507. r = r.slice(1, r.length - 1);
  63508. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  63509. });
  63510. }
  63511. if (query === "true") {
  63512. return true;
  63513. }
  63514. if (query === "false") {
  63515. return false;
  63516. }
  63517. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  63518. };
  63519. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  63520. evaluateCallback = evaluateCallback || (function (r) {
  63521. return r === "true" ? true : false;
  63522. });
  63523. var result;
  63524. var or = parenthesisContent.split("||");
  63525. for (var i in or) {
  63526. if (or.hasOwnProperty(i)) {
  63527. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  63528. var and = ori.split("&&");
  63529. if (and.length > 1) {
  63530. for (var j = 0; j < and.length; ++j) {
  63531. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  63532. if (andj !== "true" && andj !== "false") {
  63533. if (andj[0] === "!") {
  63534. result = !evaluateCallback(andj.substring(1));
  63535. }
  63536. else {
  63537. result = evaluateCallback(andj);
  63538. }
  63539. }
  63540. else {
  63541. result = andj === "true" ? true : false;
  63542. }
  63543. if (!result) {
  63544. ori = "false";
  63545. break;
  63546. }
  63547. }
  63548. }
  63549. if (result || ori === "true") {
  63550. result = true;
  63551. break;
  63552. }
  63553. // result equals false (or undefined)
  63554. if (ori !== "true" && ori !== "false") {
  63555. if (ori[0] === "!") {
  63556. result = !evaluateCallback(ori.substring(1));
  63557. }
  63558. else {
  63559. result = evaluateCallback(ori);
  63560. }
  63561. }
  63562. else {
  63563. result = ori === "true" ? true : false;
  63564. }
  63565. }
  63566. }
  63567. // the whole parenthesis scope is replaced by 'true' or 'false'
  63568. return result ? "true" : "false";
  63569. };
  63570. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  63571. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  63572. // remove whitespaces
  63573. r = r.replace(/[\s]/g, function () { return ""; });
  63574. return r.length % 2 ? "!" : "";
  63575. });
  63576. booleanString = booleanString.trim();
  63577. if (booleanString === "!true") {
  63578. booleanString = "false";
  63579. }
  63580. else if (booleanString === "!false") {
  63581. booleanString = "true";
  63582. }
  63583. return booleanString;
  63584. };
  63585. return AndOrNotEvaluator;
  63586. }());
  63587. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  63588. })(BABYLON || (BABYLON = {}));
  63589. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  63590. var BABYLON;
  63591. (function (BABYLON) {
  63592. var Database = /** @class */ (function () {
  63593. function Database(urlToScene, callbackManifestChecked) {
  63594. // Handling various flavors of prefixed version of IndexedDB
  63595. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  63596. this.callbackManifestChecked = callbackManifestChecked;
  63597. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  63598. this.db = null;
  63599. this._enableSceneOffline = false;
  63600. this._enableTexturesOffline = false;
  63601. this.manifestVersionFound = 0;
  63602. this.mustUpdateRessources = false;
  63603. this.hasReachedQuota = false;
  63604. if (!Database.IDBStorageEnabled) {
  63605. this.callbackManifestChecked(true);
  63606. }
  63607. else {
  63608. this.checkManifestFile();
  63609. }
  63610. }
  63611. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  63612. get: function () {
  63613. return this._enableSceneOffline;
  63614. },
  63615. enumerable: true,
  63616. configurable: true
  63617. });
  63618. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  63619. get: function () {
  63620. return this._enableTexturesOffline;
  63621. },
  63622. enumerable: true,
  63623. configurable: true
  63624. });
  63625. Database.prototype.checkManifestFile = function () {
  63626. var _this = this;
  63627. var noManifestFile = function () {
  63628. _this._enableSceneOffline = false;
  63629. _this._enableTexturesOffline = false;
  63630. _this.callbackManifestChecked(false);
  63631. };
  63632. var timeStampUsed = false;
  63633. var manifestURL = this.currentSceneUrl + ".manifest";
  63634. var xhr = new XMLHttpRequest();
  63635. if (navigator.onLine) {
  63636. // Adding a timestamp to by-pass browsers' cache
  63637. timeStampUsed = true;
  63638. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  63639. }
  63640. xhr.open("GET", manifestURL, true);
  63641. xhr.addEventListener("load", function () {
  63642. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63643. try {
  63644. var manifestFile = JSON.parse(xhr.response);
  63645. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  63646. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  63647. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  63648. _this.manifestVersionFound = manifestFile.version;
  63649. }
  63650. if (_this.callbackManifestChecked) {
  63651. _this.callbackManifestChecked(true);
  63652. }
  63653. }
  63654. catch (ex) {
  63655. noManifestFile();
  63656. }
  63657. }
  63658. else {
  63659. noManifestFile();
  63660. }
  63661. }, false);
  63662. xhr.addEventListener("error", function (event) {
  63663. if (timeStampUsed) {
  63664. timeStampUsed = false;
  63665. // Let's retry without the timeStamp
  63666. // It could fail when coupled with HTML5 Offline API
  63667. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  63668. xhr.open("GET", retryManifestURL, true);
  63669. xhr.send();
  63670. }
  63671. else {
  63672. noManifestFile();
  63673. }
  63674. }, false);
  63675. try {
  63676. xhr.send();
  63677. }
  63678. catch (ex) {
  63679. BABYLON.Tools.Error("Error on XHR send request.");
  63680. this.callbackManifestChecked(false);
  63681. }
  63682. };
  63683. Database.prototype.openAsync = function (successCallback, errorCallback) {
  63684. var _this = this;
  63685. var handleError = function () {
  63686. _this.isSupported = false;
  63687. if (errorCallback)
  63688. errorCallback();
  63689. };
  63690. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  63691. // Your browser doesn't support IndexedDB
  63692. this.isSupported = false;
  63693. if (errorCallback)
  63694. errorCallback();
  63695. }
  63696. else {
  63697. // If the DB hasn't been opened or created yet
  63698. if (!this.db) {
  63699. this.hasReachedQuota = false;
  63700. this.isSupported = true;
  63701. var request = this.idbFactory.open("babylonjs", 1);
  63702. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  63703. request.onerror = function (event) {
  63704. handleError();
  63705. };
  63706. // executes when a version change transaction cannot complete due to other active transactions
  63707. request.onblocked = function (event) {
  63708. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  63709. handleError();
  63710. };
  63711. // DB has been opened successfully
  63712. request.onsuccess = function (event) {
  63713. _this.db = request.result;
  63714. successCallback();
  63715. };
  63716. // Initialization of the DB. Creating Scenes & Textures stores
  63717. request.onupgradeneeded = function (event) {
  63718. _this.db = (event.target).result;
  63719. if (_this.db) {
  63720. try {
  63721. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  63722. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  63723. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  63724. }
  63725. catch (ex) {
  63726. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  63727. handleError();
  63728. }
  63729. }
  63730. };
  63731. }
  63732. else {
  63733. if (successCallback)
  63734. successCallback();
  63735. }
  63736. }
  63737. };
  63738. Database.prototype.loadImageFromDB = function (url, image) {
  63739. var _this = this;
  63740. var completeURL = Database.ReturnFullUrlLocation(url);
  63741. var saveAndLoadImage = function () {
  63742. if (!_this.hasReachedQuota && _this.db !== null) {
  63743. // the texture is not yet in the DB, let's try to save it
  63744. _this._saveImageIntoDBAsync(completeURL, image);
  63745. }
  63746. else {
  63747. image.src = url;
  63748. }
  63749. };
  63750. if (!this.mustUpdateRessources) {
  63751. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  63752. }
  63753. else {
  63754. saveAndLoadImage();
  63755. }
  63756. };
  63757. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  63758. if (this.isSupported && this.db !== null) {
  63759. var texture;
  63760. var transaction = this.db.transaction(["textures"]);
  63761. transaction.onabort = function (event) {
  63762. image.src = url;
  63763. };
  63764. transaction.oncomplete = function (event) {
  63765. var blobTextureURL;
  63766. if (texture) {
  63767. var URL = window.URL || window.webkitURL;
  63768. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  63769. image.onerror = function () {
  63770. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  63771. image.src = url;
  63772. };
  63773. image.src = blobTextureURL;
  63774. }
  63775. else {
  63776. notInDBCallback();
  63777. }
  63778. };
  63779. var getRequest = transaction.objectStore("textures").get(url);
  63780. getRequest.onsuccess = function (event) {
  63781. texture = (event.target).result;
  63782. };
  63783. getRequest.onerror = function (event) {
  63784. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  63785. image.src = url;
  63786. };
  63787. }
  63788. else {
  63789. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63790. image.src = url;
  63791. }
  63792. };
  63793. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  63794. var _this = this;
  63795. if (this.isSupported) {
  63796. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  63797. var generateBlobUrl = function () {
  63798. var blobTextureURL;
  63799. if (blob) {
  63800. var URL = window.URL || window.webkitURL;
  63801. try {
  63802. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  63803. }
  63804. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  63805. catch (ex) {
  63806. blobTextureURL = URL.createObjectURL(blob);
  63807. }
  63808. }
  63809. if (blobTextureURL) {
  63810. image.src = blobTextureURL;
  63811. }
  63812. };
  63813. if (Database.IsUASupportingBlobStorage) {
  63814. var xhr = new XMLHttpRequest(), blob;
  63815. xhr.open("GET", url, true);
  63816. xhr.responseType = "blob";
  63817. xhr.addEventListener("load", function () {
  63818. if (xhr.status === 200 && _this.db) {
  63819. // Blob as response (XHR2)
  63820. blob = xhr.response;
  63821. var transaction = _this.db.transaction(["textures"], "readwrite");
  63822. // the transaction could abort because of a QuotaExceededError error
  63823. transaction.onabort = function (event) {
  63824. try {
  63825. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  63826. var srcElement = (event.srcElement || event.target);
  63827. var error = srcElement.error;
  63828. if (error && error.name === "QuotaExceededError") {
  63829. _this.hasReachedQuota = true;
  63830. }
  63831. }
  63832. catch (ex) { }
  63833. generateBlobUrl();
  63834. };
  63835. transaction.oncomplete = function (event) {
  63836. generateBlobUrl();
  63837. };
  63838. var newTexture = { textureUrl: url, data: blob };
  63839. try {
  63840. // Put the blob into the dabase
  63841. var addRequest = transaction.objectStore("textures").put(newTexture);
  63842. addRequest.onsuccess = function (event) {
  63843. };
  63844. addRequest.onerror = function (event) {
  63845. generateBlobUrl();
  63846. };
  63847. }
  63848. catch (ex) {
  63849. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  63850. if (ex.code === 25) {
  63851. Database.IsUASupportingBlobStorage = false;
  63852. }
  63853. image.src = url;
  63854. }
  63855. }
  63856. else {
  63857. image.src = url;
  63858. }
  63859. }, false);
  63860. xhr.addEventListener("error", function (event) {
  63861. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  63862. image.src = url;
  63863. }, false);
  63864. xhr.send();
  63865. }
  63866. else {
  63867. image.src = url;
  63868. }
  63869. }
  63870. else {
  63871. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63872. image.src = url;
  63873. }
  63874. };
  63875. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  63876. var _this = this;
  63877. var updateVersion = function () {
  63878. // the version is not yet in the DB or we need to update it
  63879. _this._saveVersionIntoDBAsync(url, versionLoaded);
  63880. };
  63881. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  63882. };
  63883. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  63884. var _this = this;
  63885. if (this.isSupported && this.db) {
  63886. var version;
  63887. try {
  63888. var transaction = this.db.transaction(["versions"]);
  63889. transaction.oncomplete = function (event) {
  63890. if (version) {
  63891. // If the version in the JSON file is > than the version in DB
  63892. if (_this.manifestVersionFound > version.data) {
  63893. _this.mustUpdateRessources = true;
  63894. updateInDBCallback();
  63895. }
  63896. else {
  63897. callback(version.data);
  63898. }
  63899. }
  63900. else {
  63901. _this.mustUpdateRessources = true;
  63902. updateInDBCallback();
  63903. }
  63904. };
  63905. transaction.onabort = function (event) {
  63906. callback(-1);
  63907. };
  63908. var getRequest = transaction.objectStore("versions").get(url);
  63909. getRequest.onsuccess = function (event) {
  63910. version = (event.target).result;
  63911. };
  63912. getRequest.onerror = function (event) {
  63913. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  63914. callback(-1);
  63915. };
  63916. }
  63917. catch (ex) {
  63918. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  63919. callback(-1);
  63920. }
  63921. }
  63922. else {
  63923. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63924. callback(-1);
  63925. }
  63926. };
  63927. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  63928. var _this = this;
  63929. if (this.isSupported && !this.hasReachedQuota && this.db) {
  63930. try {
  63931. // Open a transaction to the database
  63932. var transaction = this.db.transaction(["versions"], "readwrite");
  63933. // the transaction could abort because of a QuotaExceededError error
  63934. transaction.onabort = function (event) {
  63935. try {
  63936. var error = event.srcElement['error'];
  63937. if (error && error.name === "QuotaExceededError") {
  63938. _this.hasReachedQuota = true;
  63939. }
  63940. }
  63941. catch (ex) { }
  63942. callback(-1);
  63943. };
  63944. transaction.oncomplete = function (event) {
  63945. callback(_this.manifestVersionFound);
  63946. };
  63947. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  63948. // Put the scene into the database
  63949. var addRequest = transaction.objectStore("versions").put(newVersion);
  63950. addRequest.onsuccess = function (event) {
  63951. };
  63952. addRequest.onerror = function (event) {
  63953. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  63954. };
  63955. }
  63956. catch (ex) {
  63957. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  63958. callback(-1);
  63959. }
  63960. }
  63961. else {
  63962. callback(-1);
  63963. }
  63964. };
  63965. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  63966. var _this = this;
  63967. var completeUrl = Database.ReturnFullUrlLocation(url);
  63968. var saveAndLoadFile = function () {
  63969. // the scene is not yet in the DB, let's try to save it
  63970. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  63971. };
  63972. this._checkVersionFromDB(completeUrl, function (version) {
  63973. if (version !== -1) {
  63974. if (!_this.mustUpdateRessources) {
  63975. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  63976. }
  63977. else {
  63978. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  63979. }
  63980. }
  63981. else {
  63982. if (errorCallback) {
  63983. errorCallback();
  63984. }
  63985. }
  63986. });
  63987. };
  63988. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  63989. if (this.isSupported && this.db) {
  63990. var targetStore;
  63991. if (url.indexOf(".babylon") !== -1) {
  63992. targetStore = "scenes";
  63993. }
  63994. else {
  63995. targetStore = "textures";
  63996. }
  63997. var file;
  63998. var transaction = this.db.transaction([targetStore]);
  63999. transaction.oncomplete = function (event) {
  64000. if (file) {
  64001. callback(file.data);
  64002. }
  64003. else {
  64004. notInDBCallback();
  64005. }
  64006. };
  64007. transaction.onabort = function (event) {
  64008. notInDBCallback();
  64009. };
  64010. var getRequest = transaction.objectStore(targetStore).get(url);
  64011. getRequest.onsuccess = function (event) {
  64012. file = (event.target).result;
  64013. };
  64014. getRequest.onerror = function (event) {
  64015. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  64016. notInDBCallback();
  64017. };
  64018. }
  64019. else {
  64020. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64021. callback();
  64022. }
  64023. };
  64024. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  64025. var _this = this;
  64026. if (this.isSupported) {
  64027. var targetStore;
  64028. if (url.indexOf(".babylon") !== -1) {
  64029. targetStore = "scenes";
  64030. }
  64031. else {
  64032. targetStore = "textures";
  64033. }
  64034. // Create XHR
  64035. var xhr = new XMLHttpRequest();
  64036. var fileData;
  64037. xhr.open("GET", url, true);
  64038. if (useArrayBuffer) {
  64039. xhr.responseType = "arraybuffer";
  64040. }
  64041. if (progressCallback) {
  64042. xhr.onprogress = progressCallback;
  64043. }
  64044. xhr.addEventListener("load", function () {
  64045. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  64046. // Blob as response (XHR2)
  64047. //fileData = xhr.responseText;
  64048. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  64049. if (!_this.hasReachedQuota && _this.db) {
  64050. // Open a transaction to the database
  64051. var transaction = _this.db.transaction([targetStore], "readwrite");
  64052. // the transaction could abort because of a QuotaExceededError error
  64053. transaction.onabort = function (event) {
  64054. try {
  64055. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64056. var error = event.srcElement['error'];
  64057. if (error && error.name === "QuotaExceededError") {
  64058. _this.hasReachedQuota = true;
  64059. }
  64060. }
  64061. catch (ex) { }
  64062. callback(fileData);
  64063. };
  64064. transaction.oncomplete = function (event) {
  64065. callback(fileData);
  64066. };
  64067. var newFile;
  64068. if (targetStore === "scenes") {
  64069. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  64070. }
  64071. else {
  64072. newFile = { textureUrl: url, data: fileData };
  64073. }
  64074. try {
  64075. // Put the scene into the database
  64076. var addRequest = transaction.objectStore(targetStore).put(newFile);
  64077. addRequest.onsuccess = function (event) {
  64078. };
  64079. addRequest.onerror = function (event) {
  64080. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  64081. };
  64082. }
  64083. catch (ex) {
  64084. callback(fileData);
  64085. }
  64086. }
  64087. else {
  64088. callback(fileData);
  64089. }
  64090. }
  64091. else {
  64092. callback();
  64093. }
  64094. }, false);
  64095. xhr.addEventListener("error", function (event) {
  64096. BABYLON.Tools.Error("error on XHR request.");
  64097. callback();
  64098. }, false);
  64099. xhr.send();
  64100. }
  64101. else {
  64102. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64103. callback();
  64104. }
  64105. };
  64106. Database.IsUASupportingBlobStorage = true;
  64107. Database.IDBStorageEnabled = true;
  64108. Database.parseURL = function (url) {
  64109. var a = document.createElement('a');
  64110. a.href = url;
  64111. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  64112. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  64113. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  64114. return absLocation;
  64115. };
  64116. Database.ReturnFullUrlLocation = function (url) {
  64117. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  64118. return (Database.parseURL(window.location.href) + url);
  64119. }
  64120. else {
  64121. return url;
  64122. }
  64123. };
  64124. return Database;
  64125. }());
  64126. BABYLON.Database = Database;
  64127. })(BABYLON || (BABYLON = {}));
  64128. //# sourceMappingURL=babylon.database.js.map
  64129. var BABYLON;
  64130. (function (BABYLON) {
  64131. var FresnelParameters = /** @class */ (function () {
  64132. function FresnelParameters() {
  64133. this._isEnabled = true;
  64134. this.leftColor = BABYLON.Color3.White();
  64135. this.rightColor = BABYLON.Color3.Black();
  64136. this.bias = 0;
  64137. this.power = 1;
  64138. }
  64139. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  64140. get: function () {
  64141. return this._isEnabled;
  64142. },
  64143. set: function (value) {
  64144. if (this._isEnabled === value) {
  64145. return;
  64146. }
  64147. this._isEnabled = value;
  64148. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  64149. },
  64150. enumerable: true,
  64151. configurable: true
  64152. });
  64153. FresnelParameters.prototype.clone = function () {
  64154. var newFresnelParameters = new FresnelParameters();
  64155. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  64156. return newFresnelParameters;
  64157. };
  64158. FresnelParameters.prototype.serialize = function () {
  64159. var serializationObject = {};
  64160. serializationObject.isEnabled = this.isEnabled;
  64161. serializationObject.leftColor = this.leftColor;
  64162. serializationObject.rightColor = this.rightColor;
  64163. serializationObject.bias = this.bias;
  64164. serializationObject.power = this.power;
  64165. return serializationObject;
  64166. };
  64167. FresnelParameters.Parse = function (parsedFresnelParameters) {
  64168. var fresnelParameters = new FresnelParameters();
  64169. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  64170. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  64171. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  64172. fresnelParameters.bias = parsedFresnelParameters.bias;
  64173. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  64174. return fresnelParameters;
  64175. };
  64176. return FresnelParameters;
  64177. }());
  64178. BABYLON.FresnelParameters = FresnelParameters;
  64179. })(BABYLON || (BABYLON = {}));
  64180. //# sourceMappingURL=babylon.fresnelParameters.js.map
  64181. var BABYLON;
  64182. (function (BABYLON) {
  64183. var MultiMaterial = /** @class */ (function (_super) {
  64184. __extends(MultiMaterial, _super);
  64185. function MultiMaterial(name, scene) {
  64186. var _this = _super.call(this, name, scene, true) || this;
  64187. scene.multiMaterials.push(_this);
  64188. _this.subMaterials = new Array();
  64189. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  64190. return _this;
  64191. }
  64192. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  64193. get: function () {
  64194. return this._subMaterials;
  64195. },
  64196. set: function (value) {
  64197. this._subMaterials = value;
  64198. this._hookArray(value);
  64199. },
  64200. enumerable: true,
  64201. configurable: true
  64202. });
  64203. MultiMaterial.prototype._hookArray = function (array) {
  64204. var _this = this;
  64205. var oldPush = array.push;
  64206. array.push = function () {
  64207. var items = [];
  64208. for (var _i = 0; _i < arguments.length; _i++) {
  64209. items[_i] = arguments[_i];
  64210. }
  64211. var result = oldPush.apply(array, items);
  64212. _this._markAllSubMeshesAsTexturesDirty();
  64213. return result;
  64214. };
  64215. var oldSplice = array.splice;
  64216. array.splice = function (index, deleteCount) {
  64217. var deleted = oldSplice.apply(array, [index, deleteCount]);
  64218. _this._markAllSubMeshesAsTexturesDirty();
  64219. return deleted;
  64220. };
  64221. };
  64222. // Properties
  64223. MultiMaterial.prototype.getSubMaterial = function (index) {
  64224. if (index < 0 || index >= this.subMaterials.length) {
  64225. return this.getScene().defaultMaterial;
  64226. }
  64227. return this.subMaterials[index];
  64228. };
  64229. MultiMaterial.prototype.getActiveTextures = function () {
  64230. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  64231. if (subMaterial) {
  64232. return subMaterial.getActiveTextures();
  64233. }
  64234. else {
  64235. return [];
  64236. }
  64237. }));
  64238. var _a;
  64239. };
  64240. // Methods
  64241. MultiMaterial.prototype.getClassName = function () {
  64242. return "MultiMaterial";
  64243. };
  64244. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  64245. for (var index = 0; index < this.subMaterials.length; index++) {
  64246. var subMaterial = this.subMaterials[index];
  64247. if (subMaterial) {
  64248. if (subMaterial.storeEffectOnSubMeshes) {
  64249. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  64250. return false;
  64251. }
  64252. continue;
  64253. }
  64254. if (!subMaterial.isReady(mesh)) {
  64255. return false;
  64256. }
  64257. }
  64258. }
  64259. return true;
  64260. };
  64261. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  64262. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  64263. for (var index = 0; index < this.subMaterials.length; index++) {
  64264. var subMaterial = null;
  64265. var current = this.subMaterials[index];
  64266. if (cloneChildren && current) {
  64267. subMaterial = current.clone(name + "-" + current.name);
  64268. }
  64269. else {
  64270. subMaterial = this.subMaterials[index];
  64271. }
  64272. newMultiMaterial.subMaterials.push(subMaterial);
  64273. }
  64274. return newMultiMaterial;
  64275. };
  64276. MultiMaterial.prototype.serialize = function () {
  64277. var serializationObject = {};
  64278. serializationObject.name = this.name;
  64279. serializationObject.id = this.id;
  64280. if (BABYLON.Tags) {
  64281. serializationObject.tags = BABYLON.Tags.GetTags(this);
  64282. }
  64283. serializationObject.materials = [];
  64284. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  64285. var subMat = this.subMaterials[matIndex];
  64286. if (subMat) {
  64287. serializationObject.materials.push(subMat.id);
  64288. }
  64289. else {
  64290. serializationObject.materials.push(null);
  64291. }
  64292. }
  64293. return serializationObject;
  64294. };
  64295. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  64296. var scene = this.getScene();
  64297. if (!scene) {
  64298. return;
  64299. }
  64300. var index = scene.multiMaterials.indexOf(this);
  64301. if (index >= 0) {
  64302. scene.multiMaterials.splice(index, 1);
  64303. }
  64304. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  64305. };
  64306. return MultiMaterial;
  64307. }(BABYLON.Material));
  64308. BABYLON.MultiMaterial = MultiMaterial;
  64309. })(BABYLON || (BABYLON = {}));
  64310. //# sourceMappingURL=babylon.multiMaterial.js.map
  64311. var BABYLON;
  64312. (function (BABYLON) {
  64313. var FreeCameraTouchInput = /** @class */ (function () {
  64314. function FreeCameraTouchInput() {
  64315. this._offsetX = null;
  64316. this._offsetY = null;
  64317. this._pointerPressed = new Array();
  64318. this.touchAngularSensibility = 200000.0;
  64319. this.touchMoveSensibility = 250.0;
  64320. }
  64321. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  64322. var _this = this;
  64323. var previousPosition = null;
  64324. if (this._pointerInput === undefined) {
  64325. this._onLostFocus = function (evt) {
  64326. _this._offsetX = null;
  64327. _this._offsetY = null;
  64328. };
  64329. this._pointerInput = function (p, s) {
  64330. var evt = p.event;
  64331. if (evt.pointerType === "mouse") {
  64332. return;
  64333. }
  64334. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  64335. if (!noPreventDefault) {
  64336. evt.preventDefault();
  64337. }
  64338. _this._pointerPressed.push(evt.pointerId);
  64339. if (_this._pointerPressed.length !== 1) {
  64340. return;
  64341. }
  64342. previousPosition = {
  64343. x: evt.clientX,
  64344. y: evt.clientY
  64345. };
  64346. }
  64347. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  64348. if (!noPreventDefault) {
  64349. evt.preventDefault();
  64350. }
  64351. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64352. if (index === -1) {
  64353. return;
  64354. }
  64355. _this._pointerPressed.splice(index, 1);
  64356. if (index != 0) {
  64357. return;
  64358. }
  64359. previousPosition = null;
  64360. _this._offsetX = null;
  64361. _this._offsetY = null;
  64362. }
  64363. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  64364. if (!noPreventDefault) {
  64365. evt.preventDefault();
  64366. }
  64367. if (!previousPosition) {
  64368. return;
  64369. }
  64370. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64371. if (index != 0) {
  64372. return;
  64373. }
  64374. _this._offsetX = evt.clientX - previousPosition.x;
  64375. _this._offsetY = -(evt.clientY - previousPosition.y);
  64376. }
  64377. };
  64378. }
  64379. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  64380. if (this._onLostFocus) {
  64381. element.addEventListener("blur", this._onLostFocus);
  64382. }
  64383. };
  64384. FreeCameraTouchInput.prototype.detachControl = function (element) {
  64385. if (this._pointerInput && element) {
  64386. if (this._observer) {
  64387. this.camera.getScene().onPointerObservable.remove(this._observer);
  64388. this._observer = null;
  64389. }
  64390. if (this._onLostFocus) {
  64391. element.removeEventListener("blur", this._onLostFocus);
  64392. this._onLostFocus = null;
  64393. }
  64394. this._pointerPressed = [];
  64395. this._offsetX = null;
  64396. this._offsetY = null;
  64397. }
  64398. };
  64399. FreeCameraTouchInput.prototype.checkInputs = function () {
  64400. if (this._offsetX && this._offsetY) {
  64401. var camera = this.camera;
  64402. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  64403. if (this._pointerPressed.length > 1) {
  64404. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  64405. }
  64406. else {
  64407. var speed = camera._computeLocalCameraSpeed();
  64408. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  64409. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  64410. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  64411. }
  64412. }
  64413. };
  64414. FreeCameraTouchInput.prototype.getClassName = function () {
  64415. return "FreeCameraTouchInput";
  64416. };
  64417. FreeCameraTouchInput.prototype.getSimpleName = function () {
  64418. return "touch";
  64419. };
  64420. __decorate([
  64421. BABYLON.serialize()
  64422. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  64423. __decorate([
  64424. BABYLON.serialize()
  64425. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  64426. return FreeCameraTouchInput;
  64427. }());
  64428. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  64429. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  64430. })(BABYLON || (BABYLON = {}));
  64431. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  64432. var BABYLON;
  64433. (function (BABYLON) {
  64434. // We're mainly based on the logic defined into the FreeCamera code
  64435. var TouchCamera = /** @class */ (function (_super) {
  64436. __extends(TouchCamera, _super);
  64437. //-- end properties for backward compatibility for inputs
  64438. function TouchCamera(name, position, scene) {
  64439. var _this = _super.call(this, name, position, scene) || this;
  64440. _this.inputs.addTouch();
  64441. _this._setupInputs();
  64442. return _this;
  64443. }
  64444. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  64445. //-- Begin properties for backward compatibility for inputs
  64446. get: function () {
  64447. var touch = this.inputs.attached["touch"];
  64448. if (touch)
  64449. return touch.touchAngularSensibility;
  64450. return 0;
  64451. },
  64452. set: function (value) {
  64453. var touch = this.inputs.attached["touch"];
  64454. if (touch)
  64455. touch.touchAngularSensibility = value;
  64456. },
  64457. enumerable: true,
  64458. configurable: true
  64459. });
  64460. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  64461. get: function () {
  64462. var touch = this.inputs.attached["touch"];
  64463. if (touch)
  64464. return touch.touchMoveSensibility;
  64465. return 0;
  64466. },
  64467. set: function (value) {
  64468. var touch = this.inputs.attached["touch"];
  64469. if (touch)
  64470. touch.touchMoveSensibility = value;
  64471. },
  64472. enumerable: true,
  64473. configurable: true
  64474. });
  64475. TouchCamera.prototype.getClassName = function () {
  64476. return "TouchCamera";
  64477. };
  64478. TouchCamera.prototype._setupInputs = function () {
  64479. var mouse = this.inputs.attached["mouse"];
  64480. if (mouse) {
  64481. mouse.touchEnabled = false;
  64482. }
  64483. };
  64484. return TouchCamera;
  64485. }(BABYLON.FreeCamera));
  64486. BABYLON.TouchCamera = TouchCamera;
  64487. })(BABYLON || (BABYLON = {}));
  64488. //# sourceMappingURL=babylon.touchCamera.js.map
  64489. var BABYLON;
  64490. (function (BABYLON) {
  64491. var ProceduralTexture = /** @class */ (function (_super) {
  64492. __extends(ProceduralTexture, _super);
  64493. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  64494. if (fallbackTexture === void 0) { fallbackTexture = null; }
  64495. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64496. if (isCube === void 0) { isCube = false; }
  64497. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  64498. _this.isCube = isCube;
  64499. _this.isEnabled = true;
  64500. _this._currentRefreshId = -1;
  64501. _this._refreshRate = 1;
  64502. _this._vertexBuffers = {};
  64503. _this._uniforms = new Array();
  64504. _this._samplers = new Array();
  64505. _this._textures = {};
  64506. _this._floats = {};
  64507. _this._floatsArrays = {};
  64508. _this._colors3 = {};
  64509. _this._colors4 = {};
  64510. _this._vectors2 = {};
  64511. _this._vectors3 = {};
  64512. _this._matrices = {};
  64513. _this._fallbackTextureUsed = false;
  64514. scene._proceduralTextures.push(_this);
  64515. _this._engine = scene.getEngine();
  64516. _this.name = name;
  64517. _this.isRenderTarget = true;
  64518. _this._size = size;
  64519. _this._generateMipMaps = generateMipMaps;
  64520. _this.setFragment(fragment);
  64521. _this._fallbackTexture = fallbackTexture;
  64522. if (isCube) {
  64523. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  64524. _this.setFloat("face", 0);
  64525. }
  64526. else {
  64527. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  64528. }
  64529. // VBO
  64530. var vertices = [];
  64531. vertices.push(1, 1);
  64532. vertices.push(-1, 1);
  64533. vertices.push(-1, -1);
  64534. vertices.push(1, -1);
  64535. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64536. _this._createIndexBuffer();
  64537. return _this;
  64538. }
  64539. ProceduralTexture.prototype._createIndexBuffer = function () {
  64540. var engine = this._engine;
  64541. // Indices
  64542. var indices = [];
  64543. indices.push(0);
  64544. indices.push(1);
  64545. indices.push(2);
  64546. indices.push(0);
  64547. indices.push(2);
  64548. indices.push(3);
  64549. this._indexBuffer = engine.createIndexBuffer(indices);
  64550. };
  64551. ProceduralTexture.prototype._rebuild = function () {
  64552. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64553. if (vb) {
  64554. vb._rebuild();
  64555. }
  64556. this._createIndexBuffer();
  64557. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64558. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64559. }
  64560. };
  64561. ProceduralTexture.prototype.reset = function () {
  64562. if (this._effect === undefined) {
  64563. return;
  64564. }
  64565. var engine = this._engine;
  64566. engine._releaseEffect(this._effect);
  64567. };
  64568. ProceduralTexture.prototype.isReady = function () {
  64569. var _this = this;
  64570. var engine = this._engine;
  64571. var shaders;
  64572. if (!this._fragment) {
  64573. return false;
  64574. }
  64575. if (this._fallbackTextureUsed) {
  64576. return true;
  64577. }
  64578. if (this._fragment.fragmentElement !== undefined) {
  64579. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  64580. }
  64581. else {
  64582. shaders = { vertex: "procedural", fragment: this._fragment };
  64583. }
  64584. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  64585. _this.releaseInternalTexture();
  64586. if (_this._fallbackTexture) {
  64587. _this._texture = _this._fallbackTexture._texture;
  64588. if (_this._texture) {
  64589. _this._texture.incrementReferences();
  64590. }
  64591. }
  64592. _this._fallbackTextureUsed = true;
  64593. });
  64594. return this._effect.isReady();
  64595. };
  64596. ProceduralTexture.prototype.resetRefreshCounter = function () {
  64597. this._currentRefreshId = -1;
  64598. };
  64599. ProceduralTexture.prototype.setFragment = function (fragment) {
  64600. this._fragment = fragment;
  64601. };
  64602. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  64603. get: function () {
  64604. return this._refreshRate;
  64605. },
  64606. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64607. set: function (value) {
  64608. this._refreshRate = value;
  64609. this.resetRefreshCounter();
  64610. },
  64611. enumerable: true,
  64612. configurable: true
  64613. });
  64614. ProceduralTexture.prototype._shouldRender = function () {
  64615. if (!this.isEnabled || !this.isReady() || !this._texture) {
  64616. return false;
  64617. }
  64618. if (this._fallbackTextureUsed) {
  64619. return false;
  64620. }
  64621. if (this._currentRefreshId === -1) {
  64622. this._currentRefreshId = 1;
  64623. return true;
  64624. }
  64625. if (this.refreshRate === this._currentRefreshId) {
  64626. this._currentRefreshId = 1;
  64627. return true;
  64628. }
  64629. this._currentRefreshId++;
  64630. return false;
  64631. };
  64632. ProceduralTexture.prototype.getRenderSize = function () {
  64633. return this._size;
  64634. };
  64635. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  64636. if (this._fallbackTextureUsed) {
  64637. return;
  64638. }
  64639. this.releaseInternalTexture();
  64640. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  64641. };
  64642. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  64643. if (this._uniforms.indexOf(uniformName) === -1) {
  64644. this._uniforms.push(uniformName);
  64645. }
  64646. };
  64647. ProceduralTexture.prototype.setTexture = function (name, texture) {
  64648. if (this._samplers.indexOf(name) === -1) {
  64649. this._samplers.push(name);
  64650. }
  64651. this._textures[name] = texture;
  64652. return this;
  64653. };
  64654. ProceduralTexture.prototype.setFloat = function (name, value) {
  64655. this._checkUniform(name);
  64656. this._floats[name] = value;
  64657. return this;
  64658. };
  64659. ProceduralTexture.prototype.setFloats = function (name, value) {
  64660. this._checkUniform(name);
  64661. this._floatsArrays[name] = value;
  64662. return this;
  64663. };
  64664. ProceduralTexture.prototype.setColor3 = function (name, value) {
  64665. this._checkUniform(name);
  64666. this._colors3[name] = value;
  64667. return this;
  64668. };
  64669. ProceduralTexture.prototype.setColor4 = function (name, value) {
  64670. this._checkUniform(name);
  64671. this._colors4[name] = value;
  64672. return this;
  64673. };
  64674. ProceduralTexture.prototype.setVector2 = function (name, value) {
  64675. this._checkUniform(name);
  64676. this._vectors2[name] = value;
  64677. return this;
  64678. };
  64679. ProceduralTexture.prototype.setVector3 = function (name, value) {
  64680. this._checkUniform(name);
  64681. this._vectors3[name] = value;
  64682. return this;
  64683. };
  64684. ProceduralTexture.prototype.setMatrix = function (name, value) {
  64685. this._checkUniform(name);
  64686. this._matrices[name] = value;
  64687. return this;
  64688. };
  64689. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  64690. var scene = this.getScene();
  64691. if (!scene) {
  64692. return;
  64693. }
  64694. var engine = this._engine;
  64695. // Render
  64696. engine.enableEffect(this._effect);
  64697. engine.setState(false);
  64698. // Texture
  64699. for (var name in this._textures) {
  64700. this._effect.setTexture(name, this._textures[name]);
  64701. }
  64702. // Float
  64703. for (name in this._floats) {
  64704. this._effect.setFloat(name, this._floats[name]);
  64705. }
  64706. // Floats
  64707. for (name in this._floatsArrays) {
  64708. this._effect.setArray(name, this._floatsArrays[name]);
  64709. }
  64710. // Color3
  64711. for (name in this._colors3) {
  64712. this._effect.setColor3(name, this._colors3[name]);
  64713. }
  64714. // Color4
  64715. for (name in this._colors4) {
  64716. var color = this._colors4[name];
  64717. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  64718. }
  64719. // Vector2
  64720. for (name in this._vectors2) {
  64721. this._effect.setVector2(name, this._vectors2[name]);
  64722. }
  64723. // Vector3
  64724. for (name in this._vectors3) {
  64725. this._effect.setVector3(name, this._vectors3[name]);
  64726. }
  64727. // Matrix
  64728. for (name in this._matrices) {
  64729. this._effect.setMatrix(name, this._matrices[name]);
  64730. }
  64731. if (!this._texture) {
  64732. return;
  64733. }
  64734. if (this.isCube) {
  64735. for (var face = 0; face < 6; face++) {
  64736. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  64737. // VBOs
  64738. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64739. this._effect.setFloat("face", face);
  64740. // Clear
  64741. engine.clear(scene.clearColor, true, true, true);
  64742. // Draw order
  64743. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64744. // Mipmaps
  64745. if (face === 5) {
  64746. engine.generateMipMapsForCubemap(this._texture);
  64747. }
  64748. }
  64749. }
  64750. else {
  64751. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  64752. // VBOs
  64753. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64754. // Clear
  64755. engine.clear(scene.clearColor, true, true, true);
  64756. // Draw order
  64757. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64758. }
  64759. // Unbind
  64760. engine.unBindFramebuffer(this._texture, this.isCube);
  64761. if (this.onGenerated) {
  64762. this.onGenerated();
  64763. }
  64764. };
  64765. ProceduralTexture.prototype.clone = function () {
  64766. var textureSize = this.getSize();
  64767. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  64768. // Base texture
  64769. newTexture.hasAlpha = this.hasAlpha;
  64770. newTexture.level = this.level;
  64771. // RenderTarget Texture
  64772. newTexture.coordinatesMode = this.coordinatesMode;
  64773. return newTexture;
  64774. };
  64775. ProceduralTexture.prototype.dispose = function () {
  64776. var scene = this.getScene();
  64777. if (!scene) {
  64778. return;
  64779. }
  64780. var index = scene._proceduralTextures.indexOf(this);
  64781. if (index >= 0) {
  64782. scene._proceduralTextures.splice(index, 1);
  64783. }
  64784. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64785. if (vertexBuffer) {
  64786. vertexBuffer.dispose();
  64787. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64788. }
  64789. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  64790. this._indexBuffer = null;
  64791. }
  64792. _super.prototype.dispose.call(this);
  64793. };
  64794. return ProceduralTexture;
  64795. }(BABYLON.Texture));
  64796. BABYLON.ProceduralTexture = ProceduralTexture;
  64797. })(BABYLON || (BABYLON = {}));
  64798. //# sourceMappingURL=babylon.proceduralTexture.js.map
  64799. var BABYLON;
  64800. (function (BABYLON) {
  64801. var CustomProceduralTexture = /** @class */ (function (_super) {
  64802. __extends(CustomProceduralTexture, _super);
  64803. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  64804. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  64805. _this._animate = true;
  64806. _this._time = 0;
  64807. _this._texturePath = texturePath;
  64808. //Try to load json
  64809. _this.loadJson(texturePath);
  64810. _this.refreshRate = 1;
  64811. return _this;
  64812. }
  64813. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  64814. var _this = this;
  64815. var noConfigFile = function () {
  64816. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  64817. try {
  64818. _this.setFragment(_this._texturePath);
  64819. }
  64820. catch (ex) {
  64821. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  64822. }
  64823. };
  64824. var configFileUrl = jsonUrl + "/config.json";
  64825. var xhr = new XMLHttpRequest();
  64826. xhr.open("GET", configFileUrl, true);
  64827. xhr.addEventListener("load", function () {
  64828. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64829. try {
  64830. _this._config = JSON.parse(xhr.response);
  64831. _this.updateShaderUniforms();
  64832. _this.updateTextures();
  64833. _this.setFragment(_this._texturePath + "/custom");
  64834. _this._animate = _this._config.animate;
  64835. _this.refreshRate = _this._config.refreshrate;
  64836. }
  64837. catch (ex) {
  64838. noConfigFile();
  64839. }
  64840. }
  64841. else {
  64842. noConfigFile();
  64843. }
  64844. }, false);
  64845. xhr.addEventListener("error", function () {
  64846. noConfigFile();
  64847. }, false);
  64848. try {
  64849. xhr.send();
  64850. }
  64851. catch (ex) {
  64852. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  64853. }
  64854. };
  64855. CustomProceduralTexture.prototype.isReady = function () {
  64856. if (!_super.prototype.isReady.call(this)) {
  64857. return false;
  64858. }
  64859. for (var name in this._textures) {
  64860. var texture = this._textures[name];
  64861. if (!texture.isReady()) {
  64862. return false;
  64863. }
  64864. }
  64865. return true;
  64866. };
  64867. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  64868. var scene = this.getScene();
  64869. if (this._animate && scene) {
  64870. this._time += scene.getAnimationRatio() * 0.03;
  64871. this.updateShaderUniforms();
  64872. }
  64873. _super.prototype.render.call(this, useCameraPostProcess);
  64874. };
  64875. CustomProceduralTexture.prototype.updateTextures = function () {
  64876. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  64877. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  64878. }
  64879. };
  64880. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  64881. if (this._config) {
  64882. for (var j = 0; j < this._config.uniforms.length; j++) {
  64883. var uniform = this._config.uniforms[j];
  64884. switch (uniform.type) {
  64885. case "float":
  64886. this.setFloat(uniform.name, uniform.value);
  64887. break;
  64888. case "color3":
  64889. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  64890. break;
  64891. case "color4":
  64892. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  64893. break;
  64894. case "vector2":
  64895. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  64896. break;
  64897. case "vector3":
  64898. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  64899. break;
  64900. }
  64901. }
  64902. }
  64903. this.setFloat("time", this._time);
  64904. };
  64905. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  64906. get: function () {
  64907. return this._animate;
  64908. },
  64909. set: function (value) {
  64910. this._animate = value;
  64911. },
  64912. enumerable: true,
  64913. configurable: true
  64914. });
  64915. return CustomProceduralTexture;
  64916. }(BABYLON.ProceduralTexture));
  64917. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  64918. })(BABYLON || (BABYLON = {}));
  64919. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  64920. var BABYLON;
  64921. (function (BABYLON) {
  64922. var FreeCameraGamepadInput = /** @class */ (function () {
  64923. function FreeCameraGamepadInput() {
  64924. this.gamepadAngularSensibility = 200;
  64925. this.gamepadMoveSensibility = 40;
  64926. // private members
  64927. this._cameraTransform = BABYLON.Matrix.Identity();
  64928. this._deltaTransform = BABYLON.Vector3.Zero();
  64929. this._vector3 = BABYLON.Vector3.Zero();
  64930. this._vector2 = BABYLON.Vector2.Zero();
  64931. }
  64932. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64933. var _this = this;
  64934. var manager = this.camera.getScene().gamepadManager;
  64935. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64936. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64937. // prioritize XBOX gamepads.
  64938. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64939. _this.gamepad = gamepad;
  64940. }
  64941. }
  64942. });
  64943. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64944. if (_this.gamepad === gamepad) {
  64945. _this.gamepad = null;
  64946. }
  64947. });
  64948. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64949. };
  64950. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  64951. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64952. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64953. this.gamepad = null;
  64954. };
  64955. FreeCameraGamepadInput.prototype.checkInputs = function () {
  64956. if (this.gamepad && this.gamepad.leftStick) {
  64957. var camera = this.camera;
  64958. var LSValues = this.gamepad.leftStick;
  64959. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  64960. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64961. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  64962. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  64963. var RSValues = this.gamepad.rightStick;
  64964. if (RSValues) {
  64965. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  64966. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  64967. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  64968. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  64969. }
  64970. else {
  64971. RSValues = { x: 0, y: 0 };
  64972. }
  64973. if (!camera.rotationQuaternion) {
  64974. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  64975. }
  64976. else {
  64977. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  64978. }
  64979. var speed = camera._computeLocalCameraSpeed() * 50.0;
  64980. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  64981. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  64982. camera.cameraDirection.addInPlace(this._deltaTransform);
  64983. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  64984. camera.cameraRotation.addInPlace(this._vector2);
  64985. }
  64986. };
  64987. FreeCameraGamepadInput.prototype.getClassName = function () {
  64988. return "FreeCameraGamepadInput";
  64989. };
  64990. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  64991. return "gamepad";
  64992. };
  64993. __decorate([
  64994. BABYLON.serialize()
  64995. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  64996. __decorate([
  64997. BABYLON.serialize()
  64998. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64999. return FreeCameraGamepadInput;
  65000. }());
  65001. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  65002. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  65003. })(BABYLON || (BABYLON = {}));
  65004. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  65005. var BABYLON;
  65006. (function (BABYLON) {
  65007. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  65008. function ArcRotateCameraGamepadInput() {
  65009. this.gamepadRotationSensibility = 80;
  65010. this.gamepadMoveSensibility = 40;
  65011. }
  65012. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65013. var _this = this;
  65014. var manager = this.camera.getScene().gamepadManager;
  65015. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65016. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65017. // prioritize XBOX gamepads.
  65018. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65019. _this.gamepad = gamepad;
  65020. }
  65021. }
  65022. });
  65023. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65024. if (_this.gamepad === gamepad) {
  65025. _this.gamepad = null;
  65026. }
  65027. });
  65028. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65029. };
  65030. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  65031. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65032. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65033. this.gamepad = null;
  65034. };
  65035. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  65036. if (this.gamepad) {
  65037. var camera = this.camera;
  65038. var RSValues = this.gamepad.rightStick;
  65039. if (RSValues) {
  65040. if (RSValues.x != 0) {
  65041. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  65042. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  65043. camera.inertialAlphaOffset += normalizedRX;
  65044. }
  65045. }
  65046. if (RSValues.y != 0) {
  65047. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  65048. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  65049. camera.inertialBetaOffset += normalizedRY;
  65050. }
  65051. }
  65052. }
  65053. var LSValues = this.gamepad.leftStick;
  65054. if (LSValues && LSValues.y != 0) {
  65055. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65056. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  65057. this.camera.inertialRadiusOffset -= normalizedLY;
  65058. }
  65059. }
  65060. }
  65061. };
  65062. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  65063. return "ArcRotateCameraGamepadInput";
  65064. };
  65065. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  65066. return "gamepad";
  65067. };
  65068. __decorate([
  65069. BABYLON.serialize()
  65070. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  65071. __decorate([
  65072. BABYLON.serialize()
  65073. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65074. return ArcRotateCameraGamepadInput;
  65075. }());
  65076. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  65077. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  65078. })(BABYLON || (BABYLON = {}));
  65079. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  65080. var BABYLON;
  65081. (function (BABYLON) {
  65082. var GamepadManager = /** @class */ (function () {
  65083. function GamepadManager(_scene) {
  65084. var _this = this;
  65085. this._scene = _scene;
  65086. this._babylonGamepads = [];
  65087. this._oneGamepadConnected = false;
  65088. this._isMonitoring = false;
  65089. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  65090. if (!BABYLON.Tools.IsWindowObjectExist()) {
  65091. this._gamepadEventSupported = false;
  65092. }
  65093. else {
  65094. this._gamepadEventSupported = 'GamepadEvent' in window;
  65095. this._gamepadSupport = (navigator.getGamepads ||
  65096. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  65097. }
  65098. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  65099. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  65100. for (var i in _this._babylonGamepads) {
  65101. var gamepad = _this._babylonGamepads[i];
  65102. if (gamepad && gamepad._isConnected) {
  65103. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  65104. }
  65105. }
  65106. });
  65107. this._onGamepadConnectedEvent = function (evt) {
  65108. var gamepad = evt.gamepad;
  65109. if (gamepad.index in _this._babylonGamepads) {
  65110. if (_this._babylonGamepads[gamepad.index].isConnected) {
  65111. return;
  65112. }
  65113. }
  65114. var newGamepad;
  65115. if (_this._babylonGamepads[gamepad.index]) {
  65116. newGamepad = _this._babylonGamepads[gamepad.index];
  65117. newGamepad.browserGamepad = gamepad;
  65118. newGamepad._isConnected = true;
  65119. }
  65120. else {
  65121. newGamepad = _this._addNewGamepad(gamepad);
  65122. }
  65123. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  65124. _this._startMonitoringGamepads();
  65125. };
  65126. this._onGamepadDisconnectedEvent = function (evt) {
  65127. var gamepad = evt.gamepad;
  65128. // Remove the gamepad from the list of gamepads to monitor.
  65129. for (var i in _this._babylonGamepads) {
  65130. if (_this._babylonGamepads[i].index === gamepad.index) {
  65131. var disconnectedGamepad = _this._babylonGamepads[i];
  65132. disconnectedGamepad._isConnected = false;
  65133. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  65134. break;
  65135. }
  65136. }
  65137. };
  65138. if (this._gamepadSupport) {
  65139. //first add already-connected gamepads
  65140. this._updateGamepadObjects();
  65141. if (this._babylonGamepads.length) {
  65142. this._startMonitoringGamepads();
  65143. }
  65144. // Checking if the gamepad connected event is supported (like in Firefox)
  65145. if (this._gamepadEventSupported) {
  65146. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  65147. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  65148. }
  65149. else {
  65150. this._startMonitoringGamepads();
  65151. }
  65152. }
  65153. }
  65154. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  65155. get: function () {
  65156. return this._babylonGamepads;
  65157. },
  65158. enumerable: true,
  65159. configurable: true
  65160. });
  65161. GamepadManager.prototype.getGamepadByType = function (type) {
  65162. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  65163. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  65164. var gamepad = _a[_i];
  65165. if (gamepad && gamepad.type === type) {
  65166. return gamepad;
  65167. }
  65168. }
  65169. return null;
  65170. };
  65171. GamepadManager.prototype.dispose = function () {
  65172. if (this._gamepadEventSupported) {
  65173. if (this._onGamepadConnectedEvent) {
  65174. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  65175. }
  65176. if (this._onGamepadDisconnectedEvent) {
  65177. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  65178. }
  65179. this._onGamepadConnectedEvent = null;
  65180. this._onGamepadDisconnectedEvent = null;
  65181. }
  65182. this._babylonGamepads.forEach(function (gamepad) {
  65183. gamepad.dispose();
  65184. });
  65185. this.onGamepadConnectedObservable.clear();
  65186. this.onGamepadDisconnectedObservable.clear();
  65187. this._oneGamepadConnected = false;
  65188. this._stopMonitoringGamepads();
  65189. this._babylonGamepads = [];
  65190. };
  65191. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  65192. if (!this._oneGamepadConnected) {
  65193. this._oneGamepadConnected = true;
  65194. }
  65195. var newGamepad;
  65196. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  65197. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  65198. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  65199. }
  65200. else if (gamepad.pose) {
  65201. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  65202. }
  65203. else {
  65204. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  65205. }
  65206. this._babylonGamepads[newGamepad.index] = newGamepad;
  65207. return newGamepad;
  65208. };
  65209. GamepadManager.prototype._startMonitoringGamepads = function () {
  65210. if (!this._isMonitoring) {
  65211. this._isMonitoring = true;
  65212. //back-comp
  65213. if (!this._scene) {
  65214. this._checkGamepadsStatus();
  65215. }
  65216. }
  65217. };
  65218. GamepadManager.prototype._stopMonitoringGamepads = function () {
  65219. this._isMonitoring = false;
  65220. };
  65221. GamepadManager.prototype._checkGamepadsStatus = function () {
  65222. var _this = this;
  65223. // Hack to be compatible Chrome
  65224. this._updateGamepadObjects();
  65225. for (var i in this._babylonGamepads) {
  65226. var gamepad = this._babylonGamepads[i];
  65227. if (!gamepad || !gamepad.isConnected) {
  65228. continue;
  65229. }
  65230. gamepad.update();
  65231. }
  65232. if (this._isMonitoring && !this._scene) {
  65233. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  65234. }
  65235. };
  65236. // This function is called only on Chrome, which does not properly support
  65237. // connection/disconnection events and forces you to recopy again the gamepad object
  65238. GamepadManager.prototype._updateGamepadObjects = function () {
  65239. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  65240. for (var i = 0; i < gamepads.length; i++) {
  65241. if (gamepads[i]) {
  65242. if (!this._babylonGamepads[gamepads[i].index]) {
  65243. var newGamepad = this._addNewGamepad(gamepads[i]);
  65244. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  65245. }
  65246. else {
  65247. // Forced to copy again this object for Chrome for unknown reason
  65248. this._babylonGamepads[i].browserGamepad = gamepads[i];
  65249. if (!this._babylonGamepads[i].isConnected) {
  65250. this._babylonGamepads[i]._isConnected = true;
  65251. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  65252. }
  65253. }
  65254. }
  65255. }
  65256. };
  65257. return GamepadManager;
  65258. }());
  65259. BABYLON.GamepadManager = GamepadManager;
  65260. })(BABYLON || (BABYLON = {}));
  65261. //# sourceMappingURL=babylon.gamepadManager.js.map
  65262. var BABYLON;
  65263. (function (BABYLON) {
  65264. var StickValues = /** @class */ (function () {
  65265. function StickValues(x, y) {
  65266. this.x = x;
  65267. this.y = y;
  65268. }
  65269. return StickValues;
  65270. }());
  65271. BABYLON.StickValues = StickValues;
  65272. var Gamepad = /** @class */ (function () {
  65273. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  65274. if (leftStickX === void 0) { leftStickX = 0; }
  65275. if (leftStickY === void 0) { leftStickY = 1; }
  65276. if (rightStickX === void 0) { rightStickX = 2; }
  65277. if (rightStickY === void 0) { rightStickY = 3; }
  65278. this.id = id;
  65279. this.index = index;
  65280. this.browserGamepad = browserGamepad;
  65281. this._isConnected = true;
  65282. this._invertLeftStickY = false;
  65283. this.type = Gamepad.GAMEPAD;
  65284. this._leftStickAxisX = leftStickX;
  65285. this._leftStickAxisY = leftStickY;
  65286. this._rightStickAxisX = rightStickX;
  65287. this._rightStickAxisY = rightStickY;
  65288. if (this.browserGamepad.axes.length >= 2) {
  65289. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  65290. }
  65291. if (this.browserGamepad.axes.length >= 4) {
  65292. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  65293. }
  65294. }
  65295. Object.defineProperty(Gamepad.prototype, "isConnected", {
  65296. get: function () {
  65297. return this._isConnected;
  65298. },
  65299. enumerable: true,
  65300. configurable: true
  65301. });
  65302. Gamepad.prototype.onleftstickchanged = function (callback) {
  65303. this._onleftstickchanged = callback;
  65304. };
  65305. Gamepad.prototype.onrightstickchanged = function (callback) {
  65306. this._onrightstickchanged = callback;
  65307. };
  65308. Object.defineProperty(Gamepad.prototype, "leftStick", {
  65309. get: function () {
  65310. return this._leftStick;
  65311. },
  65312. set: function (newValues) {
  65313. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  65314. this._onleftstickchanged(newValues);
  65315. }
  65316. this._leftStick = newValues;
  65317. },
  65318. enumerable: true,
  65319. configurable: true
  65320. });
  65321. Object.defineProperty(Gamepad.prototype, "rightStick", {
  65322. get: function () {
  65323. return this._rightStick;
  65324. },
  65325. set: function (newValues) {
  65326. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  65327. this._onrightstickchanged(newValues);
  65328. }
  65329. this._rightStick = newValues;
  65330. },
  65331. enumerable: true,
  65332. configurable: true
  65333. });
  65334. Gamepad.prototype.update = function () {
  65335. if (this._leftStick) {
  65336. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  65337. if (this._invertLeftStickY) {
  65338. this.leftStick.y *= -1;
  65339. }
  65340. }
  65341. if (this._rightStick) {
  65342. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  65343. }
  65344. };
  65345. Gamepad.prototype.dispose = function () {
  65346. };
  65347. Gamepad.GAMEPAD = 0;
  65348. Gamepad.GENERIC = 1;
  65349. Gamepad.XBOX = 2;
  65350. Gamepad.POSE_ENABLED = 3;
  65351. return Gamepad;
  65352. }());
  65353. BABYLON.Gamepad = Gamepad;
  65354. var GenericPad = /** @class */ (function (_super) {
  65355. __extends(GenericPad, _super);
  65356. function GenericPad(id, index, browserGamepad) {
  65357. var _this = _super.call(this, id, index, browserGamepad) || this;
  65358. _this.onButtonDownObservable = new BABYLON.Observable();
  65359. _this.onButtonUpObservable = new BABYLON.Observable();
  65360. _this.type = Gamepad.GENERIC;
  65361. _this._buttons = new Array(browserGamepad.buttons.length);
  65362. return _this;
  65363. }
  65364. GenericPad.prototype.onbuttondown = function (callback) {
  65365. this._onbuttondown = callback;
  65366. };
  65367. GenericPad.prototype.onbuttonup = function (callback) {
  65368. this._onbuttonup = callback;
  65369. };
  65370. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  65371. if (newValue !== currentValue) {
  65372. if (newValue === 1) {
  65373. if (this._onbuttondown) {
  65374. this._onbuttondown(buttonIndex);
  65375. }
  65376. this.onButtonDownObservable.notifyObservers(buttonIndex);
  65377. }
  65378. if (newValue === 0) {
  65379. if (this._onbuttonup) {
  65380. this._onbuttonup(buttonIndex);
  65381. }
  65382. this.onButtonUpObservable.notifyObservers(buttonIndex);
  65383. }
  65384. }
  65385. return newValue;
  65386. };
  65387. GenericPad.prototype.update = function () {
  65388. _super.prototype.update.call(this);
  65389. for (var index = 0; index < this._buttons.length; index++) {
  65390. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  65391. }
  65392. };
  65393. GenericPad.prototype.dispose = function () {
  65394. _super.prototype.dispose.call(this);
  65395. this.onButtonDownObservable.clear();
  65396. this.onButtonUpObservable.clear();
  65397. };
  65398. return GenericPad;
  65399. }(Gamepad));
  65400. BABYLON.GenericPad = GenericPad;
  65401. })(BABYLON || (BABYLON = {}));
  65402. //# sourceMappingURL=babylon.gamepad.js.map
  65403. var BABYLON;
  65404. (function (BABYLON) {
  65405. var Xbox360Button;
  65406. (function (Xbox360Button) {
  65407. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  65408. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  65409. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  65410. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  65411. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  65412. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  65413. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  65414. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  65415. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  65416. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  65417. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  65418. var Xbox360Dpad;
  65419. (function (Xbox360Dpad) {
  65420. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  65421. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  65422. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  65423. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  65424. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  65425. var Xbox360Pad = /** @class */ (function (_super) {
  65426. __extends(Xbox360Pad, _super);
  65427. function Xbox360Pad(id, index, gamepad, xboxOne) {
  65428. if (xboxOne === void 0) { xboxOne = false; }
  65429. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  65430. _this._leftTrigger = 0;
  65431. _this._rightTrigger = 0;
  65432. _this.onButtonDownObservable = new BABYLON.Observable();
  65433. _this.onButtonUpObservable = new BABYLON.Observable();
  65434. _this.onPadDownObservable = new BABYLON.Observable();
  65435. _this.onPadUpObservable = new BABYLON.Observable();
  65436. _this._buttonA = 0;
  65437. _this._buttonB = 0;
  65438. _this._buttonX = 0;
  65439. _this._buttonY = 0;
  65440. _this._buttonBack = 0;
  65441. _this._buttonStart = 0;
  65442. _this._buttonLB = 0;
  65443. _this._buttonRB = 0;
  65444. _this._buttonLeftStick = 0;
  65445. _this._buttonRightStick = 0;
  65446. _this._dPadUp = 0;
  65447. _this._dPadDown = 0;
  65448. _this._dPadLeft = 0;
  65449. _this._dPadRight = 0;
  65450. _this._isXboxOnePad = false;
  65451. _this.type = BABYLON.Gamepad.XBOX;
  65452. _this._isXboxOnePad = xboxOne;
  65453. return _this;
  65454. }
  65455. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  65456. this._onlefttriggerchanged = callback;
  65457. };
  65458. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  65459. this._onrighttriggerchanged = callback;
  65460. };
  65461. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  65462. get: function () {
  65463. return this._leftTrigger;
  65464. },
  65465. set: function (newValue) {
  65466. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  65467. this._onlefttriggerchanged(newValue);
  65468. }
  65469. this._leftTrigger = newValue;
  65470. },
  65471. enumerable: true,
  65472. configurable: true
  65473. });
  65474. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  65475. get: function () {
  65476. return this._rightTrigger;
  65477. },
  65478. set: function (newValue) {
  65479. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  65480. this._onrighttriggerchanged(newValue);
  65481. }
  65482. this._rightTrigger = newValue;
  65483. },
  65484. enumerable: true,
  65485. configurable: true
  65486. });
  65487. Xbox360Pad.prototype.onbuttondown = function (callback) {
  65488. this._onbuttondown = callback;
  65489. };
  65490. Xbox360Pad.prototype.onbuttonup = function (callback) {
  65491. this._onbuttonup = callback;
  65492. };
  65493. Xbox360Pad.prototype.ondpaddown = function (callback) {
  65494. this._ondpaddown = callback;
  65495. };
  65496. Xbox360Pad.prototype.ondpadup = function (callback) {
  65497. this._ondpadup = callback;
  65498. };
  65499. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  65500. if (newValue !== currentValue) {
  65501. if (newValue === 1) {
  65502. if (this._onbuttondown) {
  65503. this._onbuttondown(buttonType);
  65504. }
  65505. this.onButtonDownObservable.notifyObservers(buttonType);
  65506. }
  65507. if (newValue === 0) {
  65508. if (this._onbuttonup) {
  65509. this._onbuttonup(buttonType);
  65510. }
  65511. this.onButtonUpObservable.notifyObservers(buttonType);
  65512. }
  65513. }
  65514. return newValue;
  65515. };
  65516. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  65517. if (newValue !== currentValue) {
  65518. if (newValue === 1) {
  65519. if (this._ondpaddown) {
  65520. this._ondpaddown(buttonType);
  65521. }
  65522. this.onPadDownObservable.notifyObservers(buttonType);
  65523. }
  65524. if (newValue === 0) {
  65525. if (this._ondpadup) {
  65526. this._ondpadup(buttonType);
  65527. }
  65528. this.onPadUpObservable.notifyObservers(buttonType);
  65529. }
  65530. }
  65531. return newValue;
  65532. };
  65533. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  65534. get: function () {
  65535. return this._buttonA;
  65536. },
  65537. set: function (value) {
  65538. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  65539. },
  65540. enumerable: true,
  65541. configurable: true
  65542. });
  65543. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  65544. get: function () {
  65545. return this._buttonB;
  65546. },
  65547. set: function (value) {
  65548. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  65549. },
  65550. enumerable: true,
  65551. configurable: true
  65552. });
  65553. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  65554. get: function () {
  65555. return this._buttonX;
  65556. },
  65557. set: function (value) {
  65558. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  65559. },
  65560. enumerable: true,
  65561. configurable: true
  65562. });
  65563. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  65564. get: function () {
  65565. return this._buttonY;
  65566. },
  65567. set: function (value) {
  65568. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  65569. },
  65570. enumerable: true,
  65571. configurable: true
  65572. });
  65573. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  65574. get: function () {
  65575. return this._buttonStart;
  65576. },
  65577. set: function (value) {
  65578. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  65579. },
  65580. enumerable: true,
  65581. configurable: true
  65582. });
  65583. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  65584. get: function () {
  65585. return this._buttonBack;
  65586. },
  65587. set: function (value) {
  65588. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  65589. },
  65590. enumerable: true,
  65591. configurable: true
  65592. });
  65593. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  65594. get: function () {
  65595. return this._buttonLB;
  65596. },
  65597. set: function (value) {
  65598. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  65599. },
  65600. enumerable: true,
  65601. configurable: true
  65602. });
  65603. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  65604. get: function () {
  65605. return this._buttonRB;
  65606. },
  65607. set: function (value) {
  65608. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  65609. },
  65610. enumerable: true,
  65611. configurable: true
  65612. });
  65613. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  65614. get: function () {
  65615. return this._buttonLeftStick;
  65616. },
  65617. set: function (value) {
  65618. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  65619. },
  65620. enumerable: true,
  65621. configurable: true
  65622. });
  65623. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  65624. get: function () {
  65625. return this._buttonRightStick;
  65626. },
  65627. set: function (value) {
  65628. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  65629. },
  65630. enumerable: true,
  65631. configurable: true
  65632. });
  65633. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  65634. get: function () {
  65635. return this._dPadUp;
  65636. },
  65637. set: function (value) {
  65638. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  65639. },
  65640. enumerable: true,
  65641. configurable: true
  65642. });
  65643. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  65644. get: function () {
  65645. return this._dPadDown;
  65646. },
  65647. set: function (value) {
  65648. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  65649. },
  65650. enumerable: true,
  65651. configurable: true
  65652. });
  65653. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  65654. get: function () {
  65655. return this._dPadLeft;
  65656. },
  65657. set: function (value) {
  65658. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  65659. },
  65660. enumerable: true,
  65661. configurable: true
  65662. });
  65663. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  65664. get: function () {
  65665. return this._dPadRight;
  65666. },
  65667. set: function (value) {
  65668. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  65669. },
  65670. enumerable: true,
  65671. configurable: true
  65672. });
  65673. Xbox360Pad.prototype.update = function () {
  65674. _super.prototype.update.call(this);
  65675. if (this._isXboxOnePad) {
  65676. this.buttonA = this.browserGamepad.buttons[0].value;
  65677. this.buttonB = this.browserGamepad.buttons[1].value;
  65678. this.buttonX = this.browserGamepad.buttons[2].value;
  65679. this.buttonY = this.browserGamepad.buttons[3].value;
  65680. this.buttonLB = this.browserGamepad.buttons[4].value;
  65681. this.buttonRB = this.browserGamepad.buttons[5].value;
  65682. this.leftTrigger = this.browserGamepad.axes[2];
  65683. this.rightTrigger = this.browserGamepad.axes[5];
  65684. this.buttonBack = this.browserGamepad.buttons[9].value;
  65685. this.buttonStart = this.browserGamepad.buttons[8].value;
  65686. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  65687. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  65688. this.dPadUp = this.browserGamepad.buttons[11].value;
  65689. this.dPadDown = this.browserGamepad.buttons[12].value;
  65690. this.dPadLeft = this.browserGamepad.buttons[13].value;
  65691. this.dPadRight = this.browserGamepad.buttons[14].value;
  65692. }
  65693. else {
  65694. this.buttonA = this.browserGamepad.buttons[0].value;
  65695. this.buttonB = this.browserGamepad.buttons[1].value;
  65696. this.buttonX = this.browserGamepad.buttons[2].value;
  65697. this.buttonY = this.browserGamepad.buttons[3].value;
  65698. this.buttonLB = this.browserGamepad.buttons[4].value;
  65699. this.buttonRB = this.browserGamepad.buttons[5].value;
  65700. this.leftTrigger = this.browserGamepad.buttons[6].value;
  65701. this.rightTrigger = this.browserGamepad.buttons[7].value;
  65702. this.buttonBack = this.browserGamepad.buttons[8].value;
  65703. this.buttonStart = this.browserGamepad.buttons[9].value;
  65704. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  65705. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  65706. this.dPadUp = this.browserGamepad.buttons[12].value;
  65707. this.dPadDown = this.browserGamepad.buttons[13].value;
  65708. this.dPadLeft = this.browserGamepad.buttons[14].value;
  65709. this.dPadRight = this.browserGamepad.buttons[15].value;
  65710. }
  65711. };
  65712. Xbox360Pad.prototype.dispose = function () {
  65713. _super.prototype.dispose.call(this);
  65714. this.onButtonDownObservable.clear();
  65715. this.onButtonUpObservable.clear();
  65716. this.onPadDownObservable.clear();
  65717. this.onPadUpObservable.clear();
  65718. };
  65719. return Xbox360Pad;
  65720. }(BABYLON.Gamepad));
  65721. BABYLON.Xbox360Pad = Xbox360Pad;
  65722. })(BABYLON || (BABYLON = {}));
  65723. //# sourceMappingURL=babylon.xboxGamepad.js.map
  65724. var BABYLON;
  65725. (function (BABYLON) {
  65726. var PoseEnabledControllerType;
  65727. (function (PoseEnabledControllerType) {
  65728. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  65729. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  65730. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  65731. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  65732. /**
  65733. * Google Daydream
  65734. */
  65735. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  65736. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  65737. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  65738. var PoseEnabledControllerHelper = /** @class */ (function () {
  65739. function PoseEnabledControllerHelper() {
  65740. }
  65741. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  65742. // Oculus Touch
  65743. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  65744. return new BABYLON.OculusTouchController(vrGamepad);
  65745. }
  65746. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  65747. return new BABYLON.WindowsMotionController(vrGamepad);
  65748. }
  65749. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  65750. return new BABYLON.ViveController(vrGamepad);
  65751. }
  65752. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  65753. return new BABYLON.GearVRController(vrGamepad);
  65754. }
  65755. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  65756. return new BABYLON.DaydreamController(vrGamepad);
  65757. }
  65758. else {
  65759. return new BABYLON.GenericController(vrGamepad);
  65760. }
  65761. };
  65762. return PoseEnabledControllerHelper;
  65763. }());
  65764. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  65765. var PoseEnabledController = /** @class */ (function (_super) {
  65766. __extends(PoseEnabledController, _super);
  65767. function PoseEnabledController(browserGamepad) {
  65768. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  65769. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  65770. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  65771. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  65772. // Represents device position and rotation in babylon space
  65773. _this.devicePosition = BABYLON.Vector3.Zero();
  65774. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  65775. _this.deviceScaleFactor = 1;
  65776. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  65777. _this._deviceToWorld = BABYLON.Matrix.Identity();
  65778. /**
  65779. * Node to be used when casting a ray from the controller
  65780. */
  65781. _this._pointingPoseNode = null;
  65782. _this._workingMatrix = BABYLON.Matrix.Identity();
  65783. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  65784. _this.controllerType = PoseEnabledControllerType.GENERIC;
  65785. _this.position = BABYLON.Vector3.Zero();
  65786. _this.rotationQuaternion = new BABYLON.Quaternion();
  65787. _this._calculatedPosition = BABYLON.Vector3.Zero();
  65788. _this._calculatedRotation = new BABYLON.Quaternion();
  65789. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  65790. return _this;
  65791. }
  65792. PoseEnabledController.prototype.update = function () {
  65793. _super.prototype.update.call(this);
  65794. var pose = this.browserGamepad.pose;
  65795. this.updateFromDevice(pose);
  65796. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  65797. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  65798. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  65799. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  65800. if (this._mesh) {
  65801. this._mesh.position.copyFrom(this.devicePosition);
  65802. if (this._mesh.rotationQuaternion) {
  65803. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  65804. }
  65805. }
  65806. };
  65807. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  65808. if (poseData) {
  65809. this.rawPose = poseData;
  65810. if (poseData.position) {
  65811. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  65812. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  65813. this._deviceRoomPosition.z *= -1;
  65814. }
  65815. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  65816. this._calculatedPosition.addInPlace(this.position);
  65817. }
  65818. var pose = this.rawPose;
  65819. if (poseData.orientation && pose.orientation) {
  65820. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  65821. if (this._mesh) {
  65822. if (this._mesh.getScene().useRightHandedSystem) {
  65823. this._deviceRoomRotationQuaternion.z *= -1;
  65824. this._deviceRoomRotationQuaternion.w *= -1;
  65825. }
  65826. else {
  65827. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  65828. }
  65829. }
  65830. // if the camera is set, rotate to the camera's rotation
  65831. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  65832. }
  65833. }
  65834. };
  65835. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  65836. if (this._mesh) {
  65837. this._mesh.parent = null;
  65838. }
  65839. this._mesh = mesh;
  65840. if (this._poseControlledCamera) {
  65841. this._mesh.parent = this._poseControlledCamera;
  65842. }
  65843. if (!this._mesh.rotationQuaternion) {
  65844. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  65845. }
  65846. };
  65847. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  65848. this._poseControlledCamera = camera;
  65849. if (this._mesh) {
  65850. this._mesh.parent = this._poseControlledCamera;
  65851. }
  65852. };
  65853. PoseEnabledController.prototype.dispose = function () {
  65854. if (this._mesh) {
  65855. this._mesh.dispose();
  65856. }
  65857. this._mesh = null;
  65858. _super.prototype.dispose.call(this);
  65859. };
  65860. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  65861. get: function () {
  65862. return this._mesh;
  65863. },
  65864. enumerable: true,
  65865. configurable: true
  65866. });
  65867. PoseEnabledController.prototype.getForwardRay = function (length) {
  65868. if (length === void 0) { length = 100; }
  65869. if (!this.mesh) {
  65870. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  65871. }
  65872. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  65873. var origin = m.getTranslation();
  65874. var forward = new BABYLON.Vector3(0, 0, -1);
  65875. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65876. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65877. return new BABYLON.Ray(origin, direction, length);
  65878. };
  65879. /**
  65880. * Name of the child mesh that can be used to cast a ray from the controller
  65881. */
  65882. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  65883. return PoseEnabledController;
  65884. }(BABYLON.Gamepad));
  65885. BABYLON.PoseEnabledController = PoseEnabledController;
  65886. })(BABYLON || (BABYLON = {}));
  65887. //# sourceMappingURL=babylon.poseEnabledController.js.map
  65888. var BABYLON;
  65889. (function (BABYLON) {
  65890. var WebVRController = /** @class */ (function (_super) {
  65891. __extends(WebVRController, _super);
  65892. function WebVRController(vrGamepad) {
  65893. var _this = _super.call(this, vrGamepad) || this;
  65894. // Observables
  65895. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  65896. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  65897. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  65898. _this.onPadStateChangedObservable = new BABYLON.Observable();
  65899. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  65900. _this.pad = { x: 0, y: 0 };
  65901. // avoid GC, store state in a tmp object
  65902. _this._changes = {
  65903. pressChanged: false,
  65904. touchChanged: false,
  65905. valueChanged: false,
  65906. changed: false
  65907. };
  65908. _this._buttons = new Array(vrGamepad.buttons.length);
  65909. _this.hand = vrGamepad.hand;
  65910. return _this;
  65911. }
  65912. WebVRController.prototype.onButtonStateChange = function (callback) {
  65913. this._onButtonStateChange = callback;
  65914. };
  65915. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  65916. get: function () {
  65917. return this._defaultModel;
  65918. },
  65919. enumerable: true,
  65920. configurable: true
  65921. });
  65922. WebVRController.prototype.update = function () {
  65923. _super.prototype.update.call(this);
  65924. for (var index = 0; index < this._buttons.length; index++) {
  65925. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  65926. }
  65927. ;
  65928. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  65929. this.pad.x = this.leftStick.x;
  65930. this.pad.y = this.leftStick.y;
  65931. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  65932. }
  65933. };
  65934. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  65935. if (!newState) {
  65936. newState = {
  65937. pressed: false,
  65938. touched: false,
  65939. value: 0
  65940. };
  65941. }
  65942. if (!currentState) {
  65943. this._buttons[buttonIndex] = {
  65944. pressed: newState.pressed,
  65945. touched: newState.touched,
  65946. value: newState.value
  65947. };
  65948. return;
  65949. }
  65950. this._checkChanges(newState, currentState);
  65951. if (this._changes.changed) {
  65952. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  65953. this._handleButtonChange(buttonIndex, newState, this._changes);
  65954. }
  65955. this._buttons[buttonIndex].pressed = newState.pressed;
  65956. this._buttons[buttonIndex].touched = newState.touched;
  65957. // oculus triggers are never 0, thou not touched.
  65958. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  65959. };
  65960. WebVRController.prototype._checkChanges = function (newState, currentState) {
  65961. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  65962. this._changes.touchChanged = newState.touched !== currentState.touched;
  65963. this._changes.valueChanged = newState.value !== currentState.value;
  65964. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  65965. return this._changes;
  65966. };
  65967. WebVRController.prototype.dispose = function () {
  65968. _super.prototype.dispose.call(this);
  65969. this.onTriggerStateChangedObservable.clear();
  65970. this.onMainButtonStateChangedObservable.clear();
  65971. this.onSecondaryButtonStateChangedObservable.clear();
  65972. this.onPadStateChangedObservable.clear();
  65973. this.onPadValuesChangedObservable.clear();
  65974. };
  65975. return WebVRController;
  65976. }(BABYLON.PoseEnabledController));
  65977. BABYLON.WebVRController = WebVRController;
  65978. })(BABYLON || (BABYLON = {}));
  65979. //# sourceMappingURL=babylon.webVRController.js.map
  65980. var BABYLON;
  65981. (function (BABYLON) {
  65982. var OculusTouchController = /** @class */ (function (_super) {
  65983. __extends(OculusTouchController, _super);
  65984. function OculusTouchController(vrGamepad) {
  65985. var _this = _super.call(this, vrGamepad) || this;
  65986. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  65987. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  65988. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  65989. return _this;
  65990. }
  65991. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65992. var _this = this;
  65993. var meshName;
  65994. // Hand
  65995. if (this.hand === 'left') {
  65996. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  65997. }
  65998. else {
  65999. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  66000. }
  66001. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  66002. /*
  66003. Parent Mesh name: oculus_touch_left
  66004. - body
  66005. - trigger
  66006. - thumbstick
  66007. - grip
  66008. - button_y
  66009. - button_x
  66010. - button_enter
  66011. */
  66012. _this._defaultModel = newMeshes[1];
  66013. _this.attachToMesh(_this._defaultModel);
  66014. if (meshLoaded) {
  66015. meshLoaded(_this._defaultModel);
  66016. }
  66017. });
  66018. };
  66019. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  66020. // helper getters for left and right hand.
  66021. get: function () {
  66022. if (this.hand === 'right') {
  66023. return this.onMainButtonStateChangedObservable;
  66024. }
  66025. else {
  66026. throw new Error('No A button on left hand');
  66027. }
  66028. },
  66029. enumerable: true,
  66030. configurable: true
  66031. });
  66032. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  66033. get: function () {
  66034. if (this.hand === 'right') {
  66035. return this.onSecondaryButtonStateChangedObservable;
  66036. }
  66037. else {
  66038. throw new Error('No B button on left hand');
  66039. }
  66040. },
  66041. enumerable: true,
  66042. configurable: true
  66043. });
  66044. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  66045. get: function () {
  66046. if (this.hand === 'left') {
  66047. return this.onMainButtonStateChangedObservable;
  66048. }
  66049. else {
  66050. throw new Error('No X button on right hand');
  66051. }
  66052. },
  66053. enumerable: true,
  66054. configurable: true
  66055. });
  66056. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  66057. get: function () {
  66058. if (this.hand === 'left') {
  66059. return this.onSecondaryButtonStateChangedObservable;
  66060. }
  66061. else {
  66062. throw new Error('No Y button on right hand');
  66063. }
  66064. },
  66065. enumerable: true,
  66066. configurable: true
  66067. });
  66068. /*
  66069. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  66070. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  66071. 2) secondary trigger (same)
  66072. 3) A (right) X (left), touch, pressed = value
  66073. 4) B / Y
  66074. 5) thumb rest
  66075. */
  66076. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66077. var notifyObject = state; //{ state: state, changes: changes };
  66078. var triggerDirection = this.hand === 'right' ? -1 : 1;
  66079. switch (buttonIdx) {
  66080. case 0:
  66081. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66082. return;
  66083. case 1:// index trigger
  66084. if (this._defaultModel) {
  66085. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  66086. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  66087. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  66088. }
  66089. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66090. return;
  66091. case 2:// secondary trigger
  66092. if (this._defaultModel) {
  66093. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  66094. }
  66095. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  66096. return;
  66097. case 3:
  66098. if (this._defaultModel) {
  66099. if (notifyObject.pressed) {
  66100. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  66101. }
  66102. else {
  66103. (this._defaultModel.getChildren()[1]).position.y = 0;
  66104. }
  66105. }
  66106. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  66107. return;
  66108. case 4:
  66109. if (this._defaultModel) {
  66110. if (notifyObject.pressed) {
  66111. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  66112. }
  66113. else {
  66114. (this._defaultModel.getChildren()[2]).position.y = 0;
  66115. }
  66116. }
  66117. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  66118. return;
  66119. case 5:
  66120. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  66121. return;
  66122. }
  66123. };
  66124. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  66125. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  66126. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  66127. return OculusTouchController;
  66128. }(BABYLON.WebVRController));
  66129. BABYLON.OculusTouchController = OculusTouchController;
  66130. })(BABYLON || (BABYLON = {}));
  66131. //# sourceMappingURL=babylon.oculusTouchController.js.map
  66132. var BABYLON;
  66133. (function (BABYLON) {
  66134. var ViveController = /** @class */ (function (_super) {
  66135. __extends(ViveController, _super);
  66136. function ViveController(vrGamepad) {
  66137. var _this = _super.call(this, vrGamepad) || this;
  66138. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  66139. _this._invertLeftStickY = true;
  66140. return _this;
  66141. }
  66142. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66143. var _this = this;
  66144. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  66145. /*
  66146. Parent Mesh name: ViveWand
  66147. - body
  66148. - r_gripper
  66149. - l_gripper
  66150. - menu_button
  66151. - system_button
  66152. - trackpad
  66153. - trigger
  66154. - LED
  66155. */
  66156. _this._defaultModel = newMeshes[1];
  66157. _this.attachToMesh(_this._defaultModel);
  66158. if (meshLoaded) {
  66159. meshLoaded(_this._defaultModel);
  66160. }
  66161. });
  66162. };
  66163. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  66164. get: function () {
  66165. return this.onMainButtonStateChangedObservable;
  66166. },
  66167. enumerable: true,
  66168. configurable: true
  66169. });
  66170. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  66171. get: function () {
  66172. return this.onMainButtonStateChangedObservable;
  66173. },
  66174. enumerable: true,
  66175. configurable: true
  66176. });
  66177. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  66178. get: function () {
  66179. return this.onSecondaryButtonStateChangedObservable;
  66180. },
  66181. enumerable: true,
  66182. configurable: true
  66183. });
  66184. /**
  66185. * Vive mapping:
  66186. * 0: touchpad
  66187. * 1: trigger
  66188. * 2: left AND right buttons
  66189. * 3: menu button
  66190. */
  66191. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66192. var notifyObject = state; //{ state: state, changes: changes };
  66193. switch (buttonIdx) {
  66194. case 0:
  66195. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66196. return;
  66197. case 1:// index trigger
  66198. if (this._defaultModel) {
  66199. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  66200. }
  66201. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66202. return;
  66203. case 2:// left AND right button
  66204. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  66205. return;
  66206. case 3:
  66207. if (this._defaultModel) {
  66208. if (notifyObject.pressed) {
  66209. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  66210. }
  66211. else {
  66212. (this._defaultModel.getChildren()[2]).position.y = 0;
  66213. }
  66214. }
  66215. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  66216. return;
  66217. }
  66218. };
  66219. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  66220. ViveController.MODEL_FILENAME = 'wand.babylon';
  66221. return ViveController;
  66222. }(BABYLON.WebVRController));
  66223. BABYLON.ViveController = ViveController;
  66224. })(BABYLON || (BABYLON = {}));
  66225. //# sourceMappingURL=babylon.viveController.js.map
  66226. var BABYLON;
  66227. (function (BABYLON) {
  66228. var GenericController = /** @class */ (function (_super) {
  66229. __extends(GenericController, _super);
  66230. function GenericController(vrGamepad) {
  66231. return _super.call(this, vrGamepad) || this;
  66232. }
  66233. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66234. var _this = this;
  66235. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  66236. _this._defaultModel = newMeshes[1];
  66237. _this.attachToMesh(_this._defaultModel);
  66238. if (meshLoaded) {
  66239. meshLoaded(_this._defaultModel);
  66240. }
  66241. });
  66242. };
  66243. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66244. console.log("Button id: " + buttonIdx + "state: ");
  66245. console.dir(state);
  66246. };
  66247. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66248. GenericController.MODEL_FILENAME = 'generic.babylon';
  66249. return GenericController;
  66250. }(BABYLON.WebVRController));
  66251. BABYLON.GenericController = GenericController;
  66252. })(BABYLON || (BABYLON = {}));
  66253. //# sourceMappingURL=babylon.genericController.js.map
  66254. var BABYLON;
  66255. (function (BABYLON) {
  66256. var LoadedMeshInfo = /** @class */ (function () {
  66257. function LoadedMeshInfo() {
  66258. this.buttonMeshes = {};
  66259. this.axisMeshes = {};
  66260. }
  66261. return LoadedMeshInfo;
  66262. }());
  66263. var WindowsMotionController = /** @class */ (function (_super) {
  66264. __extends(WindowsMotionController, _super);
  66265. function WindowsMotionController(vrGamepad) {
  66266. var _this = _super.call(this, vrGamepad) || this;
  66267. _this._mapping = {
  66268. // Semantic button names
  66269. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  66270. // A mapping of the button name to glTF model node name
  66271. // that should be transformed by button value.
  66272. buttonMeshNames: {
  66273. 'trigger': 'SELECT',
  66274. 'menu': 'MENU',
  66275. 'grip': 'GRASP',
  66276. 'thumbstick': 'THUMBSTICK_PRESS',
  66277. 'trackpad': 'TOUCHPAD_PRESS'
  66278. },
  66279. // This mapping is used to translate from the Motion Controller to Babylon semantics
  66280. buttonObservableNames: {
  66281. 'trigger': 'onTriggerStateChangedObservable',
  66282. 'menu': 'onSecondaryButtonStateChangedObservable',
  66283. 'grip': 'onMainButtonStateChangedObservable',
  66284. 'thumbstick': 'onPadStateChangedObservable',
  66285. 'trackpad': 'onTrackpadChangedObservable'
  66286. },
  66287. // A mapping of the axis name to glTF model node name
  66288. // that should be transformed by axis value.
  66289. // This array mirrors the browserGamepad.axes array, such that
  66290. // the mesh corresponding to axis 0 is in this array index 0.
  66291. axisMeshNames: [
  66292. 'THUMBSTICK_X',
  66293. 'THUMBSTICK_Y',
  66294. 'TOUCHPAD_TOUCH_X',
  66295. 'TOUCHPAD_TOUCH_Y'
  66296. ],
  66297. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  66298. };
  66299. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  66300. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  66301. _this.trackpad = { x: 0, y: 0 };
  66302. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  66303. _this._loadedMeshInfo = null;
  66304. return _this;
  66305. }
  66306. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  66307. get: function () {
  66308. return this.onTriggerStateChangedObservable;
  66309. },
  66310. enumerable: true,
  66311. configurable: true
  66312. });
  66313. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  66314. get: function () {
  66315. return this.onSecondaryButtonStateChangedObservable;
  66316. },
  66317. enumerable: true,
  66318. configurable: true
  66319. });
  66320. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  66321. get: function () {
  66322. return this.onMainButtonStateChangedObservable;
  66323. },
  66324. enumerable: true,
  66325. configurable: true
  66326. });
  66327. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  66328. get: function () {
  66329. return this.onPadStateChangedObservable;
  66330. },
  66331. enumerable: true,
  66332. configurable: true
  66333. });
  66334. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  66335. get: function () {
  66336. return this.onTrackpadChangedObservable;
  66337. },
  66338. enumerable: true,
  66339. configurable: true
  66340. });
  66341. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  66342. get: function () {
  66343. return this.onTrackpadValuesChangedObservable;
  66344. },
  66345. enumerable: true,
  66346. configurable: true
  66347. });
  66348. /**
  66349. * Called once per frame by the engine.
  66350. */
  66351. WindowsMotionController.prototype.update = function () {
  66352. _super.prototype.update.call(this);
  66353. if (this.browserGamepad.axes) {
  66354. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  66355. this.trackpad.x = this.browserGamepad["axes"][2];
  66356. this.trackpad.y = this.browserGamepad["axes"][3];
  66357. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  66358. }
  66359. // Only need to animate axes if there is a loaded mesh
  66360. if (this._loadedMeshInfo) {
  66361. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  66362. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  66363. }
  66364. }
  66365. }
  66366. };
  66367. /**
  66368. * Called once for each button that changed state since the last frame
  66369. * @param buttonIdx Which button index changed
  66370. * @param state New state of the button
  66371. * @param changes Which properties on the state changed since last frame
  66372. */
  66373. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66374. var buttonName = this._mapping.buttons[buttonIdx];
  66375. if (!buttonName) {
  66376. return;
  66377. }
  66378. // Only emit events for buttons that we know how to map from index to name
  66379. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  66380. if (observable) {
  66381. observable.notifyObservers(state);
  66382. }
  66383. this.lerpButtonTransform(buttonName, state.value);
  66384. };
  66385. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  66386. // If there is no loaded mesh, there is nothing to transform.
  66387. if (!this._loadedMeshInfo) {
  66388. return;
  66389. }
  66390. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  66391. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66392. return;
  66393. }
  66394. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  66395. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  66396. };
  66397. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  66398. if (!this._loadedMeshInfo) {
  66399. return;
  66400. }
  66401. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  66402. if (!meshInfo) {
  66403. return;
  66404. }
  66405. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66406. return;
  66407. }
  66408. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  66409. var lerpValue = axisValue * 0.5 + 0.5;
  66410. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  66411. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  66412. };
  66413. /**
  66414. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  66415. * @param scene scene in which to add meshes
  66416. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  66417. */
  66418. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  66419. var _this = this;
  66420. if (forceDefault === void 0) { forceDefault = false; }
  66421. var path;
  66422. var filename;
  66423. // Checking if GLB loader is present
  66424. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  66425. // Determine the device specific folder based on the ID suffix
  66426. var device = 'default';
  66427. if (this.id && !forceDefault) {
  66428. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  66429. device = ((match && match[0]) || device);
  66430. }
  66431. // Hand
  66432. if (this.hand === 'left') {
  66433. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  66434. }
  66435. else {
  66436. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  66437. }
  66438. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  66439. }
  66440. else {
  66441. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  66442. path = BABYLON.GenericController.MODEL_BASE_URL;
  66443. filename = BABYLON.GenericController.MODEL_FILENAME;
  66444. }
  66445. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  66446. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  66447. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  66448. if (!_this._loadedMeshInfo) {
  66449. return;
  66450. }
  66451. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  66452. _this.attachToMesh(_this._defaultModel);
  66453. if (meshLoaded) {
  66454. meshLoaded(_this._defaultModel);
  66455. }
  66456. }, null, function (scene, message) {
  66457. BABYLON.Tools.Log(message);
  66458. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  66459. if (!forceDefault) {
  66460. _this.initControllerMesh(scene, meshLoaded, true);
  66461. }
  66462. });
  66463. };
  66464. /**
  66465. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  66466. * can be transformed by button presses and axes values, based on this._mapping.
  66467. *
  66468. * @param scene scene in which the meshes exist
  66469. * @param meshes list of meshes that make up the controller model to process
  66470. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  66471. */
  66472. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  66473. var loadedMeshInfo = null;
  66474. // Create a new mesh to contain the glTF hierarchy
  66475. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  66476. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  66477. var childMesh = null;
  66478. for (var i = 0; i < meshes.length; i++) {
  66479. var mesh = meshes[i];
  66480. if (!mesh.parent) {
  66481. // Exclude controller meshes from picking results
  66482. mesh.isPickable = false;
  66483. // Handle root node, attach to the new parentMesh
  66484. childMesh = mesh;
  66485. break;
  66486. }
  66487. }
  66488. if (childMesh) {
  66489. childMesh.setParent(parentMesh);
  66490. // Create our mesh info. Note that this method will always return non-null.
  66491. loadedMeshInfo = this.createMeshInfo(parentMesh);
  66492. }
  66493. else {
  66494. BABYLON.Tools.Warn('Could not find root node in model file.');
  66495. }
  66496. return loadedMeshInfo;
  66497. };
  66498. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  66499. var loadedMeshInfo = new LoadedMeshInfo();
  66500. var i;
  66501. loadedMeshInfo.rootNode = rootNode;
  66502. // Reset the caches
  66503. loadedMeshInfo.buttonMeshes = {};
  66504. loadedMeshInfo.axisMeshes = {};
  66505. // Button Meshes
  66506. for (i = 0; i < this._mapping.buttons.length; i++) {
  66507. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  66508. if (!buttonMeshName) {
  66509. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  66510. continue;
  66511. }
  66512. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  66513. if (!buttonMesh) {
  66514. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  66515. continue;
  66516. }
  66517. var buttonMeshInfo = {
  66518. index: i,
  66519. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  66520. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  66521. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  66522. };
  66523. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  66524. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  66525. }
  66526. else {
  66527. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  66528. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  66529. '(VALUE: ' + !!buttonMeshInfo.value +
  66530. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  66531. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  66532. ')');
  66533. }
  66534. }
  66535. // Axis Meshes
  66536. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  66537. var axisMeshName = this._mapping.axisMeshNames[i];
  66538. if (!axisMeshName) {
  66539. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  66540. continue;
  66541. }
  66542. var axisMesh = getChildByName(rootNode, axisMeshName);
  66543. if (!axisMesh) {
  66544. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  66545. continue;
  66546. }
  66547. var axisMeshInfo = {
  66548. index: i,
  66549. value: getImmediateChildByName(axisMesh, 'VALUE'),
  66550. min: getImmediateChildByName(axisMesh, 'MIN'),
  66551. max: getImmediateChildByName(axisMesh, 'MAX')
  66552. };
  66553. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  66554. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  66555. }
  66556. else {
  66557. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  66558. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  66559. '(VALUE: ' + !!axisMeshInfo.value +
  66560. ', MIN: ' + !!axisMeshInfo.min +
  66561. ', MAX:' + !!axisMeshInfo.max +
  66562. ')');
  66563. }
  66564. }
  66565. // Pointing Ray
  66566. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  66567. if (!loadedMeshInfo.pointingPoseNode) {
  66568. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  66569. }
  66570. return loadedMeshInfo;
  66571. // Look through all children recursively. This will return null if no mesh exists with the given name.
  66572. function getChildByName(node, name) {
  66573. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  66574. }
  66575. // Look through only immediate children. This will return null if no mesh exists with the given name.
  66576. function getImmediateChildByName(node, name) {
  66577. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  66578. }
  66579. };
  66580. WindowsMotionController.prototype.getForwardRay = function (length) {
  66581. if (length === void 0) { length = 100; }
  66582. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  66583. return _super.prototype.getForwardRay.call(this, length);
  66584. }
  66585. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  66586. var origin = m.getTranslation();
  66587. var forward = new BABYLON.Vector3(0, 0, -1);
  66588. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66589. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66590. return new BABYLON.Ray(origin, direction, length);
  66591. };
  66592. WindowsMotionController.prototype.dispose = function () {
  66593. _super.prototype.dispose.call(this);
  66594. this.onTrackpadChangedObservable.clear();
  66595. };
  66596. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  66597. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  66598. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  66599. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  66600. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  66601. return WindowsMotionController;
  66602. }(BABYLON.WebVRController));
  66603. BABYLON.WindowsMotionController = WindowsMotionController;
  66604. })(BABYLON || (BABYLON = {}));
  66605. //# sourceMappingURL=babylon.windowsMotionController.js.map
  66606. var BABYLON;
  66607. (function (BABYLON) {
  66608. var GearVRController = /** @class */ (function (_super) {
  66609. __extends(GearVRController, _super);
  66610. function GearVRController(vrGamepad) {
  66611. var _this = _super.call(this, vrGamepad) || this;
  66612. _this._buttonIndexToObservableNameMap = [
  66613. 'onTrackpadChangedObservable',
  66614. 'onTriggerStateChangedObservable' // Trigger
  66615. ];
  66616. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  66617. return _this;
  66618. }
  66619. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66620. var _this = this;
  66621. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  66622. _this._defaultModel = newMeshes[1];
  66623. _this.attachToMesh(_this._defaultModel);
  66624. if (meshLoaded) {
  66625. meshLoaded(_this._defaultModel);
  66626. }
  66627. });
  66628. };
  66629. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66630. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  66631. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  66632. // Only emit events for buttons that we know how to map from index to observable
  66633. var observable = this[observableName];
  66634. if (observable) {
  66635. observable.notifyObservers(state);
  66636. }
  66637. }
  66638. };
  66639. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66640. GearVRController.MODEL_FILENAME = 'generic.babylon';
  66641. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  66642. return GearVRController;
  66643. }(BABYLON.WebVRController));
  66644. BABYLON.GearVRController = GearVRController;
  66645. })(BABYLON || (BABYLON = {}));
  66646. //# sourceMappingURL=babylon.gearVRController.js.map
  66647. var BABYLON;
  66648. (function (BABYLON) {
  66649. /**
  66650. * Google Daydream controller
  66651. */
  66652. var DaydreamController = /** @class */ (function (_super) {
  66653. __extends(DaydreamController, _super);
  66654. function DaydreamController(vrGamepad) {
  66655. var _this = _super.call(this, vrGamepad) || this;
  66656. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  66657. return _this;
  66658. }
  66659. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66660. var _this = this;
  66661. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  66662. _this._defaultModel = newMeshes[1];
  66663. _this.attachToMesh(_this._defaultModel);
  66664. if (meshLoaded) {
  66665. meshLoaded(_this._defaultModel);
  66666. }
  66667. });
  66668. };
  66669. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66670. // Daydream controller only has 1 GamepadButton (on the trackpad).
  66671. if (buttonIdx === 0) {
  66672. var observable = this.onTriggerStateChangedObservable;
  66673. if (observable) {
  66674. observable.notifyObservers(state);
  66675. }
  66676. }
  66677. else {
  66678. // If the app or home buttons are ever made available
  66679. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  66680. }
  66681. };
  66682. /**
  66683. * Base Url for the controller model.
  66684. */
  66685. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66686. /**
  66687. * File name for the controller model.
  66688. */
  66689. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  66690. /**
  66691. * Gamepad Id prefix used to identify Daydream Controller.
  66692. */
  66693. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  66694. return DaydreamController;
  66695. }(BABYLON.WebVRController));
  66696. BABYLON.DaydreamController = DaydreamController;
  66697. })(BABYLON || (BABYLON = {}));
  66698. //# sourceMappingURL=babylon.daydreamController.js.map
  66699. var BABYLON;
  66700. (function (BABYLON) {
  66701. var FollowCamera = /** @class */ (function (_super) {
  66702. __extends(FollowCamera, _super);
  66703. function FollowCamera(name, position, scene, lockedTarget) {
  66704. if (lockedTarget === void 0) { lockedTarget = null; }
  66705. var _this = _super.call(this, name, position, scene) || this;
  66706. _this.radius = 12;
  66707. _this.rotationOffset = 0;
  66708. _this.heightOffset = 4;
  66709. _this.cameraAcceleration = 0.05;
  66710. _this.maxCameraSpeed = 20;
  66711. _this.lockedTarget = lockedTarget;
  66712. return _this;
  66713. }
  66714. FollowCamera.prototype.getRadians = function (degrees) {
  66715. return degrees * Math.PI / 180;
  66716. };
  66717. FollowCamera.prototype.follow = function (cameraTarget) {
  66718. if (!cameraTarget)
  66719. return;
  66720. var yRotation;
  66721. if (cameraTarget.rotationQuaternion) {
  66722. var rotMatrix = new BABYLON.Matrix();
  66723. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  66724. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  66725. }
  66726. else {
  66727. yRotation = cameraTarget.rotation.y;
  66728. }
  66729. var radians = this.getRadians(this.rotationOffset) + yRotation;
  66730. var targetPosition = cameraTarget.getAbsolutePosition();
  66731. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  66732. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  66733. var dx = targetX - this.position.x;
  66734. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  66735. var dz = (targetZ) - this.position.z;
  66736. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  66737. var vy = dy * this.cameraAcceleration;
  66738. var vz = dz * this.cameraAcceleration * 2;
  66739. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  66740. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66741. }
  66742. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  66743. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66744. }
  66745. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  66746. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66747. }
  66748. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  66749. this.setTarget(targetPosition);
  66750. };
  66751. FollowCamera.prototype._checkInputs = function () {
  66752. _super.prototype._checkInputs.call(this);
  66753. if (this.lockedTarget) {
  66754. this.follow(this.lockedTarget);
  66755. }
  66756. };
  66757. FollowCamera.prototype.getClassName = function () {
  66758. return "FollowCamera";
  66759. };
  66760. __decorate([
  66761. BABYLON.serialize()
  66762. ], FollowCamera.prototype, "radius", void 0);
  66763. __decorate([
  66764. BABYLON.serialize()
  66765. ], FollowCamera.prototype, "rotationOffset", void 0);
  66766. __decorate([
  66767. BABYLON.serialize()
  66768. ], FollowCamera.prototype, "heightOffset", void 0);
  66769. __decorate([
  66770. BABYLON.serialize()
  66771. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  66772. __decorate([
  66773. BABYLON.serialize()
  66774. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  66775. __decorate([
  66776. BABYLON.serializeAsMeshReference("lockedTargetId")
  66777. ], FollowCamera.prototype, "lockedTarget", void 0);
  66778. return FollowCamera;
  66779. }(BABYLON.TargetCamera));
  66780. BABYLON.FollowCamera = FollowCamera;
  66781. var ArcFollowCamera = /** @class */ (function (_super) {
  66782. __extends(ArcFollowCamera, _super);
  66783. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  66784. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  66785. _this.alpha = alpha;
  66786. _this.beta = beta;
  66787. _this.radius = radius;
  66788. _this.target = target;
  66789. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  66790. _this.follow();
  66791. return _this;
  66792. }
  66793. ArcFollowCamera.prototype.follow = function () {
  66794. if (!this.target) {
  66795. return;
  66796. }
  66797. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  66798. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  66799. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  66800. var targetPosition = this.target.getAbsolutePosition();
  66801. this.position = targetPosition.add(this._cartesianCoordinates);
  66802. this.setTarget(targetPosition);
  66803. };
  66804. ArcFollowCamera.prototype._checkInputs = function () {
  66805. _super.prototype._checkInputs.call(this);
  66806. this.follow();
  66807. };
  66808. ArcFollowCamera.prototype.getClassName = function () {
  66809. return "ArcFollowCamera";
  66810. };
  66811. return ArcFollowCamera;
  66812. }(BABYLON.TargetCamera));
  66813. BABYLON.ArcFollowCamera = ArcFollowCamera;
  66814. })(BABYLON || (BABYLON = {}));
  66815. //# sourceMappingURL=babylon.followCamera.js.map
  66816. var BABYLON;
  66817. (function (BABYLON) {
  66818. // We're mainly based on the logic defined into the FreeCamera code
  66819. var UniversalCamera = /** @class */ (function (_super) {
  66820. __extends(UniversalCamera, _super);
  66821. //-- end properties for backward compatibility for inputs
  66822. function UniversalCamera(name, position, scene) {
  66823. var _this = _super.call(this, name, position, scene) || this;
  66824. _this.inputs.addGamepad();
  66825. return _this;
  66826. }
  66827. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  66828. //-- Begin properties for backward compatibility for inputs
  66829. get: function () {
  66830. var gamepad = this.inputs.attached["gamepad"];
  66831. if (gamepad)
  66832. return gamepad.gamepadAngularSensibility;
  66833. return 0;
  66834. },
  66835. set: function (value) {
  66836. var gamepad = this.inputs.attached["gamepad"];
  66837. if (gamepad)
  66838. gamepad.gamepadAngularSensibility = value;
  66839. },
  66840. enumerable: true,
  66841. configurable: true
  66842. });
  66843. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  66844. get: function () {
  66845. var gamepad = this.inputs.attached["gamepad"];
  66846. if (gamepad)
  66847. return gamepad.gamepadMoveSensibility;
  66848. return 0;
  66849. },
  66850. set: function (value) {
  66851. var gamepad = this.inputs.attached["gamepad"];
  66852. if (gamepad)
  66853. gamepad.gamepadMoveSensibility = value;
  66854. },
  66855. enumerable: true,
  66856. configurable: true
  66857. });
  66858. UniversalCamera.prototype.getClassName = function () {
  66859. return "UniversalCamera";
  66860. };
  66861. return UniversalCamera;
  66862. }(BABYLON.TouchCamera));
  66863. BABYLON.UniversalCamera = UniversalCamera;
  66864. })(BABYLON || (BABYLON = {}));
  66865. //# sourceMappingURL=babylon.universalCamera.js.map
  66866. var BABYLON;
  66867. (function (BABYLON) {
  66868. // We're mainly based on the logic defined into the FreeCamera code
  66869. var GamepadCamera = /** @class */ (function (_super) {
  66870. __extends(GamepadCamera, _super);
  66871. //-- end properties for backward compatibility for inputs
  66872. function GamepadCamera(name, position, scene) {
  66873. return _super.call(this, name, position, scene) || this;
  66874. }
  66875. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  66876. //-- Begin properties for backward compatibility for inputs
  66877. get: function () {
  66878. var gamepad = this.inputs.attached["gamepad"];
  66879. if (gamepad)
  66880. return gamepad.gamepadAngularSensibility;
  66881. return 0;
  66882. },
  66883. set: function (value) {
  66884. var gamepad = this.inputs.attached["gamepad"];
  66885. if (gamepad)
  66886. gamepad.gamepadAngularSensibility = value;
  66887. },
  66888. enumerable: true,
  66889. configurable: true
  66890. });
  66891. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  66892. get: function () {
  66893. var gamepad = this.inputs.attached["gamepad"];
  66894. if (gamepad)
  66895. return gamepad.gamepadMoveSensibility;
  66896. return 0;
  66897. },
  66898. set: function (value) {
  66899. var gamepad = this.inputs.attached["gamepad"];
  66900. if (gamepad)
  66901. gamepad.gamepadMoveSensibility = value;
  66902. },
  66903. enumerable: true,
  66904. configurable: true
  66905. });
  66906. GamepadCamera.prototype.getClassName = function () {
  66907. return "GamepadCamera";
  66908. };
  66909. return GamepadCamera;
  66910. }(BABYLON.UniversalCamera));
  66911. BABYLON.GamepadCamera = GamepadCamera;
  66912. })(BABYLON || (BABYLON = {}));
  66913. //# sourceMappingURL=babylon.gamepadCamera.js.map
  66914. var BABYLON;
  66915. (function (BABYLON) {
  66916. var PostProcessRenderPipelineManager = /** @class */ (function () {
  66917. function PostProcessRenderPipelineManager() {
  66918. this._renderPipelines = {};
  66919. }
  66920. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  66921. this._renderPipelines[renderPipeline._name] = renderPipeline;
  66922. };
  66923. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  66924. if (unique === void 0) { unique = false; }
  66925. var renderPipeline = this._renderPipelines[renderPipelineName];
  66926. if (!renderPipeline) {
  66927. return;
  66928. }
  66929. renderPipeline._attachCameras(cameras, unique);
  66930. };
  66931. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  66932. var renderPipeline = this._renderPipelines[renderPipelineName];
  66933. if (!renderPipeline) {
  66934. return;
  66935. }
  66936. renderPipeline._detachCameras(cameras);
  66937. };
  66938. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66939. var renderPipeline = this._renderPipelines[renderPipelineName];
  66940. if (!renderPipeline) {
  66941. return;
  66942. }
  66943. renderPipeline._enableEffect(renderEffectName, cameras);
  66944. };
  66945. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66946. var renderPipeline = this._renderPipelines[renderPipelineName];
  66947. if (!renderPipeline) {
  66948. return;
  66949. }
  66950. renderPipeline._disableEffect(renderEffectName, cameras);
  66951. };
  66952. PostProcessRenderPipelineManager.prototype.update = function () {
  66953. for (var renderPipelineName in this._renderPipelines) {
  66954. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66955. var pipeline = this._renderPipelines[renderPipelineName];
  66956. if (!pipeline.isSupported) {
  66957. pipeline.dispose();
  66958. delete this._renderPipelines[renderPipelineName];
  66959. }
  66960. else {
  66961. pipeline._update();
  66962. }
  66963. }
  66964. }
  66965. };
  66966. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  66967. for (var renderPipelineName in this._renderPipelines) {
  66968. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66969. var pipeline = this._renderPipelines[renderPipelineName];
  66970. pipeline._rebuild();
  66971. }
  66972. }
  66973. };
  66974. PostProcessRenderPipelineManager.prototype.dispose = function () {
  66975. for (var renderPipelineName in this._renderPipelines) {
  66976. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66977. var pipeline = this._renderPipelines[renderPipelineName];
  66978. pipeline.dispose();
  66979. }
  66980. }
  66981. };
  66982. return PostProcessRenderPipelineManager;
  66983. }());
  66984. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  66985. })(BABYLON || (BABYLON = {}));
  66986. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  66987. var BABYLON;
  66988. (function (BABYLON) {
  66989. /**
  66990. * This represents a set of one or more post processes in Babylon.
  66991. * A post process can be used to apply a shader to a texture after it is rendered.
  66992. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  66993. */
  66994. var PostProcessRenderEffect = /** @class */ (function () {
  66995. /**
  66996. * Instantiates a post process render effect.
  66997. * A post process can be used to apply a shader to a texture after it is rendered.
  66998. * @param engine The engine the effect is tied to
  66999. * @param name The name of the effect
  67000. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  67001. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  67002. */
  67003. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  67004. this._name = name;
  67005. this._singleInstance = singleInstance || true;
  67006. this._getPostProcesses = getPostProcesses;
  67007. this._cameras = {};
  67008. this._indicesForCamera = {};
  67009. this._postProcesses = {};
  67010. }
  67011. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  67012. /**
  67013. * Checks if all the post processes in the effect are supported.
  67014. */
  67015. get: function () {
  67016. for (var index in this._postProcesses) {
  67017. for (var ppIndex in this._postProcesses[index]) {
  67018. if (!this._postProcesses[index][ppIndex].isSupported) {
  67019. return false;
  67020. }
  67021. }
  67022. }
  67023. return true;
  67024. },
  67025. enumerable: true,
  67026. configurable: true
  67027. });
  67028. /**
  67029. * Updates the current state of the effect
  67030. */
  67031. PostProcessRenderEffect.prototype._update = function () {
  67032. };
  67033. /**
  67034. * Attaches the effect on cameras
  67035. * @param cameras The camera to attach to.
  67036. */
  67037. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  67038. var _this = this;
  67039. var cameraKey;
  67040. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67041. if (!cams) {
  67042. return;
  67043. }
  67044. for (var i = 0; i < cams.length; i++) {
  67045. var camera = cams[i];
  67046. var cameraName = camera.name;
  67047. if (this._singleInstance) {
  67048. cameraKey = 0;
  67049. }
  67050. else {
  67051. cameraKey = cameraName;
  67052. }
  67053. if (!this._postProcesses[cameraKey]) {
  67054. var postProcess = this._getPostProcesses();
  67055. if (postProcess) {
  67056. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  67057. }
  67058. }
  67059. if (!this._indicesForCamera[cameraName]) {
  67060. this._indicesForCamera[cameraName] = [];
  67061. }
  67062. this._postProcesses[cameraKey].forEach(function (postProcess) {
  67063. var index = camera.attachPostProcess(postProcess);
  67064. _this._indicesForCamera[cameraName].push(index);
  67065. });
  67066. if (!this._cameras[cameraName]) {
  67067. this._cameras[cameraName] = camera;
  67068. }
  67069. }
  67070. };
  67071. /**
  67072. * Detatches the effect on cameras
  67073. * @param cameras The camera to detatch from.
  67074. */
  67075. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  67076. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67077. if (!cams) {
  67078. return;
  67079. }
  67080. for (var i = 0; i < cams.length; i++) {
  67081. var camera = cams[i];
  67082. var cameraName = camera.name;
  67083. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67084. camera.detachPostProcess(postProcess);
  67085. });
  67086. if (this._cameras[cameraName]) {
  67087. //this._indicesForCamera.splice(index, 1);
  67088. this._cameras[cameraName] = null;
  67089. }
  67090. }
  67091. };
  67092. /**
  67093. * Enables the effect on given cameras
  67094. * @param cameras The camera to enable.
  67095. */
  67096. PostProcessRenderEffect.prototype._enable = function (cameras) {
  67097. var _this = this;
  67098. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67099. if (!cams) {
  67100. return;
  67101. }
  67102. for (var i = 0; i < cams.length; i++) {
  67103. var camera = cams[i];
  67104. var cameraName = camera.name;
  67105. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  67106. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  67107. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67108. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  67109. });
  67110. }
  67111. }
  67112. }
  67113. };
  67114. /**
  67115. * Disables the effect on the given cameras
  67116. * @param cameras The camera to disable.
  67117. */
  67118. PostProcessRenderEffect.prototype._disable = function (cameras) {
  67119. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67120. if (!cams) {
  67121. return;
  67122. }
  67123. for (var i = 0; i < cams.length; i++) {
  67124. var camera = cams[i];
  67125. var cameraName = camera.name;
  67126. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67127. camera.detachPostProcess(postProcess);
  67128. });
  67129. }
  67130. };
  67131. /**
  67132. * Gets a list of the post processes contained in the effect.
  67133. * @param camera The camera to get the post processes on.
  67134. * @returns The list of the post processes in the effect.
  67135. */
  67136. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  67137. if (this._singleInstance) {
  67138. return this._postProcesses[0];
  67139. }
  67140. else {
  67141. if (!camera) {
  67142. return null;
  67143. }
  67144. return this._postProcesses[camera.name];
  67145. }
  67146. };
  67147. return PostProcessRenderEffect;
  67148. }());
  67149. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  67150. })(BABYLON || (BABYLON = {}));
  67151. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  67152. var BABYLON;
  67153. (function (BABYLON) {
  67154. var PostProcessRenderPipeline = /** @class */ (function () {
  67155. function PostProcessRenderPipeline(engine, name) {
  67156. this.engine = engine;
  67157. this._name = name;
  67158. this._renderEffects = {};
  67159. this._renderEffectsForIsolatedPass = new Array();
  67160. this._cameras = [];
  67161. }
  67162. PostProcessRenderPipeline.prototype.getClassName = function () {
  67163. return "PostProcessRenderPipeline";
  67164. };
  67165. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  67166. get: function () {
  67167. for (var renderEffectName in this._renderEffects) {
  67168. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67169. if (!this._renderEffects[renderEffectName].isSupported) {
  67170. return false;
  67171. }
  67172. }
  67173. }
  67174. return true;
  67175. },
  67176. enumerable: true,
  67177. configurable: true
  67178. });
  67179. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  67180. this._renderEffects[renderEffect._name] = renderEffect;
  67181. };
  67182. // private
  67183. PostProcessRenderPipeline.prototype._rebuild = function () {
  67184. };
  67185. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  67186. var renderEffects = this._renderEffects[renderEffectName];
  67187. if (!renderEffects) {
  67188. return;
  67189. }
  67190. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  67191. };
  67192. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  67193. var renderEffects = this._renderEffects[renderEffectName];
  67194. if (!renderEffects) {
  67195. return;
  67196. }
  67197. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  67198. };
  67199. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  67200. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67201. if (!cams) {
  67202. return;
  67203. }
  67204. var indicesToDelete = [];
  67205. var i;
  67206. for (i = 0; i < cams.length; i++) {
  67207. var camera = cams[i];
  67208. var cameraName = camera.name;
  67209. if (this._cameras.indexOf(camera) === -1) {
  67210. this._cameras[cameraName] = camera;
  67211. }
  67212. else if (unique) {
  67213. indicesToDelete.push(i);
  67214. }
  67215. }
  67216. for (i = 0; i < indicesToDelete.length; i++) {
  67217. cameras.splice(indicesToDelete[i], 1);
  67218. }
  67219. for (var renderEffectName in this._renderEffects) {
  67220. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67221. this._renderEffects[renderEffectName]._attachCameras(cams);
  67222. }
  67223. }
  67224. };
  67225. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  67226. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67227. if (!cams) {
  67228. return;
  67229. }
  67230. for (var renderEffectName in this._renderEffects) {
  67231. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67232. this._renderEffects[renderEffectName]._detachCameras(cams);
  67233. }
  67234. }
  67235. for (var i = 0; i < cams.length; i++) {
  67236. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  67237. }
  67238. };
  67239. PostProcessRenderPipeline.prototype._update = function () {
  67240. for (var renderEffectName in this._renderEffects) {
  67241. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67242. this._renderEffects[renderEffectName]._update();
  67243. }
  67244. }
  67245. for (var i = 0; i < this._cameras.length; i++) {
  67246. var cameraName = this._cameras[i].name;
  67247. if (this._renderEffectsForIsolatedPass[cameraName]) {
  67248. this._renderEffectsForIsolatedPass[cameraName]._update();
  67249. }
  67250. }
  67251. };
  67252. PostProcessRenderPipeline.prototype._reset = function () {
  67253. this._renderEffects = {};
  67254. this._renderEffectsForIsolatedPass = new Array();
  67255. };
  67256. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  67257. // 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)
  67258. var effectKeys = Object.keys(this._renderEffects);
  67259. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  67260. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  67261. if (postProcesses) {
  67262. postProcesses[0].samples = 4;
  67263. return true;
  67264. }
  67265. }
  67266. return false;
  67267. };
  67268. PostProcessRenderPipeline.prototype.dispose = function () {
  67269. // Must be implemented by children
  67270. };
  67271. __decorate([
  67272. BABYLON.serialize()
  67273. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  67274. return PostProcessRenderPipeline;
  67275. }());
  67276. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  67277. })(BABYLON || (BABYLON = {}));
  67278. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  67279. var BABYLON;
  67280. (function (BABYLON) {
  67281. /**
  67282. * This represents a depth renderer in Babylon.
  67283. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  67284. */
  67285. var DepthRenderer = /** @class */ (function () {
  67286. /**
  67287. * Instantiates a depth renderer
  67288. * @param scene The scene the renderer belongs to
  67289. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  67290. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  67291. */
  67292. function DepthRenderer(scene, type, camera) {
  67293. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  67294. if (camera === void 0) { camera = null; }
  67295. var _this = this;
  67296. this._scene = scene;
  67297. this._camera = camera;
  67298. var engine = scene.getEngine();
  67299. // Render target
  67300. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  67301. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67302. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67303. this._depthMap.refreshRate = 1;
  67304. this._depthMap.renderParticles = false;
  67305. this._depthMap.renderList = null;
  67306. // Camera to get depth map from to support multiple concurrent cameras
  67307. this._depthMap.activeCamera = this._camera;
  67308. this._depthMap.ignoreCameraViewport = true;
  67309. this._depthMap.useCameraPostProcesses = false;
  67310. // set default depth value to 1.0 (far away)
  67311. this._depthMap.onClearObservable.add(function (engine) {
  67312. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  67313. });
  67314. // Custom render function
  67315. var renderSubMesh = function (subMesh) {
  67316. var mesh = subMesh.getRenderingMesh();
  67317. var scene = _this._scene;
  67318. var engine = scene.getEngine();
  67319. var material = subMesh.getMaterial();
  67320. if (!material) {
  67321. return;
  67322. }
  67323. // Culling and reverse (right handed system)
  67324. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  67325. // Managing instances
  67326. var batch = mesh._getInstancesRenderList(subMesh._id);
  67327. if (batch.mustReturn) {
  67328. return;
  67329. }
  67330. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67331. var camera = _this._camera || scene.activeCamera;
  67332. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  67333. engine.enableEffect(_this._effect);
  67334. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  67335. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67336. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  67337. // Alpha test
  67338. if (material && material.needAlphaTesting()) {
  67339. var alphaTexture = material.getAlphaTestTexture();
  67340. if (alphaTexture) {
  67341. _this._effect.setTexture("diffuseSampler", alphaTexture);
  67342. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67343. }
  67344. }
  67345. // Bones
  67346. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67347. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67348. }
  67349. // Draw
  67350. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67351. }
  67352. };
  67353. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67354. var index;
  67355. if (depthOnlySubMeshes.length) {
  67356. engine.setColorWrite(false);
  67357. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67358. renderSubMesh(depthOnlySubMeshes.data[index]);
  67359. }
  67360. engine.setColorWrite(true);
  67361. }
  67362. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67363. renderSubMesh(opaqueSubMeshes.data[index]);
  67364. }
  67365. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67366. renderSubMesh(alphaTestSubMeshes.data[index]);
  67367. }
  67368. };
  67369. }
  67370. /**
  67371. * Creates the depth rendering effect and checks if the effect is ready.
  67372. * @param subMesh The submesh to be used to render the depth map of
  67373. * @param useInstances If multiple world instances should be used
  67374. * @returns if the depth renderer is ready to render the depth map
  67375. */
  67376. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  67377. var material = subMesh.getMaterial();
  67378. if (material.disableDepthWrite) {
  67379. return false;
  67380. }
  67381. var defines = [];
  67382. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67383. var mesh = subMesh.getMesh();
  67384. // Alpha test
  67385. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  67386. defines.push("#define ALPHATEST");
  67387. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67388. attribs.push(BABYLON.VertexBuffer.UVKind);
  67389. defines.push("#define UV1");
  67390. }
  67391. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67392. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67393. defines.push("#define UV2");
  67394. }
  67395. }
  67396. // Bones
  67397. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67398. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67399. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67400. if (mesh.numBoneInfluencers > 4) {
  67401. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67402. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67403. }
  67404. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67405. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  67406. }
  67407. else {
  67408. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67409. }
  67410. // Instances
  67411. if (useInstances) {
  67412. defines.push("#define INSTANCES");
  67413. attribs.push("world0");
  67414. attribs.push("world1");
  67415. attribs.push("world2");
  67416. attribs.push("world3");
  67417. }
  67418. // Get correct effect
  67419. var join = defines.join("\n");
  67420. if (this._cachedDefines !== join) {
  67421. this._cachedDefines = join;
  67422. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  67423. }
  67424. return this._effect.isReady();
  67425. };
  67426. /**
  67427. * Gets the texture which the depth map will be written to.
  67428. * @returns The depth map texture
  67429. */
  67430. DepthRenderer.prototype.getDepthMap = function () {
  67431. return this._depthMap;
  67432. };
  67433. /**
  67434. * Disposes of the depth renderer.
  67435. */
  67436. DepthRenderer.prototype.dispose = function () {
  67437. this._depthMap.dispose();
  67438. };
  67439. return DepthRenderer;
  67440. }());
  67441. BABYLON.DepthRenderer = DepthRenderer;
  67442. })(BABYLON || (BABYLON = {}));
  67443. //# sourceMappingURL=babylon.depthRenderer.js.map
  67444. var BABYLON;
  67445. (function (BABYLON) {
  67446. var SSAORenderingPipeline = /** @class */ (function (_super) {
  67447. __extends(SSAORenderingPipeline, _super);
  67448. /**
  67449. * @constructor
  67450. * @param {string} name - The rendering pipeline name
  67451. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67452. * @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 }
  67453. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67454. */
  67455. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  67456. var _this = _super.call(this, scene.getEngine(), name) || this;
  67457. // Members
  67458. /**
  67459. * The PassPostProcess id in the pipeline that contains the original scene color
  67460. * @type {string}
  67461. */
  67462. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  67463. /**
  67464. * The SSAO PostProcess id in the pipeline
  67465. * @type {string}
  67466. */
  67467. _this.SSAORenderEffect = "SSAORenderEffect";
  67468. /**
  67469. * The horizontal blur PostProcess id in the pipeline
  67470. * @type {string}
  67471. */
  67472. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  67473. /**
  67474. * The vertical blur PostProcess id in the pipeline
  67475. * @type {string}
  67476. */
  67477. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  67478. /**
  67479. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  67480. * @type {string}
  67481. */
  67482. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  67483. /**
  67484. * The output strength of the SSAO post-process. Default value is 1.0.
  67485. * @type {number}
  67486. */
  67487. _this.totalStrength = 1.0;
  67488. /**
  67489. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  67490. * @type {number}
  67491. */
  67492. _this.radius = 0.0001;
  67493. /**
  67494. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  67495. * Must not be equal to fallOff and superior to fallOff.
  67496. * Default value is 0.975
  67497. * @type {number}
  67498. */
  67499. _this.area = 0.0075;
  67500. /**
  67501. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  67502. * Must not be equal to area and inferior to area.
  67503. * Default value is 0.0
  67504. * @type {number}
  67505. */
  67506. _this.fallOff = 0.000001;
  67507. /**
  67508. * The base color of the SSAO post-process
  67509. * The final result is "base + ssao" between [0, 1]
  67510. * @type {number}
  67511. */
  67512. _this.base = 0.5;
  67513. _this._firstUpdate = true;
  67514. _this._scene = scene;
  67515. // Set up assets
  67516. _this._createRandomTexture();
  67517. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  67518. var ssaoRatio = ratio.ssaoRatio || ratio;
  67519. var combineRatio = ratio.combineRatio || ratio;
  67520. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  67521. _this._createSSAOPostProcess(ssaoRatio);
  67522. _this._createBlurPostProcess(ssaoRatio);
  67523. _this._createSSAOCombinePostProcess(combineRatio);
  67524. // Set up pipeline
  67525. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  67526. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  67527. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  67528. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  67529. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  67530. // Finish
  67531. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67532. if (cameras)
  67533. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67534. return _this;
  67535. }
  67536. // Public Methods
  67537. /**
  67538. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  67539. */
  67540. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67541. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67542. for (var i = 0; i < this._scene.cameras.length; i++) {
  67543. var camera = this._scene.cameras[i];
  67544. this._originalColorPostProcess.dispose(camera);
  67545. this._ssaoPostProcess.dispose(camera);
  67546. this._blurHPostProcess.dispose(camera);
  67547. this._blurVPostProcess.dispose(camera);
  67548. this._ssaoCombinePostProcess.dispose(camera);
  67549. }
  67550. this._randomTexture.dispose();
  67551. if (disableDepthRender)
  67552. this._scene.disableDepthRenderer();
  67553. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67554. _super.prototype.dispose.call(this);
  67555. };
  67556. // Private Methods
  67557. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  67558. var _this = this;
  67559. var size = 16;
  67560. 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);
  67561. 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);
  67562. this._blurHPostProcess.onActivateObservable.add(function () {
  67563. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  67564. _this._blurHPostProcess.kernel = size * dw;
  67565. });
  67566. this._blurVPostProcess.onActivateObservable.add(function () {
  67567. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  67568. _this._blurVPostProcess.kernel = size * dw;
  67569. });
  67570. };
  67571. SSAORenderingPipeline.prototype._rebuild = function () {
  67572. this._firstUpdate = true;
  67573. _super.prototype._rebuild.call(this);
  67574. };
  67575. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  67576. var _this = this;
  67577. var numSamples = 16;
  67578. var sampleSphere = [
  67579. 0.5381, 0.1856, -0.4319,
  67580. 0.1379, 0.2486, 0.4430,
  67581. 0.3371, 0.5679, -0.0057,
  67582. -0.6999, -0.0451, -0.0019,
  67583. 0.0689, -0.1598, -0.8547,
  67584. 0.0560, 0.0069, -0.1843,
  67585. -0.0146, 0.1402, 0.0762,
  67586. 0.0100, -0.1924, -0.0344,
  67587. -0.3577, -0.5301, -0.4358,
  67588. -0.3169, 0.1063, 0.0158,
  67589. 0.0103, -0.5869, 0.0046,
  67590. -0.0897, -0.4940, 0.3287,
  67591. 0.7119, -0.0154, -0.0918,
  67592. -0.0533, 0.0596, -0.5411,
  67593. 0.0352, -0.0631, 0.5460,
  67594. -0.4776, 0.2847, -0.0271
  67595. ];
  67596. var samplesFactor = 1.0 / numSamples;
  67597. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  67598. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  67599. "area", "fallOff", "base", "range", "viewport"
  67600. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  67601. this._ssaoPostProcess.onApply = function (effect) {
  67602. if (_this._firstUpdate) {
  67603. effect.setArray3("sampleSphere", sampleSphere);
  67604. effect.setFloat("samplesFactor", samplesFactor);
  67605. effect.setFloat("randTextureTiles", 4.0);
  67606. }
  67607. effect.setFloat("totalStrength", _this.totalStrength);
  67608. effect.setFloat("radius", _this.radius);
  67609. effect.setFloat("area", _this.area);
  67610. effect.setFloat("fallOff", _this.fallOff);
  67611. effect.setFloat("base", _this.base);
  67612. effect.setTexture("textureSampler", _this._depthTexture);
  67613. effect.setTexture("randomSampler", _this._randomTexture);
  67614. };
  67615. };
  67616. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67617. var _this = this;
  67618. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67619. this._ssaoCombinePostProcess.onApply = function (effect) {
  67620. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67621. };
  67622. };
  67623. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  67624. var size = 512;
  67625. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67626. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67627. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67628. var context = this._randomTexture.getContext();
  67629. var rand = function (min, max) {
  67630. return Math.random() * (max - min) + min;
  67631. };
  67632. var randVector = BABYLON.Vector3.Zero();
  67633. for (var x = 0; x < size; x++) {
  67634. for (var y = 0; y < size; y++) {
  67635. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  67636. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  67637. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  67638. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67639. context.fillRect(x, y, 1, 1);
  67640. }
  67641. }
  67642. this._randomTexture.update(false);
  67643. };
  67644. __decorate([
  67645. BABYLON.serialize()
  67646. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  67647. __decorate([
  67648. BABYLON.serialize()
  67649. ], SSAORenderingPipeline.prototype, "radius", void 0);
  67650. __decorate([
  67651. BABYLON.serialize()
  67652. ], SSAORenderingPipeline.prototype, "area", void 0);
  67653. __decorate([
  67654. BABYLON.serialize()
  67655. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  67656. __decorate([
  67657. BABYLON.serialize()
  67658. ], SSAORenderingPipeline.prototype, "base", void 0);
  67659. return SSAORenderingPipeline;
  67660. }(BABYLON.PostProcessRenderPipeline));
  67661. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  67662. })(BABYLON || (BABYLON = {}));
  67663. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  67664. var BABYLON;
  67665. (function (BABYLON) {
  67666. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  67667. __extends(SSAO2RenderingPipeline, _super);
  67668. /**
  67669. * @constructor
  67670. * @param {string} name - The rendering pipeline name
  67671. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67672. * @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 }
  67673. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67674. */
  67675. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  67676. var _this = _super.call(this, scene.getEngine(), name) || this;
  67677. // Members
  67678. /**
  67679. * The PassPostProcess id in the pipeline that contains the original scene color
  67680. * @type {string}
  67681. */
  67682. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  67683. /**
  67684. * The SSAO PostProcess id in the pipeline
  67685. * @type {string}
  67686. */
  67687. _this.SSAORenderEffect = "SSAORenderEffect";
  67688. /**
  67689. * The horizontal blur PostProcess id in the pipeline
  67690. * @type {string}
  67691. */
  67692. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  67693. /**
  67694. * The vertical blur PostProcess id in the pipeline
  67695. * @type {string}
  67696. */
  67697. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  67698. /**
  67699. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  67700. * @type {string}
  67701. */
  67702. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  67703. /**
  67704. * The output strength of the SSAO post-process. Default value is 1.0.
  67705. * @type {number}
  67706. */
  67707. _this.totalStrength = 1.0;
  67708. /**
  67709. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  67710. * @type {number}
  67711. */
  67712. _this.maxZ = 100.0;
  67713. /**
  67714. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  67715. * @type {number}
  67716. */
  67717. _this.minZAspect = 0.2;
  67718. /**
  67719. * Number of samples used for the SSAO calculations. Default value is 8
  67720. * @type {number}
  67721. */
  67722. _this._samples = 8;
  67723. /**
  67724. * Are we using bilateral blur ?
  67725. * @type {boolean}
  67726. */
  67727. _this._expensiveBlur = true;
  67728. /**
  67729. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  67730. * @type {number}
  67731. */
  67732. _this.radius = 2.0;
  67733. /**
  67734. * The base color of the SSAO post-process
  67735. * The final result is "base + ssao" between [0, 1]
  67736. * @type {number}
  67737. */
  67738. _this.base = 0.1;
  67739. _this._firstUpdate = true;
  67740. _this._scene = scene;
  67741. if (!_this.isSupported) {
  67742. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  67743. return _this;
  67744. }
  67745. var ssaoRatio = ratio.ssaoRatio || ratio;
  67746. var blurRatio = ratio.blurRatio || ratio;
  67747. // Set up assets
  67748. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  67749. _this._createRandomTexture();
  67750. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  67751. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  67752. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  67753. _this._createSSAOPostProcess(1.0);
  67754. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  67755. _this._createSSAOCombinePostProcess(blurRatio);
  67756. // Set up pipeline
  67757. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  67758. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  67759. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  67760. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  67761. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  67762. // Finish
  67763. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67764. if (cameras)
  67765. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67766. return _this;
  67767. }
  67768. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  67769. get: function () {
  67770. return this._samples;
  67771. },
  67772. set: function (n) {
  67773. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  67774. this._samples = n;
  67775. this._sampleSphere = this._generateHemisphere();
  67776. this._firstUpdate = true;
  67777. },
  67778. enumerable: true,
  67779. configurable: true
  67780. });
  67781. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  67782. get: function () {
  67783. return this._expensiveBlur;
  67784. },
  67785. set: function (b) {
  67786. 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"]);
  67787. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  67788. this._expensiveBlur = b;
  67789. this._firstUpdate = true;
  67790. },
  67791. enumerable: true,
  67792. configurable: true
  67793. });
  67794. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  67795. /**
  67796. * Support test.
  67797. * @type {boolean}
  67798. */
  67799. get: function () {
  67800. var engine = BABYLON.Engine.LastCreatedEngine;
  67801. if (!engine) {
  67802. return false;
  67803. }
  67804. return engine.getCaps().drawBuffersExtension;
  67805. },
  67806. enumerable: true,
  67807. configurable: true
  67808. });
  67809. // Public Methods
  67810. /**
  67811. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  67812. */
  67813. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  67814. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  67815. for (var i = 0; i < this._scene.cameras.length; i++) {
  67816. var camera = this._scene.cameras[i];
  67817. this._originalColorPostProcess.dispose(camera);
  67818. this._ssaoPostProcess.dispose(camera);
  67819. this._blurHPostProcess.dispose(camera);
  67820. this._blurVPostProcess.dispose(camera);
  67821. this._ssaoCombinePostProcess.dispose(camera);
  67822. }
  67823. this._randomTexture.dispose();
  67824. if (disableGeometryBufferRenderer)
  67825. this._scene.disableGeometryBufferRenderer();
  67826. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67827. _super.prototype.dispose.call(this);
  67828. };
  67829. // Private Methods
  67830. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  67831. var _this = this;
  67832. this._samplerOffsets = [];
  67833. var expensive = this.expensiveBlur;
  67834. for (var i = -8; i < 8; i++) {
  67835. this._samplerOffsets.push(i * 2 + 0.5);
  67836. }
  67837. 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");
  67838. this._blurHPostProcess.onApply = function (effect) {
  67839. if (!_this._scene.activeCamera) {
  67840. return;
  67841. }
  67842. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  67843. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67844. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67845. effect.setFloat("radius", _this.radius);
  67846. effect.setTexture("depthSampler", _this._depthTexture);
  67847. if (_this._firstUpdate) {
  67848. effect.setArray("samplerOffsets", _this._samplerOffsets);
  67849. }
  67850. };
  67851. 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");
  67852. this._blurVPostProcess.onApply = function (effect) {
  67853. if (!_this._scene.activeCamera) {
  67854. return;
  67855. }
  67856. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  67857. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67858. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67859. effect.setFloat("radius", _this.radius);
  67860. effect.setTexture("depthSampler", _this._depthTexture);
  67861. if (_this._firstUpdate) {
  67862. effect.setArray("samplerOffsets", _this._samplerOffsets);
  67863. _this._firstUpdate = false;
  67864. }
  67865. };
  67866. };
  67867. SSAO2RenderingPipeline.prototype._rebuild = function () {
  67868. this._firstUpdate = true;
  67869. _super.prototype._rebuild.call(this);
  67870. };
  67871. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  67872. var numSamples = this.samples;
  67873. var result = [];
  67874. var vector, scale;
  67875. var rand = function (min, max) {
  67876. return Math.random() * (max - min) + min;
  67877. };
  67878. var i = 0;
  67879. while (i < numSamples) {
  67880. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  67881. vector.normalize();
  67882. scale = i / numSamples;
  67883. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  67884. vector.scaleInPlace(scale);
  67885. result.push(vector.x, vector.y, vector.z);
  67886. i++;
  67887. }
  67888. return result;
  67889. };
  67890. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  67891. var _this = this;
  67892. var numSamples = this.samples;
  67893. this._sampleSphere = this._generateHemisphere();
  67894. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  67895. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  67896. "base", "range", "projection", "near", "far", "texelSize",
  67897. "xViewport", "yViewport", "maxZ", "minZAspect"
  67898. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  67899. this._ssaoPostProcess.onApply = function (effect) {
  67900. if (_this._firstUpdate) {
  67901. effect.setArray3("sampleSphere", _this._sampleSphere);
  67902. effect.setFloat("randTextureTiles", 4.0);
  67903. }
  67904. if (!_this._scene.activeCamera) {
  67905. return;
  67906. }
  67907. effect.setFloat("samplesFactor", 1 / _this.samples);
  67908. effect.setFloat("totalStrength", _this.totalStrength);
  67909. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  67910. effect.setFloat("radius", _this.radius);
  67911. effect.setFloat("maxZ", _this.maxZ);
  67912. effect.setFloat("minZAspect", _this.minZAspect);
  67913. effect.setFloat("base", _this.base);
  67914. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67915. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67916. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  67917. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  67918. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  67919. effect.setTexture("textureSampler", _this._depthTexture);
  67920. effect.setTexture("normalSampler", _this._normalTexture);
  67921. effect.setTexture("randomSampler", _this._randomTexture);
  67922. };
  67923. };
  67924. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67925. var _this = this;
  67926. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67927. this._ssaoCombinePostProcess.onApply = function (effect) {
  67928. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67929. };
  67930. };
  67931. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  67932. var size = 512;
  67933. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67934. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67935. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67936. var context = this._randomTexture.getContext();
  67937. var rand = function (min, max) {
  67938. return Math.random() * (max - min) + min;
  67939. };
  67940. var randVector = BABYLON.Vector3.Zero();
  67941. for (var x = 0; x < size; x++) {
  67942. for (var y = 0; y < size; y++) {
  67943. randVector.x = rand(0.0, 1.0);
  67944. randVector.y = rand(0.0, 1.0);
  67945. randVector.z = 0.0;
  67946. randVector.normalize();
  67947. randVector.scaleInPlace(255);
  67948. randVector.x = Math.floor(randVector.x);
  67949. randVector.y = Math.floor(randVector.y);
  67950. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67951. context.fillRect(x, y, 1, 1);
  67952. }
  67953. }
  67954. this._randomTexture.update(false);
  67955. };
  67956. __decorate([
  67957. BABYLON.serialize()
  67958. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  67959. __decorate([
  67960. BABYLON.serialize()
  67961. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  67962. __decorate([
  67963. BABYLON.serialize()
  67964. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  67965. __decorate([
  67966. BABYLON.serialize("samples")
  67967. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  67968. __decorate([
  67969. BABYLON.serialize("expensiveBlur")
  67970. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  67971. __decorate([
  67972. BABYLON.serialize()
  67973. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  67974. __decorate([
  67975. BABYLON.serialize()
  67976. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  67977. return SSAO2RenderingPipeline;
  67978. }(BABYLON.PostProcessRenderPipeline));
  67979. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  67980. })(BABYLON || (BABYLON = {}));
  67981. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  67982. // BABYLON.JS Chromatic Aberration GLSL Shader
  67983. // Author: Olivier Guyot
  67984. // Separates very slightly R, G and B colors on the edges of the screen
  67985. // Inspired by Francois Tarlier & Martins Upitis
  67986. var BABYLON;
  67987. (function (BABYLON) {
  67988. var LensRenderingPipeline = /** @class */ (function (_super) {
  67989. __extends(LensRenderingPipeline, _super);
  67990. /**
  67991. * @constructor
  67992. *
  67993. * Effect parameters are as follow:
  67994. * {
  67995. * chromatic_aberration: number; // from 0 to x (1 for realism)
  67996. * edge_blur: number; // from 0 to x (1 for realism)
  67997. * distortion: number; // from 0 to x (1 for realism)
  67998. * grain_amount: number; // from 0 to 1
  67999. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  68000. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  68001. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  68002. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  68003. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  68004. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  68005. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  68006. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  68007. * }
  68008. * Note: if an effect parameter is unset, effect is disabled
  68009. *
  68010. * @param {string} name - The rendering pipeline name
  68011. * @param {object} parameters - An object containing all parameters (see above)
  68012. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68013. * @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)
  68014. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68015. */
  68016. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  68017. if (ratio === void 0) { ratio = 1.0; }
  68018. var _this = _super.call(this, scene.getEngine(), name) || this;
  68019. // Lens effects can be of the following:
  68020. // - chromatic aberration (slight shift of RGB colors)
  68021. // - blur on the edge of the lens
  68022. // - lens distortion
  68023. // - depth-of-field blur & highlights enhancing
  68024. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  68025. // - grain effect (noise or custom texture)
  68026. // Two additional texture samplers are needed:
  68027. // - depth map (for depth-of-field)
  68028. // - grain texture
  68029. /**
  68030. * The chromatic aberration PostProcess id in the pipeline
  68031. * @type {string}
  68032. */
  68033. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  68034. /**
  68035. * The highlights enhancing PostProcess id in the pipeline
  68036. * @type {string}
  68037. */
  68038. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  68039. /**
  68040. * The depth-of-field PostProcess id in the pipeline
  68041. * @type {string}
  68042. */
  68043. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  68044. _this._scene = scene;
  68045. // Fetch texture samplers
  68046. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68047. if (parameters.grain_texture) {
  68048. _this._grainTexture = parameters.grain_texture;
  68049. }
  68050. else {
  68051. _this._createGrainTexture();
  68052. }
  68053. // save parameters
  68054. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  68055. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  68056. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  68057. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  68058. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  68059. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  68060. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  68061. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  68062. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  68063. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  68064. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  68065. // Create effects
  68066. _this._createChromaticAberrationPostProcess(ratio);
  68067. _this._createHighlightsPostProcess(ratio);
  68068. _this._createDepthOfFieldPostProcess(ratio / 4);
  68069. // Set up pipeline
  68070. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  68071. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  68072. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  68073. if (_this._highlightsGain === -1) {
  68074. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  68075. }
  68076. // Finish
  68077. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68078. if (cameras) {
  68079. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68080. }
  68081. return _this;
  68082. }
  68083. // public methods (self explanatory)
  68084. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  68085. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  68086. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  68087. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  68088. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  68089. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  68090. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  68091. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  68092. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  68093. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  68094. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  68095. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  68096. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  68097. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  68098. };
  68099. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  68100. this._highlightsPostProcess.updateEffect();
  68101. };
  68102. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  68103. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  68104. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  68105. this._highlightsGain = amount;
  68106. };
  68107. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  68108. if (this._highlightsGain === -1) {
  68109. this._highlightsGain = 1.0;
  68110. }
  68111. this._highlightsThreshold = amount;
  68112. };
  68113. LensRenderingPipeline.prototype.disableHighlights = function () {
  68114. this._highlightsGain = -1;
  68115. };
  68116. /**
  68117. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  68118. */
  68119. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  68120. if (disableDepthRender === void 0) { disableDepthRender = false; }
  68121. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68122. this._chromaticAberrationPostProcess = null;
  68123. this._highlightsPostProcess = null;
  68124. this._depthOfFieldPostProcess = null;
  68125. this._grainTexture.dispose();
  68126. if (disableDepthRender)
  68127. this._scene.disableDepthRenderer();
  68128. };
  68129. // colors shifting and distortion
  68130. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  68131. var _this = this;
  68132. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  68133. [], // samplers
  68134. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68135. this._chromaticAberrationPostProcess.onApply = function (effect) {
  68136. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  68137. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68138. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68139. effect.setFloat('radialIntensity', 1);
  68140. effect.setFloat2('direction', 17, 17);
  68141. effect.setFloat2('centerPosition', 0.5, 0.5);
  68142. };
  68143. };
  68144. // highlights enhancing
  68145. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  68146. var _this = this;
  68147. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  68148. [], // samplers
  68149. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  68150. this._highlightsPostProcess.onApply = function (effect) {
  68151. effect.setFloat('gain', _this._highlightsGain);
  68152. effect.setFloat('threshold', _this._highlightsThreshold);
  68153. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  68154. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68155. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68156. };
  68157. };
  68158. // colors shifting and distortion
  68159. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  68160. var _this = this;
  68161. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  68162. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  68163. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  68164. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68165. this._depthOfFieldPostProcess.onApply = function (effect) {
  68166. effect.setTexture("depthSampler", _this._depthTexture);
  68167. effect.setTexture("grainSampler", _this._grainTexture);
  68168. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  68169. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  68170. effect.setFloat('grain_amount', _this._grainAmount);
  68171. effect.setBool('blur_noise', _this._blurNoise);
  68172. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68173. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68174. effect.setFloat('distortion', _this._distortion);
  68175. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  68176. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  68177. effect.setFloat('aperture', _this._dofAperture);
  68178. effect.setFloat('darken', _this._dofDarken);
  68179. effect.setFloat('edge_blur', _this._edgeBlur);
  68180. effect.setBool('highlights', (_this._highlightsGain !== -1));
  68181. if (_this._scene.activeCamera) {
  68182. effect.setFloat('near', _this._scene.activeCamera.minZ);
  68183. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  68184. }
  68185. };
  68186. };
  68187. // creates a black and white random noise texture, 512x512
  68188. LensRenderingPipeline.prototype._createGrainTexture = function () {
  68189. var size = 512;
  68190. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68191. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68192. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68193. var context = this._grainTexture.getContext();
  68194. var rand = function (min, max) {
  68195. return Math.random() * (max - min) + min;
  68196. };
  68197. var value;
  68198. for (var x = 0; x < size; x++) {
  68199. for (var y = 0; y < size; y++) {
  68200. value = Math.floor(rand(0.42, 0.58) * 255);
  68201. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  68202. context.fillRect(x, y, 1, 1);
  68203. }
  68204. }
  68205. this._grainTexture.update(false);
  68206. };
  68207. return LensRenderingPipeline;
  68208. }(BABYLON.PostProcessRenderPipeline));
  68209. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  68210. })(BABYLON || (BABYLON = {}));
  68211. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  68212. var BABYLON;
  68213. (function (BABYLON) {
  68214. var StandardRenderingPipeline = /** @class */ (function (_super) {
  68215. __extends(StandardRenderingPipeline, _super);
  68216. /**
  68217. * @constructor
  68218. * @param {string} name - The rendering pipeline name
  68219. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68220. * @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)
  68221. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  68222. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68223. */
  68224. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  68225. if (originalPostProcess === void 0) { originalPostProcess = null; }
  68226. var _this = _super.call(this, scene.getEngine(), name) || this;
  68227. _this.downSampleX4PostProcess = null;
  68228. _this.brightPassPostProcess = null;
  68229. _this.blurHPostProcesses = [];
  68230. _this.blurVPostProcesses = [];
  68231. _this.textureAdderPostProcess = null;
  68232. _this.volumetricLightPostProcess = null;
  68233. _this.volumetricLightSmoothXPostProcess = null;
  68234. _this.volumetricLightSmoothYPostProcess = null;
  68235. _this.volumetricLightMergePostProces = null;
  68236. _this.volumetricLightFinalPostProcess = null;
  68237. _this.luminancePostProcess = null;
  68238. _this.luminanceDownSamplePostProcesses = [];
  68239. _this.hdrPostProcess = null;
  68240. _this.textureAdderFinalPostProcess = null;
  68241. _this.lensFlareFinalPostProcess = null;
  68242. _this.hdrFinalPostProcess = null;
  68243. _this.lensFlarePostProcess = null;
  68244. _this.lensFlareComposePostProcess = null;
  68245. _this.motionBlurPostProcess = null;
  68246. _this.depthOfFieldPostProcess = null;
  68247. // Values
  68248. _this.brightThreshold = 1.0;
  68249. _this.blurWidth = 512.0;
  68250. _this.horizontalBlur = false;
  68251. _this.exposure = 1.0;
  68252. _this.lensTexture = null;
  68253. _this.volumetricLightCoefficient = 0.2;
  68254. _this.volumetricLightPower = 4.0;
  68255. _this.volumetricLightBlurScale = 64.0;
  68256. _this.sourceLight = null;
  68257. _this.hdrMinimumLuminance = 1.0;
  68258. _this.hdrDecreaseRate = 0.5;
  68259. _this.hdrIncreaseRate = 0.5;
  68260. _this.lensColorTexture = null;
  68261. _this.lensFlareStrength = 20.0;
  68262. _this.lensFlareGhostDispersal = 1.4;
  68263. _this.lensFlareHaloWidth = 0.7;
  68264. _this.lensFlareDistortionStrength = 16.0;
  68265. _this.lensStarTexture = null;
  68266. _this.lensFlareDirtTexture = null;
  68267. _this.depthOfFieldDistance = 10.0;
  68268. _this.depthOfFieldBlurWidth = 64.0;
  68269. _this.motionStrength = 1.0;
  68270. // IAnimatable
  68271. _this.animations = [];
  68272. _this._currentDepthOfFieldSource = null;
  68273. _this._hdrCurrentLuminance = 1.0;
  68274. // Getters and setters
  68275. _this._bloomEnabled = true;
  68276. _this._depthOfFieldEnabled = false;
  68277. _this._vlsEnabled = false;
  68278. _this._lensFlareEnabled = false;
  68279. _this._hdrEnabled = false;
  68280. _this._motionBlurEnabled = false;
  68281. _this._motionBlurSamples = 64.0;
  68282. _this._volumetricLightStepsCount = 50.0;
  68283. _this._cameras = cameras || [];
  68284. // Initialize
  68285. _this._scene = scene;
  68286. _this._basePostProcess = originalPostProcess;
  68287. _this._ratio = ratio;
  68288. // Misc
  68289. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68290. // Finish
  68291. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68292. _this._buildPipeline();
  68293. return _this;
  68294. }
  68295. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  68296. get: function () {
  68297. return this._bloomEnabled;
  68298. },
  68299. set: function (enabled) {
  68300. if (this._bloomEnabled === enabled) {
  68301. return;
  68302. }
  68303. this._bloomEnabled = enabled;
  68304. this._buildPipeline();
  68305. },
  68306. enumerable: true,
  68307. configurable: true
  68308. });
  68309. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  68310. get: function () {
  68311. return this._depthOfFieldEnabled;
  68312. },
  68313. set: function (enabled) {
  68314. if (this._depthOfFieldEnabled === enabled) {
  68315. return;
  68316. }
  68317. this._depthOfFieldEnabled = enabled;
  68318. this._buildPipeline();
  68319. },
  68320. enumerable: true,
  68321. configurable: true
  68322. });
  68323. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  68324. get: function () {
  68325. return this._lensFlareEnabled;
  68326. },
  68327. set: function (enabled) {
  68328. if (this._lensFlareEnabled === enabled) {
  68329. return;
  68330. }
  68331. this._lensFlareEnabled = enabled;
  68332. this._buildPipeline();
  68333. },
  68334. enumerable: true,
  68335. configurable: true
  68336. });
  68337. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  68338. get: function () {
  68339. return this._hdrEnabled;
  68340. },
  68341. set: function (enabled) {
  68342. if (this._hdrEnabled === enabled) {
  68343. return;
  68344. }
  68345. this._hdrEnabled = enabled;
  68346. this._buildPipeline();
  68347. },
  68348. enumerable: true,
  68349. configurable: true
  68350. });
  68351. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  68352. get: function () {
  68353. return this._vlsEnabled;
  68354. },
  68355. set: function (enabled) {
  68356. if (this._vlsEnabled === enabled) {
  68357. return;
  68358. }
  68359. if (enabled) {
  68360. var geometry = this._scene.enableGeometryBufferRenderer();
  68361. if (!geometry) {
  68362. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  68363. return;
  68364. }
  68365. }
  68366. this._vlsEnabled = enabled;
  68367. this._buildPipeline();
  68368. },
  68369. enumerable: true,
  68370. configurable: true
  68371. });
  68372. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  68373. get: function () {
  68374. return this._motionBlurEnabled;
  68375. },
  68376. set: function (enabled) {
  68377. if (this._motionBlurEnabled === enabled) {
  68378. return;
  68379. }
  68380. this._motionBlurEnabled = enabled;
  68381. this._buildPipeline();
  68382. },
  68383. enumerable: true,
  68384. configurable: true
  68385. });
  68386. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  68387. get: function () {
  68388. return this._volumetricLightStepsCount;
  68389. },
  68390. set: function (count) {
  68391. if (this.volumetricLightPostProcess) {
  68392. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  68393. }
  68394. this._volumetricLightStepsCount = count;
  68395. },
  68396. enumerable: true,
  68397. configurable: true
  68398. });
  68399. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  68400. get: function () {
  68401. return this._motionBlurSamples;
  68402. },
  68403. set: function (samples) {
  68404. if (this.motionBlurPostProcess) {
  68405. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  68406. }
  68407. this._motionBlurSamples = samples;
  68408. },
  68409. enumerable: true,
  68410. configurable: true
  68411. });
  68412. StandardRenderingPipeline.prototype._buildPipeline = function () {
  68413. var _this = this;
  68414. var ratio = this._ratio;
  68415. var scene = this._scene;
  68416. this._disposePostProcesses();
  68417. this._reset();
  68418. // Create pass post-process
  68419. if (!this._basePostProcess) {
  68420. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  68421. this.originalPostProcess.onApply = function (effect) {
  68422. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  68423. };
  68424. }
  68425. else {
  68426. this.originalPostProcess = this._basePostProcess;
  68427. }
  68428. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  68429. this._currentDepthOfFieldSource = this.originalPostProcess;
  68430. if (this._vlsEnabled) {
  68431. // Create volumetric light
  68432. this._createVolumetricLightPostProcess(scene, ratio);
  68433. // Create volumetric light final post-process
  68434. 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);
  68435. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  68436. }
  68437. if (this._bloomEnabled) {
  68438. // Create down sample X4 post-process
  68439. this._createDownSampleX4PostProcess(scene, ratio / 2);
  68440. // Create bright pass post-process
  68441. this._createBrightPassPostProcess(scene, ratio / 2);
  68442. // Create gaussian blur post-processes (down sampling blurs)
  68443. this._createBlurPostProcesses(scene, ratio / 4, 1);
  68444. // Create texture adder post-process
  68445. this._createTextureAdderPostProcess(scene, ratio);
  68446. // Create depth-of-field source post-process
  68447. 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);
  68448. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  68449. }
  68450. if (this._lensFlareEnabled) {
  68451. // Create lens flare post-process
  68452. this._createLensFlarePostProcess(scene, ratio);
  68453. // Create depth-of-field source post-process post lens-flare and disable it now
  68454. 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);
  68455. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  68456. }
  68457. if (this._hdrEnabled) {
  68458. // Create luminance
  68459. this._createLuminancePostProcesses(scene, this._floatTextureType);
  68460. // Create HDR
  68461. this._createHdrPostProcess(scene, ratio);
  68462. // Create depth-of-field source post-process post hdr and disable it now
  68463. 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);
  68464. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  68465. }
  68466. if (this._depthOfFieldEnabled) {
  68467. // Create gaussian blur used by depth-of-field
  68468. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  68469. // Create depth-of-field post-process
  68470. this._createDepthOfFieldPostProcess(scene, ratio);
  68471. }
  68472. if (this._motionBlurEnabled) {
  68473. // Create motion blur post-process
  68474. this._createMotionBlurPostProcess(scene, ratio);
  68475. }
  68476. if (this._cameras !== null) {
  68477. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  68478. }
  68479. };
  68480. // Down Sample X4 Post-Processs
  68481. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  68482. var _this = this;
  68483. var downSampleX4Offsets = new Array(32);
  68484. 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);
  68485. this.downSampleX4PostProcess.onApply = function (effect) {
  68486. var id = 0;
  68487. var width = _this.downSampleX4PostProcess.width;
  68488. var height = _this.downSampleX4PostProcess.height;
  68489. for (var i = -2; i < 2; i++) {
  68490. for (var j = -2; j < 2; j++) {
  68491. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  68492. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  68493. id += 2;
  68494. }
  68495. }
  68496. effect.setArray2("dsOffsets", downSampleX4Offsets);
  68497. };
  68498. // Add to pipeline
  68499. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  68500. };
  68501. // Brightpass Post-Process
  68502. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  68503. var _this = this;
  68504. var brightOffsets = new Array(8);
  68505. 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);
  68506. this.brightPassPostProcess.onApply = function (effect) {
  68507. var sU = (1.0 / _this.brightPassPostProcess.width);
  68508. var sV = (1.0 / _this.brightPassPostProcess.height);
  68509. brightOffsets[0] = -0.5 * sU;
  68510. brightOffsets[1] = 0.5 * sV;
  68511. brightOffsets[2] = 0.5 * sU;
  68512. brightOffsets[3] = 0.5 * sV;
  68513. brightOffsets[4] = -0.5 * sU;
  68514. brightOffsets[5] = -0.5 * sV;
  68515. brightOffsets[6] = 0.5 * sU;
  68516. brightOffsets[7] = -0.5 * sV;
  68517. effect.setArray2("dsOffsets", brightOffsets);
  68518. effect.setFloat("brightThreshold", _this.brightThreshold);
  68519. };
  68520. // Add to pipeline
  68521. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  68522. };
  68523. // Create blur H&V post-processes
  68524. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  68525. var _this = this;
  68526. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  68527. var engine = scene.getEngine();
  68528. 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);
  68529. 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);
  68530. blurX.onActivateObservable.add(function () {
  68531. var dw = blurX.width / engine.getRenderWidth();
  68532. blurX.kernel = _this[blurWidthKey] * dw;
  68533. });
  68534. blurY.onActivateObservable.add(function () {
  68535. var dw = blurY.height / engine.getRenderHeight();
  68536. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  68537. });
  68538. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  68539. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  68540. this.blurHPostProcesses.push(blurX);
  68541. this.blurVPostProcesses.push(blurY);
  68542. };
  68543. // Create texture adder post-process
  68544. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  68545. var _this = this;
  68546. 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);
  68547. this.textureAdderPostProcess.onApply = function (effect) {
  68548. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  68549. effect.setTexture("lensSampler", _this.lensTexture);
  68550. effect.setFloat("exposure", _this.exposure);
  68551. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  68552. };
  68553. // Add to pipeline
  68554. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  68555. };
  68556. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  68557. var _this = this;
  68558. var geometryRenderer = scene.enableGeometryBufferRenderer();
  68559. geometryRenderer.enablePosition = true;
  68560. var geometry = geometryRenderer.getGBuffer();
  68561. // Base post-process
  68562. 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));
  68563. var depthValues = BABYLON.Vector2.Zero();
  68564. this.volumetricLightPostProcess.onApply = function (effect) {
  68565. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  68566. var generator = _this.sourceLight.getShadowGenerator();
  68567. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  68568. effect.setTexture("positionSampler", geometry.textures[2]);
  68569. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  68570. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  68571. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  68572. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  68573. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  68574. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  68575. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  68576. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  68577. effect.setVector2("depthValues", depthValues);
  68578. }
  68579. };
  68580. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  68581. // Smooth
  68582. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  68583. // Merge
  68584. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  68585. this.volumetricLightMergePostProces.onApply = function (effect) {
  68586. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  68587. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  68588. };
  68589. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  68590. };
  68591. // Create luminance
  68592. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  68593. var _this = this;
  68594. // Create luminance
  68595. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  68596. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  68597. var offsets = [];
  68598. this.luminancePostProcess.onApply = function (effect) {
  68599. var sU = (1.0 / _this.luminancePostProcess.width);
  68600. var sV = (1.0 / _this.luminancePostProcess.height);
  68601. offsets[0] = -0.5 * sU;
  68602. offsets[1] = 0.5 * sV;
  68603. offsets[2] = 0.5 * sU;
  68604. offsets[3] = 0.5 * sV;
  68605. offsets[4] = -0.5 * sU;
  68606. offsets[5] = -0.5 * sV;
  68607. offsets[6] = 0.5 * sU;
  68608. offsets[7] = -0.5 * sV;
  68609. effect.setArray2("lumOffsets", offsets);
  68610. };
  68611. // Add to pipeline
  68612. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  68613. // Create down sample luminance
  68614. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  68615. var size = Math.pow(3, i);
  68616. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  68617. if (i === 0) {
  68618. defines += "#define FINAL_DOWN_SAMPLER";
  68619. }
  68620. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  68621. this.luminanceDownSamplePostProcesses.push(postProcess);
  68622. }
  68623. // Create callbacks and add effects
  68624. var lastLuminance = this.luminancePostProcess;
  68625. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  68626. var downSampleOffsets = new Array(18);
  68627. pp.onApply = function (effect) {
  68628. if (!lastLuminance) {
  68629. return;
  68630. }
  68631. var id = 0;
  68632. for (var x = -1; x < 2; x++) {
  68633. for (var y = -1; y < 2; y++) {
  68634. downSampleOffsets[id] = x / lastLuminance.width;
  68635. downSampleOffsets[id + 1] = y / lastLuminance.height;
  68636. id += 2;
  68637. }
  68638. }
  68639. effect.setArray2("dsOffsets", downSampleOffsets);
  68640. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  68641. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68642. lastLuminance = _this.luminancePostProcess;
  68643. }
  68644. else {
  68645. lastLuminance = pp;
  68646. }
  68647. };
  68648. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68649. pp.onAfterRender = function (effect) {
  68650. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  68651. 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);
  68652. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  68653. };
  68654. }
  68655. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  68656. });
  68657. };
  68658. // Create HDR post-process
  68659. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  68660. var _this = this;
  68661. 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);
  68662. var outputLiminance = 1;
  68663. var time = 0;
  68664. var lastTime = 0;
  68665. this.hdrPostProcess.onApply = function (effect) {
  68666. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  68667. time += scene.getEngine().getDeltaTime();
  68668. if (outputLiminance < 0) {
  68669. outputLiminance = _this._hdrCurrentLuminance;
  68670. }
  68671. else {
  68672. var dt = (lastTime - time) / 1000.0;
  68673. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  68674. outputLiminance += _this.hdrDecreaseRate * dt;
  68675. }
  68676. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  68677. outputLiminance -= _this.hdrIncreaseRate * dt;
  68678. }
  68679. else {
  68680. outputLiminance = _this._hdrCurrentLuminance;
  68681. }
  68682. }
  68683. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  68684. effect.setFloat("averageLuminance", outputLiminance);
  68685. lastTime = time;
  68686. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  68687. };
  68688. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  68689. };
  68690. // Create lens flare post-process
  68691. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  68692. var _this = this;
  68693. 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);
  68694. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  68695. this._createBlurPostProcesses(scene, ratio / 4, 2);
  68696. 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);
  68697. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  68698. var resolution = new BABYLON.Vector2(0, 0);
  68699. // Lens flare
  68700. this.lensFlarePostProcess.onApply = function (effect) {
  68701. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  68702. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  68703. effect.setFloat("strength", _this.lensFlareStrength);
  68704. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  68705. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  68706. // Shift
  68707. resolution.x = _this.lensFlarePostProcess.width;
  68708. resolution.y = _this.lensFlarePostProcess.height;
  68709. effect.setVector2("resolution", resolution);
  68710. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  68711. };
  68712. // Compose
  68713. 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);
  68714. 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);
  68715. this.lensFlareComposePostProcess.onApply = function (effect) {
  68716. if (!_this._scene.activeCamera) {
  68717. return;
  68718. }
  68719. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  68720. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  68721. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  68722. // Lens start rotation matrix
  68723. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  68724. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  68725. 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));
  68726. camRot *= 4.0;
  68727. 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);
  68728. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  68729. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  68730. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  68731. };
  68732. };
  68733. // Create depth-of-field post-process
  68734. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  68735. var _this = this;
  68736. 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);
  68737. this.depthOfFieldPostProcess.onApply = function (effect) {
  68738. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  68739. effect.setTexture("depthSampler", _this._getDepthTexture());
  68740. effect.setFloat("distance", _this.depthOfFieldDistance);
  68741. };
  68742. // Add to pipeline
  68743. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  68744. };
  68745. // Create motion blur post-process
  68746. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  68747. var _this = this;
  68748. 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);
  68749. var motionScale = 0;
  68750. var prevViewProjection = BABYLON.Matrix.Identity();
  68751. var invViewProjection = BABYLON.Matrix.Identity();
  68752. var viewProjection = BABYLON.Matrix.Identity();
  68753. var screenSize = BABYLON.Vector2.Zero();
  68754. this.motionBlurPostProcess.onApply = function (effect) {
  68755. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  68756. viewProjection.invertToRef(invViewProjection);
  68757. effect.setMatrix("inverseViewProjection", invViewProjection);
  68758. effect.setMatrix("prevViewProjection", prevViewProjection);
  68759. prevViewProjection = viewProjection;
  68760. screenSize.x = _this.motionBlurPostProcess.width;
  68761. screenSize.y = _this.motionBlurPostProcess.height;
  68762. effect.setVector2("screenSize", screenSize);
  68763. motionScale = scene.getEngine().getFps() / 60.0;
  68764. effect.setFloat("motionScale", motionScale);
  68765. effect.setFloat("motionStrength", _this.motionStrength);
  68766. effect.setTexture("depthSampler", _this._getDepthTexture());
  68767. };
  68768. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  68769. };
  68770. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  68771. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  68772. var renderer = this._scene.enableGeometryBufferRenderer();
  68773. return renderer.getGBuffer().textures[0];
  68774. }
  68775. return this._scene.enableDepthRenderer().getDepthMap();
  68776. };
  68777. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  68778. for (var i = 0; i < this._cameras.length; i++) {
  68779. var camera = this._cameras[i];
  68780. if (this.originalPostProcess) {
  68781. this.originalPostProcess.dispose(camera);
  68782. }
  68783. if (this.downSampleX4PostProcess) {
  68784. this.downSampleX4PostProcess.dispose(camera);
  68785. }
  68786. if (this.brightPassPostProcess) {
  68787. this.brightPassPostProcess.dispose(camera);
  68788. }
  68789. if (this.textureAdderPostProcess) {
  68790. this.textureAdderPostProcess.dispose(camera);
  68791. }
  68792. if (this.textureAdderFinalPostProcess) {
  68793. this.textureAdderFinalPostProcess.dispose(camera);
  68794. }
  68795. if (this.volumetricLightPostProcess) {
  68796. this.volumetricLightPostProcess.dispose(camera);
  68797. }
  68798. if (this.volumetricLightSmoothXPostProcess) {
  68799. this.volumetricLightSmoothXPostProcess.dispose(camera);
  68800. }
  68801. if (this.volumetricLightSmoothYPostProcess) {
  68802. this.volumetricLightSmoothYPostProcess.dispose(camera);
  68803. }
  68804. if (this.volumetricLightMergePostProces) {
  68805. this.volumetricLightMergePostProces.dispose(camera);
  68806. }
  68807. if (this.volumetricLightFinalPostProcess) {
  68808. this.volumetricLightFinalPostProcess.dispose(camera);
  68809. }
  68810. if (this.lensFlarePostProcess) {
  68811. this.lensFlarePostProcess.dispose(camera);
  68812. }
  68813. if (this.lensFlareComposePostProcess) {
  68814. this.lensFlareComposePostProcess.dispose(camera);
  68815. }
  68816. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  68817. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  68818. }
  68819. if (this.luminancePostProcess) {
  68820. this.luminancePostProcess.dispose(camera);
  68821. }
  68822. if (this.hdrPostProcess) {
  68823. this.hdrPostProcess.dispose(camera);
  68824. }
  68825. if (this.hdrFinalPostProcess) {
  68826. this.hdrFinalPostProcess.dispose(camera);
  68827. }
  68828. if (this.depthOfFieldPostProcess) {
  68829. this.depthOfFieldPostProcess.dispose(camera);
  68830. }
  68831. if (this.motionBlurPostProcess) {
  68832. this.motionBlurPostProcess.dispose(camera);
  68833. }
  68834. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  68835. this.blurHPostProcesses[j].dispose(camera);
  68836. }
  68837. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  68838. this.blurVPostProcesses[j].dispose(camera);
  68839. }
  68840. }
  68841. this.originalPostProcess = null;
  68842. this.downSampleX4PostProcess = null;
  68843. this.brightPassPostProcess = null;
  68844. this.textureAdderPostProcess = null;
  68845. this.textureAdderFinalPostProcess = null;
  68846. this.volumetricLightPostProcess = null;
  68847. this.volumetricLightSmoothXPostProcess = null;
  68848. this.volumetricLightSmoothYPostProcess = null;
  68849. this.volumetricLightMergePostProces = null;
  68850. this.volumetricLightFinalPostProcess = null;
  68851. this.lensFlarePostProcess = null;
  68852. this.lensFlareComposePostProcess = null;
  68853. this.luminancePostProcess = null;
  68854. this.hdrPostProcess = null;
  68855. this.hdrFinalPostProcess = null;
  68856. this.depthOfFieldPostProcess = null;
  68857. this.motionBlurPostProcess = null;
  68858. this.luminanceDownSamplePostProcesses = [];
  68859. this.blurHPostProcesses = [];
  68860. this.blurVPostProcesses = [];
  68861. };
  68862. // Dispose
  68863. StandardRenderingPipeline.prototype.dispose = function () {
  68864. this._disposePostProcesses();
  68865. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68866. _super.prototype.dispose.call(this);
  68867. };
  68868. // Serialize rendering pipeline
  68869. StandardRenderingPipeline.prototype.serialize = function () {
  68870. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  68871. serializationObject.customType = "StandardRenderingPipeline";
  68872. return serializationObject;
  68873. };
  68874. /**
  68875. * Static members
  68876. */
  68877. // Parse serialized pipeline
  68878. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  68879. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  68880. };
  68881. // Luminance steps
  68882. StandardRenderingPipeline.LuminanceSteps = 6;
  68883. __decorate([
  68884. BABYLON.serialize()
  68885. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  68886. __decorate([
  68887. BABYLON.serialize()
  68888. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  68889. __decorate([
  68890. BABYLON.serialize()
  68891. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  68892. __decorate([
  68893. BABYLON.serialize()
  68894. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  68895. __decorate([
  68896. BABYLON.serializeAsTexture("lensTexture")
  68897. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  68898. __decorate([
  68899. BABYLON.serialize()
  68900. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  68901. __decorate([
  68902. BABYLON.serialize()
  68903. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  68904. __decorate([
  68905. BABYLON.serialize()
  68906. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  68907. __decorate([
  68908. BABYLON.serialize()
  68909. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  68910. __decorate([
  68911. BABYLON.serialize()
  68912. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  68913. __decorate([
  68914. BABYLON.serialize()
  68915. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  68916. __decorate([
  68917. BABYLON.serializeAsTexture("lensColorTexture")
  68918. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  68919. __decorate([
  68920. BABYLON.serialize()
  68921. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  68922. __decorate([
  68923. BABYLON.serialize()
  68924. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  68925. __decorate([
  68926. BABYLON.serialize()
  68927. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  68928. __decorate([
  68929. BABYLON.serialize()
  68930. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  68931. __decorate([
  68932. BABYLON.serializeAsTexture("lensStarTexture")
  68933. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  68934. __decorate([
  68935. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  68936. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  68937. __decorate([
  68938. BABYLON.serialize()
  68939. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  68940. __decorate([
  68941. BABYLON.serialize()
  68942. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  68943. __decorate([
  68944. BABYLON.serialize()
  68945. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  68946. __decorate([
  68947. BABYLON.serialize()
  68948. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  68949. __decorate([
  68950. BABYLON.serialize()
  68951. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  68952. __decorate([
  68953. BABYLON.serialize()
  68954. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  68955. __decorate([
  68956. BABYLON.serialize()
  68957. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  68958. __decorate([
  68959. BABYLON.serialize()
  68960. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  68961. __decorate([
  68962. BABYLON.serialize()
  68963. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  68964. __decorate([
  68965. BABYLON.serialize()
  68966. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  68967. __decorate([
  68968. BABYLON.serialize()
  68969. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  68970. __decorate([
  68971. BABYLON.serialize()
  68972. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  68973. return StandardRenderingPipeline;
  68974. }(BABYLON.PostProcessRenderPipeline));
  68975. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  68976. })(BABYLON || (BABYLON = {}));
  68977. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  68978. var BABYLON;
  68979. (function (BABYLON) {
  68980. var FxaaPostProcess = /** @class */ (function (_super) {
  68981. __extends(FxaaPostProcess, _super);
  68982. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68983. if (camera === void 0) { camera = null; }
  68984. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68985. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  68986. _this.onApplyObservable.add(function (effect) {
  68987. var texelSize = _this.texelSize;
  68988. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  68989. });
  68990. return _this;
  68991. }
  68992. return FxaaPostProcess;
  68993. }(BABYLON.PostProcess));
  68994. BABYLON.FxaaPostProcess = FxaaPostProcess;
  68995. })(BABYLON || (BABYLON = {}));
  68996. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  68997. var BABYLON;
  68998. (function (BABYLON) {
  68999. /**
  69000. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  69001. */
  69002. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  69003. __extends(ChromaticAberrationPostProcess, _super);
  69004. /**
  69005. * Creates a new instance of @see ChromaticAberrationPostProcess
  69006. * @param name The name of the effect.
  69007. * @param screenWidth The width of the screen to apply the effect on.
  69008. * @param screenHeight The height of the screen to apply the effect on.
  69009. * @param options The required width/height ratio to downsize to before computing the render pass.
  69010. * @param camera The camera to apply the render pass to.
  69011. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69012. * @param engine The engine which the post process will be applied. (default: current engine)
  69013. * @param reusable If the post process can be reused on the same frame. (default: false)
  69014. * @param textureType Type of textures used when performing the post process. (default: 0)
  69015. * @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)
  69016. */
  69017. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69018. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69019. if (blockCompilation === void 0) { blockCompilation = false; }
  69020. 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;
  69021. /**
  69022. * The amount of seperation of rgb channels (default: 30)
  69023. */
  69024. _this.aberrationAmount = 30;
  69025. /**
  69026. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  69027. */
  69028. _this.radialIntensity = 0;
  69029. /**
  69030. * 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))
  69031. */
  69032. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  69033. /**
  69034. * 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))
  69035. */
  69036. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  69037. _this.onApplyObservable.add(function (effect) {
  69038. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  69039. effect.setFloat('screen_width', screenWidth);
  69040. effect.setFloat('screen_height', screenHeight);
  69041. effect.setFloat('radialIntensity', _this.radialIntensity);
  69042. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  69043. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  69044. });
  69045. return _this;
  69046. }
  69047. return ChromaticAberrationPostProcess;
  69048. }(BABYLON.PostProcess));
  69049. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  69050. })(BABYLON || (BABYLON = {}));
  69051. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  69052. var BABYLON;
  69053. (function (BABYLON) {
  69054. /**
  69055. * The SharpenPostProcess applies a sharpen kernel to every pixel
  69056. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  69057. */
  69058. var SharpenPostProcess = /** @class */ (function (_super) {
  69059. __extends(SharpenPostProcess, _super);
  69060. /**
  69061. * Creates a new instance of @see ConvolutionPostProcess
  69062. * @param name The name of the effect.
  69063. * @param options The required width/height ratio to downsize to before computing the render pass.
  69064. * @param camera The camera to apply the render pass to.
  69065. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69066. * @param engine The engine which the post process will be applied. (default: current engine)
  69067. * @param reusable If the post process can be reused on the same frame. (default: false)
  69068. * @param textureType Type of textures used when performing the post process. (default: 0)
  69069. * @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)
  69070. */
  69071. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69072. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69073. if (blockCompilation === void 0) { blockCompilation = false; }
  69074. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69075. /**
  69076. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  69077. */
  69078. _this.colorAmount = 1.0;
  69079. /**
  69080. * How much sharpness should be applied (default: 0.3)
  69081. */
  69082. _this.edgeAmount = 0.3;
  69083. _this.onApply = function (effect) {
  69084. effect.setFloat2("screenSize", _this.width, _this.height);
  69085. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  69086. };
  69087. return _this;
  69088. }
  69089. return SharpenPostProcess;
  69090. }(BABYLON.PostProcess));
  69091. BABYLON.SharpenPostProcess = SharpenPostProcess;
  69092. })(BABYLON || (BABYLON = {}));
  69093. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  69094. var BABYLON;
  69095. (function (BABYLON) {
  69096. /**
  69097. * The Blur Post Process which blurs an image based on a kernel and direction.
  69098. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  69099. */
  69100. var BlurPostProcess = /** @class */ (function (_super) {
  69101. __extends(BlurPostProcess, _super);
  69102. /**
  69103. * Creates a new instance of @see BlurPostProcess
  69104. * @param name The name of the effect.
  69105. * @param direction The direction in which to blur the image.
  69106. * @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.
  69107. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69108. * @param camera The camera to apply the render pass to.
  69109. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69110. * @param engine The engine which the post process will be applied. (default: current engine)
  69111. * @param reusable If the post process can be reused on the same frame. (default: false)
  69112. * @param textureType Type of textures used when performing the post process. (default: 0)
  69113. * @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)
  69114. */
  69115. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  69116. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69117. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69118. if (defines === void 0) { defines = ""; }
  69119. if (blockCompilation === void 0) { blockCompilation = false; }
  69120. 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;
  69121. _this.direction = direction;
  69122. _this.blockCompilation = blockCompilation;
  69123. _this._packedFloat = false;
  69124. _this._staticDefines = "";
  69125. _this._staticDefines = defines;
  69126. _this.onApplyObservable.add(function (effect) {
  69127. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  69128. });
  69129. _this.kernel = kernel;
  69130. return _this;
  69131. }
  69132. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  69133. /**
  69134. * Gets the length in pixels of the blur sample region
  69135. */
  69136. get: function () {
  69137. return this._idealKernel;
  69138. },
  69139. /**
  69140. * Sets the length in pixels of the blur sample region
  69141. */
  69142. set: function (v) {
  69143. if (this._idealKernel === v) {
  69144. return;
  69145. }
  69146. v = Math.max(v, 1);
  69147. this._idealKernel = v;
  69148. this._kernel = this._nearestBestKernel(v);
  69149. if (!this.blockCompilation) {
  69150. this._updateParameters();
  69151. }
  69152. },
  69153. enumerable: true,
  69154. configurable: true
  69155. });
  69156. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  69157. /**
  69158. * Gets wether or not the blur is unpacking/repacking floats
  69159. */
  69160. get: function () {
  69161. return this._packedFloat;
  69162. },
  69163. /**
  69164. * Sets wether or not the blur needs to unpack/repack floats
  69165. */
  69166. set: function (v) {
  69167. if (this._packedFloat === v) {
  69168. return;
  69169. }
  69170. this._packedFloat = v;
  69171. if (!this.blockCompilation) {
  69172. this._updateParameters();
  69173. }
  69174. },
  69175. enumerable: true,
  69176. configurable: true
  69177. });
  69178. /**
  69179. * Updates the effect with the current post process compile time values and recompiles the shader.
  69180. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69181. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69182. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69183. * @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
  69184. * @param onCompiled Called when the shader has been compiled.
  69185. * @param onError Called if there is an error when compiling a shader.
  69186. */
  69187. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69188. if (defines === void 0) { defines = null; }
  69189. if (uniforms === void 0) { uniforms = null; }
  69190. if (samplers === void 0) { samplers = null; }
  69191. this._updateParameters(onCompiled, onError);
  69192. };
  69193. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  69194. // Generate sampling offsets and weights
  69195. var N = this._kernel;
  69196. var centerIndex = (N - 1) / 2;
  69197. // Generate Gaussian sampling weights over kernel
  69198. var offsets = [];
  69199. var weights = [];
  69200. var totalWeight = 0;
  69201. for (var i = 0; i < N; i++) {
  69202. var u = i / (N - 1);
  69203. var w = this._gaussianWeight(u * 2.0 - 1);
  69204. offsets[i] = (i - centerIndex);
  69205. weights[i] = w;
  69206. totalWeight += w;
  69207. }
  69208. // Normalize weights
  69209. for (var i = 0; i < weights.length; i++) {
  69210. weights[i] /= totalWeight;
  69211. }
  69212. // Optimize: combine samples to take advantage of hardware linear sampling
  69213. // Walk from left to center, combining pairs (symmetrically)
  69214. var linearSamplingWeights = [];
  69215. var linearSamplingOffsets = [];
  69216. var linearSamplingMap = [];
  69217. for (var i = 0; i <= centerIndex; i += 2) {
  69218. var j = Math.min(i + 1, Math.floor(centerIndex));
  69219. var singleCenterSample = i === j;
  69220. if (singleCenterSample) {
  69221. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69222. }
  69223. else {
  69224. var sharedCell = j === centerIndex;
  69225. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  69226. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  69227. if (offsetLinear === 0) {
  69228. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69229. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  69230. }
  69231. else {
  69232. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  69233. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  69234. }
  69235. }
  69236. }
  69237. for (var i = 0; i < linearSamplingMap.length; i++) {
  69238. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  69239. linearSamplingWeights[i] = linearSamplingMap[i].w;
  69240. }
  69241. // Replace with optimized
  69242. offsets = linearSamplingOffsets;
  69243. weights = linearSamplingWeights;
  69244. // Generate shaders
  69245. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  69246. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  69247. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  69248. var defines = "";
  69249. defines += this._staticDefines;
  69250. for (var i = 0; i < varyingCount; i++) {
  69251. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  69252. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  69253. }
  69254. var depCount = 0;
  69255. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  69256. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  69257. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  69258. depCount++;
  69259. }
  69260. if (this.packedFloat) {
  69261. defines += "#define PACKEDFLOAT 1";
  69262. }
  69263. _super.prototype.updateEffect.call(this, defines, null, null, {
  69264. varyingCount: varyingCount,
  69265. depCount: depCount
  69266. }, onCompiled, onError);
  69267. };
  69268. /**
  69269. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  69270. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  69271. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  69272. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  69273. * The gaps between physical kernels are compensated for in the weighting of the samples
  69274. * @param idealKernel Ideal blur kernel.
  69275. * @return Nearest best kernel.
  69276. */
  69277. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  69278. var v = Math.round(idealKernel);
  69279. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  69280. var k = _a[_i];
  69281. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  69282. return Math.max(k, 3);
  69283. }
  69284. }
  69285. return Math.max(v, 3);
  69286. };
  69287. /**
  69288. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  69289. * @param x The point on the Gaussian distribution to sample.
  69290. * @return the value of the Gaussian function at x.
  69291. */
  69292. BlurPostProcess.prototype._gaussianWeight = function (x) {
  69293. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  69294. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  69295. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  69296. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  69297. // truncated at around 1.3% of peak strength.
  69298. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  69299. var sigma = (1 / 3);
  69300. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  69301. var exponent = -((x * x) / (2.0 * sigma * sigma));
  69302. var weight = (1.0 / denominator) * Math.exp(exponent);
  69303. return weight;
  69304. };
  69305. /**
  69306. * Generates a string that can be used as a floating point number in GLSL.
  69307. * @param x Value to print.
  69308. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  69309. * @return GLSL float string.
  69310. */
  69311. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  69312. if (decimalFigures === void 0) { decimalFigures = 8; }
  69313. return x.toFixed(decimalFigures).replace(/0+$/, '');
  69314. };
  69315. return BlurPostProcess;
  69316. }(BABYLON.PostProcess));
  69317. BABYLON.BlurPostProcess = BlurPostProcess;
  69318. })(BABYLON || (BABYLON = {}));
  69319. //# sourceMappingURL=babylon.blurPostProcess.js.map
  69320. var BABYLON;
  69321. (function (BABYLON) {
  69322. /**
  69323. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  69324. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  69325. * based on samples that have a large difference in distance than the center pixel.
  69326. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69327. */
  69328. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  69329. __extends(DepthOfFieldBlurPostProcess, _super);
  69330. /**
  69331. * Creates a new instance of @see CircleOfConfusionPostProcess
  69332. * @param name The name of the effect.
  69333. * @param scene The scene the effect belongs to.
  69334. * @param direction The direction the blur should be applied.
  69335. * @param kernel The size of the kernel used to blur.
  69336. * @param options The required width/height ratio to downsize to before computing the render pass.
  69337. * @param camera The camera to apply the render pass to.
  69338. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  69339. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  69340. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69341. * @param engine The engine which the post process will be applied. (default: current engine)
  69342. * @param reusable If the post process can be reused on the same frame. (default: false)
  69343. * @param textureType Type of textures used when performing the post process. (default: 0)
  69344. * @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)
  69345. */
  69346. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  69347. if (imageToBlur === void 0) { imageToBlur = null; }
  69348. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69349. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69350. if (blockCompilation === void 0) { blockCompilation = false; }
  69351. 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;
  69352. _this.direction = direction;
  69353. _this.onApplyObservable.add(function (effect) {
  69354. if (imageToBlur != null) {
  69355. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  69356. }
  69357. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  69358. if (scene.activeCamera) {
  69359. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  69360. }
  69361. });
  69362. return _this;
  69363. }
  69364. return DepthOfFieldBlurPostProcess;
  69365. }(BABYLON.BlurPostProcess));
  69366. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  69367. })(BABYLON || (BABYLON = {}));
  69368. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  69369. var BABYLON;
  69370. (function (BABYLON) {
  69371. /**
  69372. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  69373. */
  69374. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  69375. __extends(DepthOfFieldMergePostProcess, _super);
  69376. /**
  69377. * Creates a new instance of @see CircleOfConfusionPostProcess
  69378. * @param name The name of the effect.
  69379. * @param original The non-blurred image to be modified
  69380. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  69381. * @param blurSteps Incrimental bluring post processes.
  69382. * @param options The required width/height ratio to downsize to before computing the render pass.
  69383. * @param camera The camera to apply the render pass to.
  69384. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69385. * @param engine The engine which the post process will be applied. (default: current engine)
  69386. * @param reusable If the post process can be reused on the same frame. (default: false)
  69387. * @param textureType Type of textures used when performing the post process. (default: 0)
  69388. * @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)
  69389. */
  69390. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69391. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69392. if (blockCompilation === void 0) { blockCompilation = false; }
  69393. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  69394. _this.blurSteps = blurSteps;
  69395. _this.onApplyObservable.add(function (effect) {
  69396. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  69397. effect.setTextureFromPostProcess("originalSampler", original);
  69398. blurSteps.forEach(function (step, index) {
  69399. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  69400. });
  69401. });
  69402. if (!blockCompilation) {
  69403. _this.updateEffect();
  69404. }
  69405. return _this;
  69406. }
  69407. /**
  69408. * Updates the effect with the current post process compile time values and recompiles the shader.
  69409. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69410. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69411. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69412. * @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
  69413. * @param onCompiled Called when the shader has been compiled.
  69414. * @param onError Called if there is an error when compiling a shader.
  69415. */
  69416. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69417. if (defines === void 0) { defines = null; }
  69418. if (uniforms === void 0) { uniforms = null; }
  69419. if (samplers === void 0) { samplers = null; }
  69420. _super.prototype.updateEffect.call(this, defines ? defines : "#define BLUR_LEVEL " + this.blurSteps.length + "\n", uniforms, samplers, indexParameters, onCompiled, onError);
  69421. };
  69422. return DepthOfFieldMergePostProcess;
  69423. }(BABYLON.PostProcess));
  69424. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  69425. })(BABYLON || (BABYLON = {}));
  69426. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  69427. var BABYLON;
  69428. (function (BABYLON) {
  69429. /**
  69430. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  69431. */
  69432. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  69433. __extends(CircleOfConfusionPostProcess, _super);
  69434. /**
  69435. * Creates a new instance of @see CircleOfConfusionPostProcess
  69436. * @param name The name of the effect.
  69437. * @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.
  69438. * @param options The required width/height ratio to downsize to before computing the render pass.
  69439. * @param camera The camera to apply the render pass to.
  69440. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69441. * @param engine The engine which the post process will be applied. (default: current engine)
  69442. * @param reusable If the post process can be reused on the same frame. (default: false)
  69443. * @param textureType Type of textures used when performing the post process. (default: 0)
  69444. * @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)
  69445. */
  69446. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69447. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69448. if (blockCompilation === void 0) { blockCompilation = false; }
  69449. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69450. /**
  69451. * 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.
  69452. */
  69453. _this.lensSize = 50;
  69454. /**
  69455. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  69456. */
  69457. _this.fStop = 1.4;
  69458. /**
  69459. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  69460. */
  69461. _this.focusDistance = 2000;
  69462. /**
  69463. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  69464. */
  69465. _this.focalLength = 50;
  69466. _this._depthTexture = null;
  69467. _this._depthTexture = depthTexture;
  69468. _this.onApplyObservable.add(function (effect) {
  69469. if (!_this._depthTexture) {
  69470. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  69471. return;
  69472. }
  69473. effect.setTexture("depthSampler", _this._depthTexture);
  69474. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  69475. var aperture = _this.lensSize / _this.fStop;
  69476. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  69477. effect.setFloat('focusDistance', _this.focusDistance);
  69478. effect.setFloat('cocPrecalculation', cocPrecalculation);
  69479. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  69480. });
  69481. return _this;
  69482. }
  69483. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  69484. /**
  69485. * 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.
  69486. */
  69487. set: function (value) {
  69488. this._depthTexture = value;
  69489. },
  69490. enumerable: true,
  69491. configurable: true
  69492. });
  69493. return CircleOfConfusionPostProcess;
  69494. }(BABYLON.PostProcess));
  69495. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  69496. })(BABYLON || (BABYLON = {}));
  69497. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  69498. var BABYLON;
  69499. (function (BABYLON) {
  69500. /**
  69501. * Specifies the level of max blur that should be applied when using the depth of field effect
  69502. */
  69503. var DepthOfFieldEffectBlurLevel;
  69504. (function (DepthOfFieldEffectBlurLevel) {
  69505. /**
  69506. * Subtle blur
  69507. */
  69508. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  69509. /**
  69510. * Medium blur
  69511. */
  69512. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  69513. /**
  69514. * Large blur
  69515. */
  69516. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  69517. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  69518. ;
  69519. /**
  69520. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  69521. */
  69522. var DepthOfFieldEffect = /** @class */ (function (_super) {
  69523. __extends(DepthOfFieldEffect, _super);
  69524. /**
  69525. * Creates a new instance of @see DepthOfFieldEffect
  69526. * @param scene The scene the effect belongs to.
  69527. * @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.
  69528. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  69529. * @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)
  69530. */
  69531. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  69532. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  69533. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  69534. if (blockCompilation === void 0) { blockCompilation = false; }
  69535. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  69536. return _this._effects;
  69537. }, true) || this;
  69538. _this._effects = [];
  69539. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  69540. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69541. // Capture circle of confusion texture
  69542. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69543. _this._depthOfFieldPass.autoClear = false;
  69544. // 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)
  69545. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  69546. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69547. _this._depthOfFieldBlurY = [];
  69548. _this._depthOfFieldBlurX = [];
  69549. var blurCount = 1;
  69550. var kernelSize = 15;
  69551. switch (blurLevel) {
  69552. case DepthOfFieldEffectBlurLevel.High: {
  69553. blurCount = 3;
  69554. kernelSize = 51;
  69555. break;
  69556. }
  69557. case DepthOfFieldEffectBlurLevel.Medium: {
  69558. blurCount = 2;
  69559. kernelSize = 31;
  69560. break;
  69561. }
  69562. default: {
  69563. kernelSize = 15;
  69564. blurCount = 1;
  69565. break;
  69566. }
  69567. }
  69568. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  69569. for (var i = 0; i < blurCount; i++) {
  69570. 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);
  69571. blurY.autoClear = false;
  69572. 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);
  69573. blurX.autoClear = false;
  69574. _this._depthOfFieldBlurY.push(blurY);
  69575. _this._depthOfFieldBlurX.push(blurX);
  69576. }
  69577. // Merge blurred images with original image based on circleOfConfusion
  69578. _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);
  69579. _this._depthOfFieldMerge.autoClear = false;
  69580. // Set all post processes on the effect.
  69581. _this._effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  69582. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  69583. _this._effects.push(_this._depthOfFieldBlurY[i]);
  69584. _this._effects.push(_this._depthOfFieldBlurX[i]);
  69585. }
  69586. _this._effects.push(_this._depthOfFieldMerge);
  69587. return _this;
  69588. }
  69589. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  69590. get: function () {
  69591. return this._circleOfConfusion.focalLength;
  69592. },
  69593. /**
  69594. * The focal the length of the camera used in the effect
  69595. */
  69596. set: function (value) {
  69597. this._circleOfConfusion.focalLength = value;
  69598. },
  69599. enumerable: true,
  69600. configurable: true
  69601. });
  69602. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  69603. get: function () {
  69604. return this._circleOfConfusion.fStop;
  69605. },
  69606. /**
  69607. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  69608. */
  69609. set: function (value) {
  69610. this._circleOfConfusion.fStop = value;
  69611. },
  69612. enumerable: true,
  69613. configurable: true
  69614. });
  69615. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  69616. get: function () {
  69617. return this._circleOfConfusion.focusDistance;
  69618. },
  69619. /**
  69620. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  69621. */
  69622. set: function (value) {
  69623. this._circleOfConfusion.focusDistance = value;
  69624. },
  69625. enumerable: true,
  69626. configurable: true
  69627. });
  69628. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  69629. get: function () {
  69630. return this._circleOfConfusion.lensSize;
  69631. },
  69632. /**
  69633. * 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.
  69634. */
  69635. set: function (value) {
  69636. this._circleOfConfusion.lensSize = value;
  69637. },
  69638. enumerable: true,
  69639. configurable: true
  69640. });
  69641. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  69642. /**
  69643. * 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.
  69644. */
  69645. set: function (value) {
  69646. this._circleOfConfusion.depthTexture = value;
  69647. },
  69648. enumerable: true,
  69649. configurable: true
  69650. });
  69651. /**
  69652. * Disposes each of the internal effects for a given camera.
  69653. * @param camera The camera to dispose the effect on.
  69654. */
  69655. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  69656. this._depthOfFieldPass.dispose(camera);
  69657. this._circleOfConfusion.dispose(camera);
  69658. this._depthOfFieldBlurX.forEach(function (element) {
  69659. element.dispose(camera);
  69660. });
  69661. this._depthOfFieldBlurY.forEach(function (element) {
  69662. element.dispose(camera);
  69663. });
  69664. this._depthOfFieldMerge.dispose(camera);
  69665. };
  69666. /**
  69667. * Internal
  69668. */
  69669. DepthOfFieldEffect.prototype._updateEffects = function () {
  69670. for (var effect in this._effects) {
  69671. this._effects[effect].updateEffect();
  69672. }
  69673. };
  69674. /**
  69675. * Internal
  69676. * @returns if all the contained post processes are ready.
  69677. */
  69678. DepthOfFieldEffect.prototype._isReady = function () {
  69679. for (var effect in this._effects) {
  69680. if (!this._effects[effect].isReady()) {
  69681. return false;
  69682. }
  69683. }
  69684. return true;
  69685. };
  69686. return DepthOfFieldEffect;
  69687. }(BABYLON.PostProcessRenderEffect));
  69688. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  69689. })(BABYLON || (BABYLON = {}));
  69690. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  69691. var BABYLON;
  69692. (function (BABYLON) {
  69693. /**
  69694. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  69695. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  69696. */
  69697. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  69698. __extends(DefaultRenderingPipeline, _super);
  69699. /**
  69700. * @constructor
  69701. * @param {string} name - The rendering pipeline name
  69702. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  69703. * @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)
  69704. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  69705. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  69706. */
  69707. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  69708. if (automaticBuild === void 0) { automaticBuild = true; }
  69709. var _this = _super.call(this, scene.getEngine(), name) || this;
  69710. _this._originalCameras = [];
  69711. /**
  69712. * ID of the sharpen post process,
  69713. */
  69714. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  69715. /**
  69716. * ID of the pass post process used for bloom,
  69717. */
  69718. _this.PassPostProcessId = "PassPostProcessEffect";
  69719. /**
  69720. * ID of the highlight post process used for bloom,
  69721. */
  69722. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  69723. /**
  69724. * ID of the blurX post process used for bloom,
  69725. */
  69726. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  69727. /**
  69728. * ID of the blurY post process used for bloom,
  69729. */
  69730. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  69731. /**
  69732. * ID of the copy back post process used for bloom,
  69733. */
  69734. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  69735. /**
  69736. * ID of the image processing post process;
  69737. */
  69738. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  69739. /**
  69740. * ID of the Fast Approximate Anti-Aliasing post process;
  69741. */
  69742. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  69743. /**
  69744. * ID of the final merge post process;
  69745. */
  69746. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  69747. /**
  69748. * ID of the chromatic aberration post process,
  69749. */
  69750. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  69751. /**
  69752. * Animations which can be used to tweak settings over a period of time
  69753. */
  69754. _this.animations = [];
  69755. // Values
  69756. _this._sharpenEnabled = false;
  69757. _this._bloomEnabled = false;
  69758. _this._depthOfFieldEnabled = false;
  69759. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  69760. _this._fxaaEnabled = false;
  69761. _this._msaaEnabled = false;
  69762. _this._imageProcessingEnabled = true;
  69763. _this._bloomScale = 0.6;
  69764. _this._chromaticAberrationEnabled = false;
  69765. _this._buildAllowed = true;
  69766. /**
  69767. * Specifies the size of the bloom blur kernel, relative to the final output size
  69768. */
  69769. _this.bloomKernel = 64;
  69770. /**
  69771. * Specifies the weight of the bloom in the final rendering
  69772. */
  69773. _this._bloomWeight = 0.15;
  69774. _this._prevPostProcess = null;
  69775. _this._prevPrevPostProcess = null;
  69776. _this._cameras = cameras || [];
  69777. _this._originalCameras = _this._cameras.slice();
  69778. _this._buildAllowed = automaticBuild;
  69779. // Initialize
  69780. _this._scene = scene;
  69781. var caps = _this._scene.getEngine().getCaps();
  69782. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  69783. // Misc
  69784. if (_this._hdr) {
  69785. if (caps.textureHalfFloatRender) {
  69786. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69787. }
  69788. else if (caps.textureFloatRender) {
  69789. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69790. }
  69791. }
  69792. else {
  69793. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69794. }
  69795. // Attach
  69796. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69797. var engine = _this._scene.getEngine();
  69798. // Create post processes before hand so they can be modified before enabled.
  69799. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  69800. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  69801. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  69802. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  69803. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  69804. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  69805. _this._buildPipeline();
  69806. return _this;
  69807. }
  69808. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  69809. get: function () {
  69810. return this._sharpenEnabled;
  69811. },
  69812. /**
  69813. * Enable or disable the sharpen process from the pipeline
  69814. */
  69815. set: function (enabled) {
  69816. if (this._sharpenEnabled === enabled) {
  69817. return;
  69818. }
  69819. this._sharpenEnabled = enabled;
  69820. this._buildPipeline();
  69821. },
  69822. enumerable: true,
  69823. configurable: true
  69824. });
  69825. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  69826. get: function () {
  69827. return this._bloomWeight;
  69828. },
  69829. /**
  69830. * The strength of the bloom.
  69831. */
  69832. set: function (value) {
  69833. if (this._bloomWeight === value) {
  69834. return;
  69835. }
  69836. this._bloomWeight = value;
  69837. if (this._hdr && this.copyBack) {
  69838. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  69839. }
  69840. },
  69841. enumerable: true,
  69842. configurable: true
  69843. });
  69844. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  69845. get: function () {
  69846. return this._bloomScale;
  69847. },
  69848. /**
  69849. * The scale of the bloom, lower value will provide better performance.
  69850. */
  69851. set: function (value) {
  69852. if (this._bloomScale === value) {
  69853. return;
  69854. }
  69855. this._bloomScale = value;
  69856. this._buildPipeline();
  69857. },
  69858. enumerable: true,
  69859. configurable: true
  69860. });
  69861. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  69862. get: function () {
  69863. return this._bloomEnabled;
  69864. },
  69865. /**
  69866. * Enable or disable the bloom from the pipeline
  69867. */
  69868. set: function (enabled) {
  69869. if (this._bloomEnabled === enabled) {
  69870. return;
  69871. }
  69872. this._bloomEnabled = enabled;
  69873. this._buildPipeline();
  69874. },
  69875. enumerable: true,
  69876. configurable: true
  69877. });
  69878. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  69879. /**
  69880. * If the depth of field is enabled.
  69881. */
  69882. get: function () {
  69883. return this._depthOfFieldEnabled;
  69884. },
  69885. set: function (enabled) {
  69886. if (this._depthOfFieldEnabled === enabled) {
  69887. return;
  69888. }
  69889. this._depthOfFieldEnabled = enabled;
  69890. this._buildPipeline();
  69891. },
  69892. enumerable: true,
  69893. configurable: true
  69894. });
  69895. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  69896. /**
  69897. * Blur level of the depth of field effect. (Higher blur will effect performance)
  69898. */
  69899. get: function () {
  69900. return this._depthOfFieldBlurLevel;
  69901. },
  69902. set: function (value) {
  69903. if (this._depthOfFieldBlurLevel === value) {
  69904. return;
  69905. }
  69906. this._depthOfFieldBlurLevel = value;
  69907. // recreate dof and dispose old as this setting is not dynamic
  69908. var oldDof = this.depthOfField;
  69909. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  69910. this.depthOfField.focalLength = oldDof.focalLength;
  69911. this.depthOfField.focusDistance = oldDof.focusDistance;
  69912. this.depthOfField.fStop = oldDof.fStop;
  69913. this.depthOfField.lensSize = oldDof.lensSize;
  69914. for (var i = 0; i < this._cameras.length; i++) {
  69915. oldDof.disposeEffects(this._cameras[i]);
  69916. }
  69917. this._buildPipeline();
  69918. },
  69919. enumerable: true,
  69920. configurable: true
  69921. });
  69922. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  69923. get: function () {
  69924. return this._fxaaEnabled;
  69925. },
  69926. /**
  69927. * If the anti aliasing is enabled.
  69928. */
  69929. set: function (enabled) {
  69930. if (this._fxaaEnabled === enabled) {
  69931. return;
  69932. }
  69933. this._fxaaEnabled = enabled;
  69934. this._buildPipeline();
  69935. },
  69936. enumerable: true,
  69937. configurable: true
  69938. });
  69939. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  69940. get: function () {
  69941. return this._msaaEnabled;
  69942. },
  69943. /**
  69944. * If the multisample anti-aliasing is enabled.
  69945. */
  69946. set: function (enabled) {
  69947. if (this._msaaEnabled === enabled) {
  69948. return;
  69949. }
  69950. this._msaaEnabled = enabled;
  69951. this._buildPipeline();
  69952. },
  69953. enumerable: true,
  69954. configurable: true
  69955. });
  69956. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  69957. get: function () {
  69958. return this._imageProcessingEnabled;
  69959. },
  69960. /**
  69961. * If image processing is enabled.
  69962. */
  69963. set: function (enabled) {
  69964. if (this._imageProcessingEnabled === enabled) {
  69965. return;
  69966. }
  69967. this._imageProcessingEnabled = enabled;
  69968. this._buildPipeline();
  69969. },
  69970. enumerable: true,
  69971. configurable: true
  69972. });
  69973. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  69974. get: function () {
  69975. return this._chromaticAberrationEnabled;
  69976. },
  69977. /**
  69978. * Enable or disable the chromaticAberration process from the pipeline
  69979. */
  69980. set: function (enabled) {
  69981. if (this._chromaticAberrationEnabled === enabled) {
  69982. return;
  69983. }
  69984. this._chromaticAberrationEnabled = enabled;
  69985. this._buildPipeline();
  69986. },
  69987. enumerable: true,
  69988. configurable: true
  69989. });
  69990. /**
  69991. * Force the compilation of the entire pipeline.
  69992. */
  69993. DefaultRenderingPipeline.prototype.prepare = function () {
  69994. var previousState = this._buildAllowed;
  69995. this._buildAllowed = true;
  69996. this._buildPipeline();
  69997. this._buildAllowed = previousState;
  69998. };
  69999. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  70000. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  70001. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  70002. postProcess.autoClear = false;
  70003. }
  70004. else {
  70005. postProcess.autoClear = true;
  70006. }
  70007. if (!skipTextureSharing) {
  70008. if (this._prevPrevPostProcess) {
  70009. postProcess.shareOutputWith(this._prevPrevPostProcess);
  70010. }
  70011. else {
  70012. postProcess.useOwnOutput();
  70013. }
  70014. if (this._prevPostProcess) {
  70015. this._prevPrevPostProcess = this._prevPostProcess;
  70016. }
  70017. this._prevPostProcess = postProcess;
  70018. }
  70019. };
  70020. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  70021. var _this = this;
  70022. if (!this._buildAllowed) {
  70023. return;
  70024. }
  70025. var engine = this._scene.getEngine();
  70026. this._disposePostProcesses();
  70027. if (this._cameras !== null) {
  70028. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  70029. // get back cameras to be used to reattach pipeline
  70030. this._cameras = this._originalCameras.slice();
  70031. }
  70032. this._reset();
  70033. this._prevPostProcess = null;
  70034. this._prevPrevPostProcess = null;
  70035. if (this.sharpenEnabled) {
  70036. if (!this.sharpen.isReady()) {
  70037. this.sharpen.updateEffect();
  70038. }
  70039. this.addEffect(this._sharpenEffect);
  70040. this._setAutoClearAndTextureSharing(this.sharpen);
  70041. }
  70042. if (this.depthOfFieldEnabled) {
  70043. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  70044. this.depthOfField.depthTexture = depthTexture;
  70045. if (!this.depthOfField._isReady()) {
  70046. this.depthOfField._updateEffects();
  70047. }
  70048. this.addEffect(this.depthOfField);
  70049. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  70050. }
  70051. if (this.bloomEnabled) {
  70052. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70053. this._setAutoClearAndTextureSharing(this.pass, true);
  70054. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  70055. if (!this._hdr) {
  70056. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70057. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  70058. this.highlights.autoClear = false;
  70059. this.highlights.alwaysForcePOT = true;
  70060. }
  70061. 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);
  70062. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  70063. this.blurX.alwaysForcePOT = true;
  70064. this.blurX.autoClear = false;
  70065. this.blurX.onActivateObservable.add(function () {
  70066. var dw = _this.blurX.width / engine.getRenderWidth(true);
  70067. _this.blurX.kernel = _this.bloomKernel * dw;
  70068. });
  70069. 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);
  70070. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  70071. this.blurY.alwaysForcePOT = true;
  70072. this.blurY.autoClear = false;
  70073. this.blurY.onActivateObservable.add(function () {
  70074. var dh = _this.blurY.height / engine.getRenderHeight(true);
  70075. _this.blurY.kernel = _this.bloomKernel * dh;
  70076. });
  70077. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70078. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  70079. this.copyBack.alwaysForcePOT = true;
  70080. if (this._hdr) {
  70081. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  70082. var w = this.bloomWeight;
  70083. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  70084. }
  70085. else {
  70086. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  70087. }
  70088. this.copyBack.autoClear = false;
  70089. }
  70090. if (this._imageProcessingEnabled) {
  70091. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70092. if (this._hdr) {
  70093. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  70094. }
  70095. else {
  70096. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  70097. }
  70098. }
  70099. if (this._hdr && this.imageProcessing) {
  70100. this.finalMerge = this.imageProcessing;
  70101. }
  70102. else {
  70103. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70104. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  70105. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  70106. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  70107. }
  70108. if (this.bloomEnabled) {
  70109. if (this._hdr) {
  70110. this.copyBack.shareOutputWith(this.blurX);
  70111. if (this.imageProcessing) {
  70112. this.imageProcessing.shareOutputWith(this.pass);
  70113. this.imageProcessing.autoClear = false;
  70114. }
  70115. else {
  70116. this.finalMerge.shareOutputWith(this.pass);
  70117. }
  70118. }
  70119. else {
  70120. this.finalMerge.shareOutputWith(this.pass);
  70121. }
  70122. }
  70123. if (this.fxaaEnabled) {
  70124. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70125. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  70126. this._setAutoClearAndTextureSharing(this.fxaa);
  70127. }
  70128. if (this.chromaticAberrationEnabled) {
  70129. if (!this.chromaticAberration.isReady()) {
  70130. this.chromaticAberration.updateEffect();
  70131. }
  70132. this.addEffect(this._chromaticAberrationEffect);
  70133. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  70134. }
  70135. if (this._cameras !== null) {
  70136. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  70137. }
  70138. if (this.msaaEnabled) {
  70139. if (!this._enableMSAAOnFirstPostProcess()) {
  70140. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  70141. }
  70142. }
  70143. };
  70144. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  70145. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  70146. for (var i = 0; i < this._cameras.length; i++) {
  70147. var camera = this._cameras[i];
  70148. if (this.pass) {
  70149. this.pass.dispose(camera);
  70150. }
  70151. if (this.highlights) {
  70152. this.highlights.dispose(camera);
  70153. }
  70154. if (this.blurX) {
  70155. this.blurX.dispose(camera);
  70156. }
  70157. if (this.blurY) {
  70158. this.blurY.dispose(camera);
  70159. }
  70160. if (this.copyBack) {
  70161. this.copyBack.dispose(camera);
  70162. }
  70163. if (this.imageProcessing) {
  70164. this.imageProcessing.dispose(camera);
  70165. }
  70166. if (this.fxaa) {
  70167. this.fxaa.dispose(camera);
  70168. }
  70169. if (this.finalMerge) {
  70170. this.finalMerge.dispose(camera);
  70171. }
  70172. // These are created in the constructor and should not be disposed on every pipeline change
  70173. if (disposeNonRecreated) {
  70174. if (this.sharpen) {
  70175. this.sharpen.dispose(camera);
  70176. }
  70177. if (this.depthOfField) {
  70178. this.depthOfField.disposeEffects(camera);
  70179. }
  70180. if (this.chromaticAberration) {
  70181. this.chromaticAberration.dispose(camera);
  70182. }
  70183. }
  70184. }
  70185. this.pass = null;
  70186. this.highlights = null;
  70187. this.blurX = null;
  70188. this.blurY = null;
  70189. this.copyBack = null;
  70190. this.imageProcessing = null;
  70191. this.fxaa = null;
  70192. this.finalMerge = null;
  70193. if (disposeNonRecreated) {
  70194. this.sharpen = null;
  70195. this.depthOfField = null;
  70196. this.chromaticAberration = null;
  70197. }
  70198. };
  70199. /**
  70200. * Dispose of the pipeline and stop all post processes
  70201. */
  70202. DefaultRenderingPipeline.prototype.dispose = function () {
  70203. this._disposePostProcesses(true);
  70204. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  70205. _super.prototype.dispose.call(this);
  70206. };
  70207. /**
  70208. * Serialize the rendering pipeline (Used when exporting)
  70209. * @returns the serialized object
  70210. */
  70211. DefaultRenderingPipeline.prototype.serialize = function () {
  70212. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  70213. serializationObject.customType = "DefaultRenderingPipeline";
  70214. return serializationObject;
  70215. };
  70216. /**
  70217. * Parse the serialized pipeline
  70218. * @param source Source pipeline.
  70219. * @param scene The scene to load the pipeline to.
  70220. * @param rootUrl The URL of the serialized pipeline.
  70221. * @returns An instantiated pipeline from the serialized object.
  70222. */
  70223. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  70224. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  70225. };
  70226. __decorate([
  70227. BABYLON.serialize()
  70228. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  70229. __decorate([
  70230. BABYLON.serialize()
  70231. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  70232. __decorate([
  70233. BABYLON.serialize()
  70234. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  70235. __decorate([
  70236. BABYLON.serialize()
  70237. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  70238. __decorate([
  70239. BABYLON.serialize()
  70240. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  70241. __decorate([
  70242. BABYLON.serialize()
  70243. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  70244. __decorate([
  70245. BABYLON.serialize()
  70246. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  70247. __decorate([
  70248. BABYLON.serialize()
  70249. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  70250. __decorate([
  70251. BABYLON.serialize()
  70252. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  70253. __decorate([
  70254. BABYLON.serialize()
  70255. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  70256. __decorate([
  70257. BABYLON.serialize()
  70258. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  70259. __decorate([
  70260. BABYLON.serialize()
  70261. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  70262. __decorate([
  70263. BABYLON.serialize()
  70264. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  70265. return DefaultRenderingPipeline;
  70266. }(BABYLON.PostProcessRenderPipeline));
  70267. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  70268. })(BABYLON || (BABYLON = {}));
  70269. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  70270. var BABYLON;
  70271. (function (BABYLON) {
  70272. /**
  70273. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  70274. */
  70275. var GeometryBufferRenderer = /** @class */ (function () {
  70276. /**
  70277. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  70278. * @param scene The scene the buffer belongs to
  70279. * @param ratio How big is the buffer related to the main canvas.
  70280. */
  70281. function GeometryBufferRenderer(scene, ratio) {
  70282. if (ratio === void 0) { ratio = 1; }
  70283. this._enablePosition = false;
  70284. this._scene = scene;
  70285. this._ratio = ratio;
  70286. // Render target
  70287. this._createRenderTargets();
  70288. }
  70289. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  70290. /**
  70291. * Set the render list (meshes to be rendered) used in the G buffer.
  70292. */
  70293. set: function (meshes) {
  70294. this._multiRenderTarget.renderList = meshes;
  70295. },
  70296. enumerable: true,
  70297. configurable: true
  70298. });
  70299. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  70300. /**
  70301. * Gets wether or not G buffer are supported by the running hardware.
  70302. * This requires draw buffer supports
  70303. */
  70304. get: function () {
  70305. return this._multiRenderTarget.isSupported;
  70306. },
  70307. enumerable: true,
  70308. configurable: true
  70309. });
  70310. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  70311. /**
  70312. * Gets wether or not position are enabled for the G buffer.
  70313. */
  70314. get: function () {
  70315. return this._enablePosition;
  70316. },
  70317. /**
  70318. * Sets wether or not position are enabled for the G buffer.
  70319. */
  70320. set: function (enable) {
  70321. this._enablePosition = enable;
  70322. this.dispose();
  70323. this._createRenderTargets();
  70324. },
  70325. enumerable: true,
  70326. configurable: true
  70327. });
  70328. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  70329. /**
  70330. * Gets the scene associated with the buffer.
  70331. */
  70332. get: function () {
  70333. return this._scene;
  70334. },
  70335. enumerable: true,
  70336. configurable: true
  70337. });
  70338. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  70339. /**
  70340. * Gets the ratio used by the buffer during its creation.
  70341. * How big is the buffer related to the main canvas.
  70342. */
  70343. get: function () {
  70344. return this._ratio;
  70345. },
  70346. enumerable: true,
  70347. configurable: true
  70348. });
  70349. /**
  70350. * Checks wether everything is ready to render a submesh to the G buffer.
  70351. * @param subMesh the submesh to check readiness for
  70352. * @param useInstances is the mesh drawn using instance or not
  70353. * @returns true if ready otherwise false
  70354. */
  70355. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  70356. var material = subMesh.getMaterial();
  70357. if (material && material.disableDepthWrite) {
  70358. return false;
  70359. }
  70360. var defines = [];
  70361. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  70362. var mesh = subMesh.getMesh();
  70363. // Alpha test
  70364. if (material && material.needAlphaTesting()) {
  70365. defines.push("#define ALPHATEST");
  70366. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70367. attribs.push(BABYLON.VertexBuffer.UVKind);
  70368. defines.push("#define UV1");
  70369. }
  70370. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70371. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70372. defines.push("#define UV2");
  70373. }
  70374. }
  70375. // Buffers
  70376. if (this._enablePosition) {
  70377. defines.push("#define POSITION");
  70378. }
  70379. // Bones
  70380. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70381. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70382. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70383. if (mesh.numBoneInfluencers > 4) {
  70384. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70385. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70386. }
  70387. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70388. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  70389. }
  70390. else {
  70391. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70392. }
  70393. // Instances
  70394. if (useInstances) {
  70395. defines.push("#define INSTANCES");
  70396. attribs.push("world0");
  70397. attribs.push("world1");
  70398. attribs.push("world2");
  70399. attribs.push("world3");
  70400. }
  70401. // Get correct effect
  70402. var join = defines.join("\n");
  70403. if (this._cachedDefines !== join) {
  70404. this._cachedDefines = join;
  70405. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  70406. }
  70407. return this._effect.isReady();
  70408. };
  70409. /**
  70410. * Gets the current underlying G Buffer.
  70411. * @returns the buffer
  70412. */
  70413. GeometryBufferRenderer.prototype.getGBuffer = function () {
  70414. return this._multiRenderTarget;
  70415. };
  70416. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  70417. /**
  70418. * Gets the number of samples used to render the buffer (anti aliasing).
  70419. */
  70420. get: function () {
  70421. return this._multiRenderTarget.samples;
  70422. },
  70423. /**
  70424. * Sets the number of samples used to render the buffer (anti aliasing).
  70425. */
  70426. set: function (value) {
  70427. this._multiRenderTarget.samples = value;
  70428. },
  70429. enumerable: true,
  70430. configurable: true
  70431. });
  70432. /**
  70433. * Disposes the renderer and frees up associated resources.
  70434. */
  70435. GeometryBufferRenderer.prototype.dispose = function () {
  70436. this.getGBuffer().dispose();
  70437. };
  70438. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  70439. var _this = this;
  70440. var engine = this._scene.getEngine();
  70441. var count = this._enablePosition ? 3 : 2;
  70442. 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 });
  70443. if (!this.isSupported) {
  70444. return;
  70445. }
  70446. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70447. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70448. this._multiRenderTarget.refreshRate = 1;
  70449. this._multiRenderTarget.renderParticles = false;
  70450. this._multiRenderTarget.renderList = null;
  70451. // set default depth value to 1.0 (far away)
  70452. this._multiRenderTarget.onClearObservable.add(function (engine) {
  70453. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  70454. });
  70455. // Custom render function
  70456. var renderSubMesh = function (subMesh) {
  70457. var mesh = subMesh.getRenderingMesh();
  70458. var scene = _this._scene;
  70459. var engine = scene.getEngine();
  70460. var material = subMesh.getMaterial();
  70461. if (!material) {
  70462. return;
  70463. }
  70464. // Culling
  70465. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  70466. // Managing instances
  70467. var batch = mesh._getInstancesRenderList(subMesh._id);
  70468. if (batch.mustReturn) {
  70469. return;
  70470. }
  70471. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  70472. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  70473. engine.enableEffect(_this._effect);
  70474. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  70475. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  70476. _this._effect.setMatrix("view", scene.getViewMatrix());
  70477. // Alpha test
  70478. if (material && material.needAlphaTesting()) {
  70479. var alphaTexture = material.getAlphaTestTexture();
  70480. if (alphaTexture) {
  70481. _this._effect.setTexture("diffuseSampler", alphaTexture);
  70482. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70483. }
  70484. }
  70485. // Bones
  70486. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  70487. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70488. }
  70489. // Draw
  70490. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  70491. }
  70492. };
  70493. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70494. var index;
  70495. if (depthOnlySubMeshes.length) {
  70496. engine.setColorWrite(false);
  70497. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70498. renderSubMesh(depthOnlySubMeshes.data[index]);
  70499. }
  70500. engine.setColorWrite(true);
  70501. }
  70502. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70503. renderSubMesh(opaqueSubMeshes.data[index]);
  70504. }
  70505. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70506. renderSubMesh(alphaTestSubMeshes.data[index]);
  70507. }
  70508. };
  70509. };
  70510. return GeometryBufferRenderer;
  70511. }());
  70512. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  70513. })(BABYLON || (BABYLON = {}));
  70514. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  70515. var BABYLON;
  70516. (function (BABYLON) {
  70517. var RefractionPostProcess = /** @class */ (function (_super) {
  70518. __extends(RefractionPostProcess, _super);
  70519. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  70520. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  70521. _this.color = color;
  70522. _this.depth = depth;
  70523. _this.colorLevel = colorLevel;
  70524. _this._ownRefractionTexture = true;
  70525. _this.onActivateObservable.add(function (cam) {
  70526. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  70527. });
  70528. _this.onApplyObservable.add(function (effect) {
  70529. effect.setColor3("baseColor", _this.color);
  70530. effect.setFloat("depth", _this.depth);
  70531. effect.setFloat("colorLevel", _this.colorLevel);
  70532. effect.setTexture("refractionSampler", _this._refTexture);
  70533. });
  70534. return _this;
  70535. }
  70536. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  70537. /**
  70538. * Gets or sets the refraction texture
  70539. * Please note that you are responsible for disposing the texture if you set it manually
  70540. */
  70541. get: function () {
  70542. return this._refTexture;
  70543. },
  70544. set: function (value) {
  70545. if (this._refTexture && this._ownRefractionTexture) {
  70546. this._refTexture.dispose();
  70547. }
  70548. this._refTexture = value;
  70549. this._ownRefractionTexture = false;
  70550. },
  70551. enumerable: true,
  70552. configurable: true
  70553. });
  70554. // Methods
  70555. RefractionPostProcess.prototype.dispose = function (camera) {
  70556. if (this._refTexture && this._ownRefractionTexture) {
  70557. this._refTexture.dispose();
  70558. this._refTexture = null;
  70559. }
  70560. _super.prototype.dispose.call(this, camera);
  70561. };
  70562. return RefractionPostProcess;
  70563. }(BABYLON.PostProcess));
  70564. BABYLON.RefractionPostProcess = RefractionPostProcess;
  70565. })(BABYLON || (BABYLON = {}));
  70566. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  70567. var BABYLON;
  70568. (function (BABYLON) {
  70569. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  70570. __extends(BlackAndWhitePostProcess, _super);
  70571. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  70572. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  70573. _this.degree = 1;
  70574. _this.onApplyObservable.add(function (effect) {
  70575. effect.setFloat("degree", _this.degree);
  70576. });
  70577. return _this;
  70578. }
  70579. return BlackAndWhitePostProcess;
  70580. }(BABYLON.PostProcess));
  70581. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  70582. })(BABYLON || (BABYLON = {}));
  70583. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  70584. var BABYLON;
  70585. (function (BABYLON) {
  70586. /**
  70587. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  70588. * input texture to perform effects such as edge detection or sharpening
  70589. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  70590. */
  70591. var ConvolutionPostProcess = /** @class */ (function (_super) {
  70592. __extends(ConvolutionPostProcess, _super);
  70593. /**
  70594. * Creates a new instance of @see ConvolutionPostProcess
  70595. * @param name The name of the effect.
  70596. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  70597. * @param options The required width/height ratio to downsize to before computing the render pass.
  70598. * @param camera The camera to apply the render pass to.
  70599. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70600. * @param engine The engine which the post process will be applied. (default: current engine)
  70601. * @param reusable If the post process can be reused on the same frame. (default: false)
  70602. * @param textureType Type of textures used when performing the post process. (default: 0)
  70603. */
  70604. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  70605. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70606. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  70607. _this.kernel = kernel;
  70608. _this.onApply = function (effect) {
  70609. effect.setFloat2("screenSize", _this.width, _this.height);
  70610. effect.setArray("kernel", _this.kernel);
  70611. };
  70612. return _this;
  70613. }
  70614. // Statics
  70615. /**
  70616. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70617. */
  70618. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  70619. /**
  70620. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70621. */
  70622. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  70623. /**
  70624. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70625. */
  70626. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  70627. /**
  70628. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70629. */
  70630. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  70631. /**
  70632. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70633. */
  70634. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  70635. /**
  70636. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70637. */
  70638. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  70639. return ConvolutionPostProcess;
  70640. }(BABYLON.PostProcess));
  70641. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  70642. })(BABYLON || (BABYLON = {}));
  70643. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  70644. var BABYLON;
  70645. (function (BABYLON) {
  70646. var FilterPostProcess = /** @class */ (function (_super) {
  70647. __extends(FilterPostProcess, _super);
  70648. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  70649. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  70650. _this.kernelMatrix = kernelMatrix;
  70651. _this.onApply = function (effect) {
  70652. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  70653. };
  70654. return _this;
  70655. }
  70656. return FilterPostProcess;
  70657. }(BABYLON.PostProcess));
  70658. BABYLON.FilterPostProcess = FilterPostProcess;
  70659. })(BABYLON || (BABYLON = {}));
  70660. //# sourceMappingURL=babylon.filterPostProcess.js.map
  70661. var BABYLON;
  70662. (function (BABYLON) {
  70663. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  70664. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  70665. __extends(VolumetricLightScatteringPostProcess, _super);
  70666. /**
  70667. * @constructor
  70668. * @param {string} name - The post-process name
  70669. * @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)
  70670. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  70671. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  70672. * @param {number} samples - The post-process quality, default 100
  70673. * @param {number} samplingMode - The post-process filtering mode
  70674. * @param {BABYLON.Engine} engine - The babylon engine
  70675. * @param {boolean} reusable - If the post-process is reusable
  70676. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  70677. */
  70678. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  70679. if (samples === void 0) { samples = 100; }
  70680. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70681. 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;
  70682. _this._screenCoordinates = BABYLON.Vector2.Zero();
  70683. /**
  70684. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  70685. * @type {Vector3}
  70686. */
  70687. _this.customMeshPosition = BABYLON.Vector3.Zero();
  70688. /**
  70689. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  70690. * @type {boolean}
  70691. */
  70692. _this.useCustomMeshPosition = false;
  70693. /**
  70694. * If the post-process should inverse the light scattering direction
  70695. * @type {boolean}
  70696. */
  70697. _this.invert = true;
  70698. /**
  70699. * Array containing the excluded meshes not rendered in the internal pass
  70700. */
  70701. _this.excludedMeshes = new Array();
  70702. /**
  70703. * Controls the overall intensity of the post-process
  70704. * @type {number}
  70705. */
  70706. _this.exposure = 0.3;
  70707. /**
  70708. * Dissipates each sample's contribution in range [0, 1]
  70709. * @type {number}
  70710. */
  70711. _this.decay = 0.96815;
  70712. /**
  70713. * Controls the overall intensity of each sample
  70714. * @type {number}
  70715. */
  70716. _this.weight = 0.58767;
  70717. /**
  70718. * Controls the density of each sample
  70719. * @type {number}
  70720. */
  70721. _this.density = 0.926;
  70722. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  70723. engine = scene.getEngine();
  70724. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  70725. // Configure mesh
  70726. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  70727. // Configure
  70728. _this._createPass(scene, ratio.passRatio || ratio);
  70729. _this.onActivate = function (camera) {
  70730. if (!_this.isSupported) {
  70731. _this.dispose(camera);
  70732. }
  70733. _this.onActivate = null;
  70734. };
  70735. _this.onApplyObservable.add(function (effect) {
  70736. _this._updateMeshScreenCoordinates(scene);
  70737. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  70738. effect.setFloat("exposure", _this.exposure);
  70739. effect.setFloat("decay", _this.decay);
  70740. effect.setFloat("weight", _this.weight);
  70741. effect.setFloat("density", _this.density);
  70742. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  70743. });
  70744. return _this;
  70745. }
  70746. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  70747. get: function () {
  70748. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  70749. return false;
  70750. },
  70751. set: function (useDiffuseColor) {
  70752. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  70753. },
  70754. enumerable: true,
  70755. configurable: true
  70756. });
  70757. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  70758. return "VolumetricLightScatteringPostProcess";
  70759. };
  70760. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  70761. var mesh = subMesh.getMesh();
  70762. // Render this.mesh as default
  70763. if (mesh === this.mesh && mesh.material) {
  70764. return mesh.material.isReady(mesh);
  70765. }
  70766. var defines = [];
  70767. var attribs = [BABYLON.VertexBuffer.PositionKind];
  70768. var material = subMesh.getMaterial();
  70769. // Alpha test
  70770. if (material) {
  70771. if (material.needAlphaTesting()) {
  70772. defines.push("#define ALPHATEST");
  70773. }
  70774. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70775. attribs.push(BABYLON.VertexBuffer.UVKind);
  70776. defines.push("#define UV1");
  70777. }
  70778. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70779. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70780. defines.push("#define UV2");
  70781. }
  70782. }
  70783. // Bones
  70784. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70785. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70786. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70787. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70788. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  70789. }
  70790. else {
  70791. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70792. }
  70793. // Instances
  70794. if (useInstances) {
  70795. defines.push("#define INSTANCES");
  70796. attribs.push("world0");
  70797. attribs.push("world1");
  70798. attribs.push("world2");
  70799. attribs.push("world3");
  70800. }
  70801. // Get correct effect
  70802. var join = defines.join("\n");
  70803. if (this._cachedDefines !== join) {
  70804. this._cachedDefines = join;
  70805. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  70806. }
  70807. return this._volumetricLightScatteringPass.isReady();
  70808. };
  70809. /**
  70810. * Sets the new light position for light scattering effect
  70811. * @param {BABYLON.Vector3} The new custom light position
  70812. */
  70813. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  70814. this.customMeshPosition = position;
  70815. };
  70816. /**
  70817. * Returns the light position for light scattering effect
  70818. * @return {BABYLON.Vector3} The custom light position
  70819. */
  70820. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  70821. return this.customMeshPosition;
  70822. };
  70823. /**
  70824. * Disposes the internal assets and detaches the post-process from the camera
  70825. */
  70826. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  70827. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  70828. if (rttIndex !== -1) {
  70829. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  70830. }
  70831. this._volumetricLightScatteringRTT.dispose();
  70832. _super.prototype.dispose.call(this, camera);
  70833. };
  70834. /**
  70835. * Returns the render target texture used by the post-process
  70836. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  70837. */
  70838. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  70839. return this._volumetricLightScatteringRTT;
  70840. };
  70841. // Private methods
  70842. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  70843. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  70844. return true;
  70845. }
  70846. return false;
  70847. };
  70848. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  70849. var _this = this;
  70850. var engine = scene.getEngine();
  70851. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70852. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70853. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70854. this._volumetricLightScatteringRTT.renderList = null;
  70855. this._volumetricLightScatteringRTT.renderParticles = false;
  70856. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  70857. var camera = this.getCamera();
  70858. if (camera) {
  70859. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  70860. }
  70861. else {
  70862. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  70863. }
  70864. // Custom render function for submeshes
  70865. var renderSubMesh = function (subMesh) {
  70866. var mesh = subMesh.getRenderingMesh();
  70867. if (_this._meshExcluded(mesh)) {
  70868. return;
  70869. }
  70870. var material = subMesh.getMaterial();
  70871. if (!material) {
  70872. return;
  70873. }
  70874. var scene = mesh.getScene();
  70875. var engine = scene.getEngine();
  70876. // Culling
  70877. engine.setState(material.backFaceCulling);
  70878. // Managing instances
  70879. var batch = mesh._getInstancesRenderList(subMesh._id);
  70880. if (batch.mustReturn) {
  70881. return;
  70882. }
  70883. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  70884. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  70885. var effect = _this._volumetricLightScatteringPass;
  70886. if (mesh === _this.mesh) {
  70887. if (subMesh.effect) {
  70888. effect = subMesh.effect;
  70889. }
  70890. else {
  70891. effect = material.getEffect();
  70892. }
  70893. }
  70894. engine.enableEffect(effect);
  70895. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  70896. if (mesh === _this.mesh) {
  70897. material.bind(mesh.getWorldMatrix(), mesh);
  70898. }
  70899. else {
  70900. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  70901. // Alpha test
  70902. if (material && material.needAlphaTesting()) {
  70903. var alphaTexture = material.getAlphaTestTexture();
  70904. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  70905. if (alphaTexture) {
  70906. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70907. }
  70908. }
  70909. // Bones
  70910. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  70911. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70912. }
  70913. }
  70914. // Draw
  70915. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  70916. }
  70917. };
  70918. // Render target texture callbacks
  70919. var savedSceneClearColor;
  70920. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  70921. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  70922. savedSceneClearColor = scene.clearColor;
  70923. scene.clearColor = sceneClearColor;
  70924. });
  70925. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  70926. scene.clearColor = savedSceneClearColor;
  70927. });
  70928. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70929. var engine = scene.getEngine();
  70930. var index;
  70931. if (depthOnlySubMeshes.length) {
  70932. engine.setColorWrite(false);
  70933. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70934. renderSubMesh(depthOnlySubMeshes.data[index]);
  70935. }
  70936. engine.setColorWrite(true);
  70937. }
  70938. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70939. renderSubMesh(opaqueSubMeshes.data[index]);
  70940. }
  70941. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70942. renderSubMesh(alphaTestSubMeshes.data[index]);
  70943. }
  70944. if (transparentSubMeshes.length) {
  70945. // Sort sub meshes
  70946. for (index = 0; index < transparentSubMeshes.length; index++) {
  70947. var submesh = transparentSubMeshes.data[index];
  70948. var boundingInfo = submesh.getBoundingInfo();
  70949. if (boundingInfo && scene.activeCamera) {
  70950. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  70951. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  70952. }
  70953. }
  70954. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  70955. sortedArray.sort(function (a, b) {
  70956. // Alpha index first
  70957. if (a._alphaIndex > b._alphaIndex) {
  70958. return 1;
  70959. }
  70960. if (a._alphaIndex < b._alphaIndex) {
  70961. return -1;
  70962. }
  70963. // Then distance to camera
  70964. if (a._distanceToCamera < b._distanceToCamera) {
  70965. return 1;
  70966. }
  70967. if (a._distanceToCamera > b._distanceToCamera) {
  70968. return -1;
  70969. }
  70970. return 0;
  70971. });
  70972. // Render sub meshes
  70973. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  70974. for (index = 0; index < sortedArray.length; index++) {
  70975. renderSubMesh(sortedArray[index]);
  70976. }
  70977. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  70978. }
  70979. };
  70980. };
  70981. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  70982. var transform = scene.getTransformMatrix();
  70983. var meshPosition;
  70984. if (this.useCustomMeshPosition) {
  70985. meshPosition = this.customMeshPosition;
  70986. }
  70987. else if (this.attachedNode) {
  70988. meshPosition = this.attachedNode.position;
  70989. }
  70990. else {
  70991. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  70992. }
  70993. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  70994. this._screenCoordinates.x = pos.x / this._viewPort.width;
  70995. this._screenCoordinates.y = pos.y / this._viewPort.height;
  70996. if (this.invert)
  70997. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  70998. };
  70999. // Static methods
  71000. /**
  71001. * Creates a default mesh for the Volumeric Light Scattering post-process
  71002. * @param {string} The mesh name
  71003. * @param {BABYLON.Scene} The scene where to create the mesh
  71004. * @return {BABYLON.Mesh} the default mesh
  71005. */
  71006. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  71007. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  71008. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  71009. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  71010. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  71011. mesh.material = material;
  71012. return mesh;
  71013. };
  71014. __decorate([
  71015. BABYLON.serializeAsVector3()
  71016. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  71017. __decorate([
  71018. BABYLON.serialize()
  71019. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  71020. __decorate([
  71021. BABYLON.serialize()
  71022. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  71023. __decorate([
  71024. BABYLON.serializeAsMeshReference()
  71025. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  71026. __decorate([
  71027. BABYLON.serialize()
  71028. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  71029. __decorate([
  71030. BABYLON.serialize()
  71031. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  71032. __decorate([
  71033. BABYLON.serialize()
  71034. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  71035. __decorate([
  71036. BABYLON.serialize()
  71037. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  71038. __decorate([
  71039. BABYLON.serialize()
  71040. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  71041. return VolumetricLightScatteringPostProcess;
  71042. }(BABYLON.PostProcess));
  71043. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  71044. })(BABYLON || (BABYLON = {}));
  71045. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  71046. //
  71047. // This post-process allows the modification of rendered colors by using
  71048. // a 'look-up table' (LUT). This effect is also called Color Grading.
  71049. //
  71050. // The object needs to be provided an url to a texture containing the color
  71051. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  71052. // Use an image editing software to tweak the LUT to match your needs.
  71053. //
  71054. // For an example of a color LUT, see here:
  71055. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  71056. // For explanations on color grading, see here:
  71057. // http://udn.epicgames.com/Three/ColorGrading.html
  71058. //
  71059. var BABYLON;
  71060. (function (BABYLON) {
  71061. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  71062. __extends(ColorCorrectionPostProcess, _super);
  71063. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  71064. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  71065. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71066. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  71067. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71068. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71069. _this.onApply = function (effect) {
  71070. effect.setTexture("colorTable", _this._colorTableTexture);
  71071. };
  71072. return _this;
  71073. }
  71074. return ColorCorrectionPostProcess;
  71075. }(BABYLON.PostProcess));
  71076. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  71077. })(BABYLON || (BABYLON = {}));
  71078. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  71079. var BABYLON;
  71080. (function (BABYLON) {
  71081. var TonemappingOperator;
  71082. (function (TonemappingOperator) {
  71083. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  71084. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  71085. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  71086. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  71087. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  71088. ;
  71089. var TonemapPostProcess = /** @class */ (function (_super) {
  71090. __extends(TonemapPostProcess, _super);
  71091. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  71092. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71093. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71094. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  71095. _this._operator = _operator;
  71096. _this.exposureAdjustment = exposureAdjustment;
  71097. var defines = "#define ";
  71098. if (_this._operator === TonemappingOperator.Hable)
  71099. defines += "HABLE_TONEMAPPING";
  71100. else if (_this._operator === TonemappingOperator.Reinhard)
  71101. defines += "REINHARD_TONEMAPPING";
  71102. else if (_this._operator === TonemappingOperator.HejiDawson)
  71103. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  71104. else if (_this._operator === TonemappingOperator.Photographic)
  71105. defines += "PHOTOGRAPHIC_TONEMAPPING";
  71106. //sadly a second call to create the effect.
  71107. _this.updateEffect(defines);
  71108. _this.onApply = function (effect) {
  71109. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  71110. };
  71111. return _this;
  71112. }
  71113. return TonemapPostProcess;
  71114. }(BABYLON.PostProcess));
  71115. BABYLON.TonemapPostProcess = TonemapPostProcess;
  71116. })(BABYLON || (BABYLON = {}));
  71117. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  71118. var BABYLON;
  71119. (function (BABYLON) {
  71120. var DisplayPassPostProcess = /** @class */ (function (_super) {
  71121. __extends(DisplayPassPostProcess, _super);
  71122. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  71123. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  71124. }
  71125. return DisplayPassPostProcess;
  71126. }(BABYLON.PostProcess));
  71127. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  71128. })(BABYLON || (BABYLON = {}));
  71129. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  71130. var BABYLON;
  71131. (function (BABYLON) {
  71132. var HighlightsPostProcess = /** @class */ (function (_super) {
  71133. __extends(HighlightsPostProcess, _super);
  71134. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  71135. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71136. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  71137. }
  71138. return HighlightsPostProcess;
  71139. }(BABYLON.PostProcess));
  71140. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  71141. })(BABYLON || (BABYLON = {}));
  71142. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  71143. var BABYLON;
  71144. (function (BABYLON) {
  71145. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  71146. __extends(ImageProcessingPostProcess, _super);
  71147. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  71148. if (camera === void 0) { camera = null; }
  71149. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71150. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  71151. _this._fromLinearSpace = true;
  71152. /**
  71153. * Defines cache preventing GC.
  71154. */
  71155. _this._defines = {
  71156. IMAGEPROCESSING: false,
  71157. VIGNETTE: false,
  71158. VIGNETTEBLENDMODEMULTIPLY: false,
  71159. VIGNETTEBLENDMODEOPAQUE: false,
  71160. TONEMAPPING: false,
  71161. CONTRAST: false,
  71162. COLORCURVES: false,
  71163. COLORGRADING: false,
  71164. COLORGRADING3D: false,
  71165. FROMLINEARSPACE: false,
  71166. SAMPLER3DGREENDEPTH: false,
  71167. SAMPLER3DBGRMAP: false,
  71168. IMAGEPROCESSINGPOSTPROCESS: false,
  71169. EXPOSURE: false,
  71170. GRAIN: false,
  71171. };
  71172. // Setup the configuration as forced by the constructor. This would then not force the
  71173. // scene materials output in linear space and let untouched the default forward pass.
  71174. if (imageProcessingConfiguration) {
  71175. imageProcessingConfiguration.applyByPostProcess = true;
  71176. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  71177. // This will cause the shader to be compiled
  71178. _this.fromLinearSpace = false;
  71179. }
  71180. else {
  71181. _this._attachImageProcessingConfiguration(null, true);
  71182. _this.imageProcessingConfiguration.applyByPostProcess = true;
  71183. }
  71184. _this.onApply = function (effect) {
  71185. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  71186. };
  71187. return _this;
  71188. }
  71189. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  71190. /**
  71191. * Gets the image processing configuration used either in this material.
  71192. */
  71193. get: function () {
  71194. return this._imageProcessingConfiguration;
  71195. },
  71196. /**
  71197. * Sets the Default image processing configuration used either in the this material.
  71198. *
  71199. * If sets to null, the scene one is in use.
  71200. */
  71201. set: function (value) {
  71202. this._attachImageProcessingConfiguration(value);
  71203. },
  71204. enumerable: true,
  71205. configurable: true
  71206. });
  71207. /**
  71208. * Attaches a new image processing configuration to the PBR Material.
  71209. * @param configuration
  71210. */
  71211. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  71212. var _this = this;
  71213. if (doNotBuild === void 0) { doNotBuild = false; }
  71214. if (configuration === this._imageProcessingConfiguration) {
  71215. return;
  71216. }
  71217. // Detaches observer.
  71218. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  71219. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  71220. }
  71221. // Pick the scene configuration if needed.
  71222. if (!configuration) {
  71223. var scene = null;
  71224. var engine = this.getEngine();
  71225. var camera = this.getCamera();
  71226. if (camera) {
  71227. scene = camera.getScene();
  71228. }
  71229. else if (engine && engine.scenes) {
  71230. var scenes = engine.scenes;
  71231. scene = scenes[scenes.length - 1];
  71232. }
  71233. else {
  71234. scene = BABYLON.Engine.LastCreatedScene;
  71235. }
  71236. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  71237. }
  71238. else {
  71239. this._imageProcessingConfiguration = configuration;
  71240. }
  71241. // Attaches observer.
  71242. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  71243. _this._updateParameters();
  71244. });
  71245. // Ensure the effect will be rebuilt.
  71246. if (!doNotBuild) {
  71247. this._updateParameters();
  71248. }
  71249. };
  71250. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  71251. /**
  71252. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  71253. */
  71254. get: function () {
  71255. return this.imageProcessingConfiguration.colorCurves;
  71256. },
  71257. /**
  71258. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  71259. */
  71260. set: function (value) {
  71261. this.imageProcessingConfiguration.colorCurves = value;
  71262. },
  71263. enumerable: true,
  71264. configurable: true
  71265. });
  71266. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  71267. /**
  71268. * Gets wether the color curves effect is enabled.
  71269. */
  71270. get: function () {
  71271. return this.imageProcessingConfiguration.colorCurvesEnabled;
  71272. },
  71273. /**
  71274. * Sets wether the color curves effect is enabled.
  71275. */
  71276. set: function (value) {
  71277. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  71278. },
  71279. enumerable: true,
  71280. configurable: true
  71281. });
  71282. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  71283. /**
  71284. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  71285. */
  71286. get: function () {
  71287. return this.imageProcessingConfiguration.colorGradingTexture;
  71288. },
  71289. /**
  71290. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  71291. */
  71292. set: function (value) {
  71293. this.imageProcessingConfiguration.colorGradingTexture = value;
  71294. },
  71295. enumerable: true,
  71296. configurable: true
  71297. });
  71298. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  71299. /**
  71300. * Gets wether the color grading effect is enabled.
  71301. */
  71302. get: function () {
  71303. return this.imageProcessingConfiguration.colorGradingEnabled;
  71304. },
  71305. /**
  71306. * Gets wether the color grading effect is enabled.
  71307. */
  71308. set: function (value) {
  71309. this.imageProcessingConfiguration.colorGradingEnabled = value;
  71310. },
  71311. enumerable: true,
  71312. configurable: true
  71313. });
  71314. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  71315. /**
  71316. * Gets exposure used in the effect.
  71317. */
  71318. get: function () {
  71319. return this.imageProcessingConfiguration.exposure;
  71320. },
  71321. /**
  71322. * Sets exposure used in the effect.
  71323. */
  71324. set: function (value) {
  71325. this.imageProcessingConfiguration.exposure = value;
  71326. },
  71327. enumerable: true,
  71328. configurable: true
  71329. });
  71330. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  71331. /**
  71332. * Gets wether tonemapping is enabled or not.
  71333. */
  71334. get: function () {
  71335. return this._imageProcessingConfiguration.toneMappingEnabled;
  71336. },
  71337. /**
  71338. * Sets wether tonemapping is enabled or not
  71339. */
  71340. set: function (value) {
  71341. this._imageProcessingConfiguration.toneMappingEnabled = value;
  71342. },
  71343. enumerable: true,
  71344. configurable: true
  71345. });
  71346. ;
  71347. ;
  71348. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  71349. /**
  71350. * Gets contrast used in the effect.
  71351. */
  71352. get: function () {
  71353. return this.imageProcessingConfiguration.contrast;
  71354. },
  71355. /**
  71356. * Sets contrast used in the effect.
  71357. */
  71358. set: function (value) {
  71359. this.imageProcessingConfiguration.contrast = value;
  71360. },
  71361. enumerable: true,
  71362. configurable: true
  71363. });
  71364. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  71365. /**
  71366. * Gets Vignette stretch size.
  71367. */
  71368. get: function () {
  71369. return this.imageProcessingConfiguration.vignetteStretch;
  71370. },
  71371. /**
  71372. * Sets Vignette stretch size.
  71373. */
  71374. set: function (value) {
  71375. this.imageProcessingConfiguration.vignetteStretch = value;
  71376. },
  71377. enumerable: true,
  71378. configurable: true
  71379. });
  71380. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  71381. /**
  71382. * Gets Vignette centre X Offset.
  71383. */
  71384. get: function () {
  71385. return this.imageProcessingConfiguration.vignetteCentreX;
  71386. },
  71387. /**
  71388. * Sets Vignette centre X Offset.
  71389. */
  71390. set: function (value) {
  71391. this.imageProcessingConfiguration.vignetteCentreX = value;
  71392. },
  71393. enumerable: true,
  71394. configurable: true
  71395. });
  71396. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  71397. /**
  71398. * Gets Vignette centre Y Offset.
  71399. */
  71400. get: function () {
  71401. return this.imageProcessingConfiguration.vignetteCentreY;
  71402. },
  71403. /**
  71404. * Sets Vignette centre Y Offset.
  71405. */
  71406. set: function (value) {
  71407. this.imageProcessingConfiguration.vignetteCentreY = value;
  71408. },
  71409. enumerable: true,
  71410. configurable: true
  71411. });
  71412. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  71413. /**
  71414. * Gets Vignette weight or intensity of the vignette effect.
  71415. */
  71416. get: function () {
  71417. return this.imageProcessingConfiguration.vignetteWeight;
  71418. },
  71419. /**
  71420. * Sets Vignette weight or intensity of the vignette effect.
  71421. */
  71422. set: function (value) {
  71423. this.imageProcessingConfiguration.vignetteWeight = value;
  71424. },
  71425. enumerable: true,
  71426. configurable: true
  71427. });
  71428. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  71429. /**
  71430. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  71431. * if vignetteEnabled is set to true.
  71432. */
  71433. get: function () {
  71434. return this.imageProcessingConfiguration.vignetteColor;
  71435. },
  71436. /**
  71437. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  71438. * if vignetteEnabled is set to true.
  71439. */
  71440. set: function (value) {
  71441. this.imageProcessingConfiguration.vignetteColor = value;
  71442. },
  71443. enumerable: true,
  71444. configurable: true
  71445. });
  71446. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  71447. /**
  71448. * Gets Camera field of view used by the Vignette effect.
  71449. */
  71450. get: function () {
  71451. return this.imageProcessingConfiguration.vignetteCameraFov;
  71452. },
  71453. /**
  71454. * Sets Camera field of view used by the Vignette effect.
  71455. */
  71456. set: function (value) {
  71457. this.imageProcessingConfiguration.vignetteCameraFov = value;
  71458. },
  71459. enumerable: true,
  71460. configurable: true
  71461. });
  71462. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  71463. /**
  71464. * Gets the vignette blend mode allowing different kind of effect.
  71465. */
  71466. get: function () {
  71467. return this.imageProcessingConfiguration.vignetteBlendMode;
  71468. },
  71469. /**
  71470. * Sets the vignette blend mode allowing different kind of effect.
  71471. */
  71472. set: function (value) {
  71473. this.imageProcessingConfiguration.vignetteBlendMode = value;
  71474. },
  71475. enumerable: true,
  71476. configurable: true
  71477. });
  71478. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  71479. /**
  71480. * Gets wether the vignette effect is enabled.
  71481. */
  71482. get: function () {
  71483. return this.imageProcessingConfiguration.vignetteEnabled;
  71484. },
  71485. /**
  71486. * Sets wether the vignette effect is enabled.
  71487. */
  71488. set: function (value) {
  71489. this.imageProcessingConfiguration.vignetteEnabled = value;
  71490. },
  71491. enumerable: true,
  71492. configurable: true
  71493. });
  71494. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  71495. /**
  71496. * Gets wether the grain effect is enabled.
  71497. */
  71498. get: function () {
  71499. return this.imageProcessingConfiguration.grainEnabled;
  71500. },
  71501. /**
  71502. * Sets wether the grain effect is enabled.
  71503. */
  71504. set: function (value) {
  71505. this.imageProcessingConfiguration.grainEnabled = value;
  71506. },
  71507. enumerable: true,
  71508. configurable: true
  71509. });
  71510. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  71511. /**
  71512. * Gets the grain effect's intensity.
  71513. */
  71514. get: function () {
  71515. return this.imageProcessingConfiguration.grainIntensity;
  71516. },
  71517. /**
  71518. * Sets the grain effect's intensity.
  71519. */
  71520. set: function (value) {
  71521. this.imageProcessingConfiguration.grainIntensity = value;
  71522. },
  71523. enumerable: true,
  71524. configurable: true
  71525. });
  71526. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  71527. /**
  71528. * Gets wether the grain effect is animated.
  71529. */
  71530. get: function () {
  71531. return this.imageProcessingConfiguration.grainAnimated;
  71532. },
  71533. /**
  71534. * Sets wether the grain effect is animated.
  71535. */
  71536. set: function (value) {
  71537. this.imageProcessingConfiguration.grainAnimated = value;
  71538. },
  71539. enumerable: true,
  71540. configurable: true
  71541. });
  71542. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  71543. /**
  71544. * Gets wether the input of the processing is in Gamma or Linear Space.
  71545. */
  71546. get: function () {
  71547. return this._fromLinearSpace;
  71548. },
  71549. /**
  71550. * Sets wether the input of the processing is in Gamma or Linear Space.
  71551. */
  71552. set: function (value) {
  71553. if (this._fromLinearSpace === value) {
  71554. return;
  71555. }
  71556. this._fromLinearSpace = value;
  71557. this._updateParameters();
  71558. },
  71559. enumerable: true,
  71560. configurable: true
  71561. });
  71562. ImageProcessingPostProcess.prototype.getClassName = function () {
  71563. return "ImageProcessingPostProcess";
  71564. };
  71565. ImageProcessingPostProcess.prototype._updateParameters = function () {
  71566. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  71567. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  71568. var defines = "";
  71569. for (var define in this._defines) {
  71570. if (this._defines[define]) {
  71571. defines += "#define " + define + ";\r\n";
  71572. }
  71573. }
  71574. var samplers = ["textureSampler"];
  71575. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  71576. var uniforms = ["scale"];
  71577. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  71578. this.updateEffect(defines, uniforms, samplers);
  71579. };
  71580. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  71581. _super.prototype.dispose.call(this, camera);
  71582. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  71583. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  71584. }
  71585. this.imageProcessingConfiguration.applyByPostProcess = false;
  71586. };
  71587. __decorate([
  71588. BABYLON.serialize()
  71589. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  71590. return ImageProcessingPostProcess;
  71591. }(BABYLON.PostProcess));
  71592. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  71593. })(BABYLON || (BABYLON = {}));
  71594. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  71595. var BABYLON;
  71596. (function (BABYLON) {
  71597. var Bone = /** @class */ (function (_super) {
  71598. __extends(Bone, _super);
  71599. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  71600. if (parentBone === void 0) { parentBone = null; }
  71601. if (localMatrix === void 0) { localMatrix = null; }
  71602. if (restPose === void 0) { restPose = null; }
  71603. if (baseMatrix === void 0) { baseMatrix = null; }
  71604. if (index === void 0) { index = null; }
  71605. var _this = _super.call(this, name, skeleton.getScene()) || this;
  71606. _this.name = name;
  71607. _this.children = new Array();
  71608. _this.animations = new Array();
  71609. // Set this value to map this bone to a different index in the transform matrices.
  71610. // Set this value to -1 to exclude the bone from the transform matrices.
  71611. _this._index = null;
  71612. _this._worldTransform = new BABYLON.Matrix();
  71613. _this._absoluteTransform = new BABYLON.Matrix();
  71614. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  71615. _this._scaleMatrix = BABYLON.Matrix.Identity();
  71616. _this._scaleVector = BABYLON.Vector3.One();
  71617. _this._negateScaleChildren = BABYLON.Vector3.One();
  71618. _this._scalingDeterminant = 1;
  71619. _this._skeleton = skeleton;
  71620. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  71621. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  71622. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  71623. _this._index = index;
  71624. skeleton.bones.push(_this);
  71625. _this.setParent(parentBone, false);
  71626. _this._updateDifferenceMatrix();
  71627. return _this;
  71628. }
  71629. Object.defineProperty(Bone.prototype, "_matrix", {
  71630. get: function () {
  71631. return this._localMatrix;
  71632. },
  71633. set: function (val) {
  71634. if (this._localMatrix) {
  71635. this._localMatrix.copyFrom(val);
  71636. }
  71637. else {
  71638. this._localMatrix = val;
  71639. }
  71640. },
  71641. enumerable: true,
  71642. configurable: true
  71643. });
  71644. // Members
  71645. Bone.prototype.getSkeleton = function () {
  71646. return this._skeleton;
  71647. };
  71648. Bone.prototype.getParent = function () {
  71649. return this._parent;
  71650. };
  71651. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  71652. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  71653. if (this._parent === parent) {
  71654. return;
  71655. }
  71656. if (this._parent) {
  71657. var index = this._parent.children.indexOf(this);
  71658. if (index !== -1) {
  71659. this._parent.children.splice(index, 1);
  71660. }
  71661. }
  71662. this._parent = parent;
  71663. if (this._parent) {
  71664. this._parent.children.push(this);
  71665. }
  71666. if (updateDifferenceMatrix) {
  71667. this._updateDifferenceMatrix();
  71668. }
  71669. };
  71670. Bone.prototype.getLocalMatrix = function () {
  71671. return this._localMatrix;
  71672. };
  71673. Bone.prototype.getBaseMatrix = function () {
  71674. return this._baseMatrix;
  71675. };
  71676. Bone.prototype.getRestPose = function () {
  71677. return this._restPose;
  71678. };
  71679. Bone.prototype.returnToRest = function () {
  71680. this.updateMatrix(this._restPose.clone());
  71681. };
  71682. Bone.prototype.getWorldMatrix = function () {
  71683. return this._worldTransform;
  71684. };
  71685. Bone.prototype.getInvertedAbsoluteTransform = function () {
  71686. return this._invertedAbsoluteTransform;
  71687. };
  71688. Bone.prototype.getAbsoluteTransform = function () {
  71689. return this._absoluteTransform;
  71690. };
  71691. Object.defineProperty(Bone.prototype, "position", {
  71692. // Properties (matches AbstractMesh properties)
  71693. get: function () {
  71694. return this.getPosition();
  71695. },
  71696. set: function (newPosition) {
  71697. this.setPosition(newPosition);
  71698. },
  71699. enumerable: true,
  71700. configurable: true
  71701. });
  71702. Object.defineProperty(Bone.prototype, "rotation", {
  71703. get: function () {
  71704. return this.getRotation();
  71705. },
  71706. set: function (newRotation) {
  71707. this.setRotation(newRotation);
  71708. },
  71709. enumerable: true,
  71710. configurable: true
  71711. });
  71712. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  71713. get: function () {
  71714. return this.getRotationQuaternion();
  71715. },
  71716. set: function (newRotation) {
  71717. this.setRotationQuaternion(newRotation);
  71718. },
  71719. enumerable: true,
  71720. configurable: true
  71721. });
  71722. Object.defineProperty(Bone.prototype, "scaling", {
  71723. get: function () {
  71724. return this.getScale();
  71725. },
  71726. set: function (newScaling) {
  71727. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  71728. },
  71729. enumerable: true,
  71730. configurable: true
  71731. });
  71732. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  71733. /**
  71734. * Gets the animation properties override
  71735. */
  71736. get: function () {
  71737. return this._skeleton.animationPropertiesOverride;
  71738. },
  71739. enumerable: true,
  71740. configurable: true
  71741. });
  71742. // Methods
  71743. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  71744. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  71745. this._baseMatrix = matrix.clone();
  71746. this._localMatrix = matrix.clone();
  71747. this._skeleton._markAsDirty();
  71748. if (updateDifferenceMatrix) {
  71749. this._updateDifferenceMatrix();
  71750. }
  71751. };
  71752. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  71753. if (!rootMatrix) {
  71754. rootMatrix = this._baseMatrix;
  71755. }
  71756. if (this._parent) {
  71757. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  71758. }
  71759. else {
  71760. this._absoluteTransform.copyFrom(rootMatrix);
  71761. }
  71762. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  71763. for (var index = 0; index < this.children.length; index++) {
  71764. this.children[index]._updateDifferenceMatrix();
  71765. }
  71766. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  71767. };
  71768. Bone.prototype.markAsDirty = function () {
  71769. this._currentRenderId++;
  71770. this._skeleton._markAsDirty();
  71771. };
  71772. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  71773. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  71774. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  71775. // all animation may be coming from a library skeleton, so may need to create animation
  71776. if (this.animations.length === 0) {
  71777. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  71778. this.animations[0].setKeys([]);
  71779. }
  71780. // get animation info / verify there is such a range from the source bone
  71781. var sourceRange = source.animations[0].getRange(rangeName);
  71782. if (!sourceRange) {
  71783. return false;
  71784. }
  71785. var from = sourceRange.from;
  71786. var to = sourceRange.to;
  71787. var sourceKeys = source.animations[0].getKeys();
  71788. // rescaling prep
  71789. var sourceBoneLength = source.length;
  71790. var sourceParent = source.getParent();
  71791. var parent = this.getParent();
  71792. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  71793. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  71794. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  71795. var destKeys = this.animations[0].getKeys();
  71796. // loop vars declaration
  71797. var orig;
  71798. var origTranslation;
  71799. var mat;
  71800. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  71801. orig = sourceKeys[key];
  71802. if (orig.frame >= from && orig.frame <= to) {
  71803. if (rescaleAsRequired) {
  71804. mat = orig.value.clone();
  71805. // scale based on parent ratio, when bone has parent
  71806. if (parentScalingReqd) {
  71807. origTranslation = mat.getTranslation();
  71808. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  71809. // scale based on skeleton dimension ratio when root bone, and value is passed
  71810. }
  71811. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  71812. origTranslation = mat.getTranslation();
  71813. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  71814. // use original when root bone, and no data for skelDimensionsRatio
  71815. }
  71816. else {
  71817. mat = orig.value;
  71818. }
  71819. }
  71820. else {
  71821. mat = orig.value;
  71822. }
  71823. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  71824. }
  71825. }
  71826. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  71827. return true;
  71828. };
  71829. /**
  71830. * Translate the bone in local or world space.
  71831. * @param vec The amount to translate the bone.
  71832. * @param space The space that the translation is in.
  71833. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71834. */
  71835. Bone.prototype.translate = function (vec, space, mesh) {
  71836. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71837. var lm = this.getLocalMatrix();
  71838. if (space == BABYLON.Space.LOCAL) {
  71839. lm.m[12] += vec.x;
  71840. lm.m[13] += vec.y;
  71841. lm.m[14] += vec.z;
  71842. }
  71843. else {
  71844. var wm = null;
  71845. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71846. if (mesh) {
  71847. wm = mesh.getWorldMatrix();
  71848. }
  71849. this._skeleton.computeAbsoluteTransforms();
  71850. var tmat = Bone._tmpMats[0];
  71851. var tvec = Bone._tmpVecs[0];
  71852. if (this._parent) {
  71853. if (mesh && wm) {
  71854. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71855. tmat.multiplyToRef(wm, tmat);
  71856. }
  71857. else {
  71858. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71859. }
  71860. }
  71861. tmat.m[12] = 0;
  71862. tmat.m[13] = 0;
  71863. tmat.m[14] = 0;
  71864. tmat.invert();
  71865. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  71866. lm.m[12] += tvec.x;
  71867. lm.m[13] += tvec.y;
  71868. lm.m[14] += tvec.z;
  71869. }
  71870. this.markAsDirty();
  71871. };
  71872. /**
  71873. * Set the postion of the bone in local or world space.
  71874. * @param position The position to set the bone.
  71875. * @param space The space that the position is in.
  71876. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71877. */
  71878. Bone.prototype.setPosition = function (position, space, mesh) {
  71879. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71880. var lm = this.getLocalMatrix();
  71881. if (space == BABYLON.Space.LOCAL) {
  71882. lm.m[12] = position.x;
  71883. lm.m[13] = position.y;
  71884. lm.m[14] = position.z;
  71885. }
  71886. else {
  71887. var wm = null;
  71888. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71889. if (mesh) {
  71890. wm = mesh.getWorldMatrix();
  71891. }
  71892. this._skeleton.computeAbsoluteTransforms();
  71893. var tmat = Bone._tmpMats[0];
  71894. var vec = Bone._tmpVecs[0];
  71895. if (this._parent) {
  71896. if (mesh && wm) {
  71897. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71898. tmat.multiplyToRef(wm, tmat);
  71899. }
  71900. else {
  71901. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71902. }
  71903. }
  71904. tmat.invert();
  71905. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  71906. lm.m[12] = vec.x;
  71907. lm.m[13] = vec.y;
  71908. lm.m[14] = vec.z;
  71909. }
  71910. this.markAsDirty();
  71911. };
  71912. /**
  71913. * Set the absolute postion of the bone (world space).
  71914. * @param position The position to set the bone.
  71915. * @param mesh The mesh that this bone is attached to.
  71916. */
  71917. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  71918. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  71919. };
  71920. /**
  71921. * Set the scale of the bone on the x, y and z axes.
  71922. * @param x The scale of the bone on the x axis.
  71923. * @param x The scale of the bone on the y axis.
  71924. * @param z The scale of the bone on the z axis.
  71925. * @param scaleChildren Set this to true if children of the bone should be scaled.
  71926. */
  71927. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  71928. if (scaleChildren === void 0) { scaleChildren = false; }
  71929. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  71930. if (!scaleChildren) {
  71931. this._negateScaleChildren.x = 1 / x;
  71932. this._negateScaleChildren.y = 1 / y;
  71933. this._negateScaleChildren.z = 1 / z;
  71934. }
  71935. this._syncScaleVector();
  71936. }
  71937. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  71938. };
  71939. /**
  71940. * Scale the bone on the x, y and z axes.
  71941. * @param x The amount to scale the bone on the x axis.
  71942. * @param x The amount to scale the bone on the y axis.
  71943. * @param z The amount to scale the bone on the z axis.
  71944. * @param scaleChildren Set this to true if children of the bone should be scaled.
  71945. */
  71946. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  71947. if (scaleChildren === void 0) { scaleChildren = false; }
  71948. var locMat = this.getLocalMatrix();
  71949. var origLocMat = Bone._tmpMats[0];
  71950. origLocMat.copyFrom(locMat);
  71951. var origLocMatInv = Bone._tmpMats[1];
  71952. origLocMatInv.copyFrom(origLocMat);
  71953. origLocMatInv.invert();
  71954. var scaleMat = Bone._tmpMats[2];
  71955. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  71956. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  71957. this._scaleVector.x *= x;
  71958. this._scaleVector.y *= y;
  71959. this._scaleVector.z *= z;
  71960. locMat.multiplyToRef(origLocMatInv, locMat);
  71961. locMat.multiplyToRef(scaleMat, locMat);
  71962. locMat.multiplyToRef(origLocMat, locMat);
  71963. var parent = this.getParent();
  71964. if (parent) {
  71965. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  71966. }
  71967. else {
  71968. this.getAbsoluteTransform().copyFrom(locMat);
  71969. }
  71970. var len = this.children.length;
  71971. scaleMat.invert();
  71972. for (var i = 0; i < len; i++) {
  71973. var child = this.children[i];
  71974. var cm = child.getLocalMatrix();
  71975. cm.multiplyToRef(scaleMat, cm);
  71976. var lm = child.getLocalMatrix();
  71977. lm.m[12] *= x;
  71978. lm.m[13] *= y;
  71979. lm.m[14] *= z;
  71980. }
  71981. this.computeAbsoluteTransforms();
  71982. if (scaleChildren) {
  71983. for (var i = 0; i < len; i++) {
  71984. this.children[i].scale(x, y, z, scaleChildren);
  71985. }
  71986. }
  71987. this.markAsDirty();
  71988. };
  71989. /**
  71990. * Set the yaw, pitch, and roll of the bone in local or world space.
  71991. * @param yaw The rotation of the bone on the y axis.
  71992. * @param pitch The rotation of the bone on the x axis.
  71993. * @param roll The rotation of the bone on the z axis.
  71994. * @param space The space that the axes of rotation are in.
  71995. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71996. */
  71997. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  71998. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71999. var rotMat = Bone._tmpMats[0];
  72000. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  72001. var rotMatInv = Bone._tmpMats[1];
  72002. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72003. rotMatInv.multiplyToRef(rotMat, rotMat);
  72004. this._rotateWithMatrix(rotMat, space, mesh);
  72005. };
  72006. /**
  72007. * Rotate the bone on an axis in local or world space.
  72008. * @param axis The axis to rotate the bone on.
  72009. * @param amount The amount to rotate the bone.
  72010. * @param space The space that the axis is in.
  72011. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72012. */
  72013. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  72014. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72015. var rmat = Bone._tmpMats[0];
  72016. rmat.m[12] = 0;
  72017. rmat.m[13] = 0;
  72018. rmat.m[14] = 0;
  72019. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  72020. this._rotateWithMatrix(rmat, space, mesh);
  72021. };
  72022. /**
  72023. * Set the rotation of the bone to a particular axis angle in local or world space.
  72024. * @param axis The axis to rotate the bone on.
  72025. * @param angle The angle that the bone should be rotated to.
  72026. * @param space The space that the axis is in.
  72027. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72028. */
  72029. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  72030. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72031. var rotMat = Bone._tmpMats[0];
  72032. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  72033. var rotMatInv = Bone._tmpMats[1];
  72034. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72035. rotMatInv.multiplyToRef(rotMat, rotMat);
  72036. this._rotateWithMatrix(rotMat, space, mesh);
  72037. };
  72038. /**
  72039. * Set the euler rotation of the bone in local of world space.
  72040. * @param rotation The euler rotation that the bone should be set to.
  72041. * @param space The space that the rotation is in.
  72042. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72043. */
  72044. Bone.prototype.setRotation = function (rotation, space, mesh) {
  72045. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72046. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  72047. };
  72048. /**
  72049. * Set the quaternion rotation of the bone in local of world space.
  72050. * @param quat The quaternion rotation that the bone should be set to.
  72051. * @param space The space that the rotation is in.
  72052. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72053. */
  72054. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  72055. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72056. var rotMatInv = Bone._tmpMats[0];
  72057. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72058. var rotMat = Bone._tmpMats[1];
  72059. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  72060. rotMatInv.multiplyToRef(rotMat, rotMat);
  72061. this._rotateWithMatrix(rotMat, space, mesh);
  72062. };
  72063. /**
  72064. * Set the rotation matrix of the bone in local of world space.
  72065. * @param rotMat The rotation matrix that the bone should be set to.
  72066. * @param space The space that the rotation is in.
  72067. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72068. */
  72069. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  72070. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72071. var rotMatInv = Bone._tmpMats[0];
  72072. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72073. var rotMat2 = Bone._tmpMats[1];
  72074. rotMat2.copyFrom(rotMat);
  72075. rotMatInv.multiplyToRef(rotMat, rotMat2);
  72076. this._rotateWithMatrix(rotMat2, space, mesh);
  72077. };
  72078. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  72079. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72080. var lmat = this.getLocalMatrix();
  72081. var lx = lmat.m[12];
  72082. var ly = lmat.m[13];
  72083. var lz = lmat.m[14];
  72084. var parent = this.getParent();
  72085. var parentScale = Bone._tmpMats[3];
  72086. var parentScaleInv = Bone._tmpMats[4];
  72087. if (parent) {
  72088. if (space == BABYLON.Space.WORLD) {
  72089. if (mesh) {
  72090. parentScale.copyFrom(mesh.getWorldMatrix());
  72091. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  72092. }
  72093. else {
  72094. parentScale.copyFrom(parent.getAbsoluteTransform());
  72095. }
  72096. }
  72097. else {
  72098. parentScale = parent._scaleMatrix;
  72099. }
  72100. parentScaleInv.copyFrom(parentScale);
  72101. parentScaleInv.invert();
  72102. lmat.multiplyToRef(parentScale, lmat);
  72103. lmat.multiplyToRef(rmat, lmat);
  72104. lmat.multiplyToRef(parentScaleInv, lmat);
  72105. }
  72106. else {
  72107. if (space == BABYLON.Space.WORLD && mesh) {
  72108. parentScale.copyFrom(mesh.getWorldMatrix());
  72109. parentScaleInv.copyFrom(parentScale);
  72110. parentScaleInv.invert();
  72111. lmat.multiplyToRef(parentScale, lmat);
  72112. lmat.multiplyToRef(rmat, lmat);
  72113. lmat.multiplyToRef(parentScaleInv, lmat);
  72114. }
  72115. else {
  72116. lmat.multiplyToRef(rmat, lmat);
  72117. }
  72118. }
  72119. lmat.m[12] = lx;
  72120. lmat.m[13] = ly;
  72121. lmat.m[14] = lz;
  72122. this.computeAbsoluteTransforms();
  72123. this.markAsDirty();
  72124. };
  72125. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  72126. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72127. if (space == BABYLON.Space.WORLD) {
  72128. var scaleMatrix = Bone._tmpMats[2];
  72129. scaleMatrix.copyFrom(this._scaleMatrix);
  72130. rotMatInv.copyFrom(this.getAbsoluteTransform());
  72131. if (mesh) {
  72132. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  72133. var meshScale = Bone._tmpMats[3];
  72134. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  72135. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  72136. }
  72137. rotMatInv.invert();
  72138. scaleMatrix.m[0] *= this._scalingDeterminant;
  72139. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  72140. }
  72141. else {
  72142. rotMatInv.copyFrom(this.getLocalMatrix());
  72143. rotMatInv.invert();
  72144. var scaleMatrix = Bone._tmpMats[2];
  72145. scaleMatrix.copyFrom(this._scaleMatrix);
  72146. if (this._parent) {
  72147. var pscaleMatrix = Bone._tmpMats[3];
  72148. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  72149. pscaleMatrix.invert();
  72150. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  72151. }
  72152. else {
  72153. scaleMatrix.m[0] *= this._scalingDeterminant;
  72154. }
  72155. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  72156. }
  72157. };
  72158. /**
  72159. * Get the scale of the bone
  72160. * @returns the scale of the bone
  72161. */
  72162. Bone.prototype.getScale = function () {
  72163. return this._scaleVector.clone();
  72164. };
  72165. /**
  72166. * Copy the scale of the bone to a vector3.
  72167. * @param result The vector3 to copy the scale to
  72168. */
  72169. Bone.prototype.getScaleToRef = function (result) {
  72170. result.copyFrom(this._scaleVector);
  72171. };
  72172. /**
  72173. * Get the position of the bone in local or world space.
  72174. * @param space The space that the returned position is in.
  72175. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72176. * @returns The position of the bone
  72177. */
  72178. Bone.prototype.getPosition = function (space, mesh) {
  72179. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72180. if (mesh === void 0) { mesh = null; }
  72181. var pos = BABYLON.Vector3.Zero();
  72182. this.getPositionToRef(space, mesh, pos);
  72183. return pos;
  72184. };
  72185. /**
  72186. * Copy the position of the bone to a vector3 in local or world space.
  72187. * @param space The space that the returned position is in.
  72188. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72189. * @param result The vector3 to copy the position to.
  72190. */
  72191. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  72192. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72193. if (space == BABYLON.Space.LOCAL) {
  72194. var lm = this.getLocalMatrix();
  72195. result.x = lm.m[12];
  72196. result.y = lm.m[13];
  72197. result.z = lm.m[14];
  72198. }
  72199. else {
  72200. var wm = null;
  72201. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72202. if (mesh) {
  72203. wm = mesh.getWorldMatrix();
  72204. }
  72205. this._skeleton.computeAbsoluteTransforms();
  72206. var tmat = Bone._tmpMats[0];
  72207. if (mesh && wm) {
  72208. tmat.copyFrom(this.getAbsoluteTransform());
  72209. tmat.multiplyToRef(wm, tmat);
  72210. }
  72211. else {
  72212. tmat = this.getAbsoluteTransform();
  72213. }
  72214. result.x = tmat.m[12];
  72215. result.y = tmat.m[13];
  72216. result.z = tmat.m[14];
  72217. }
  72218. };
  72219. /**
  72220. * Get the absolute position of the bone (world space).
  72221. * @param mesh The mesh that this bone is attached to.
  72222. * @returns The absolute position of the bone
  72223. */
  72224. Bone.prototype.getAbsolutePosition = function (mesh) {
  72225. if (mesh === void 0) { mesh = null; }
  72226. var pos = BABYLON.Vector3.Zero();
  72227. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  72228. return pos;
  72229. };
  72230. /**
  72231. * Copy the absolute position of the bone (world space) to the result param.
  72232. * @param mesh The mesh that this bone is attached to.
  72233. * @param result The vector3 to copy the absolute position to.
  72234. */
  72235. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  72236. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  72237. };
  72238. /**
  72239. * Compute the absolute transforms of this bone and its children.
  72240. */
  72241. Bone.prototype.computeAbsoluteTransforms = function () {
  72242. if (this._parent) {
  72243. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72244. }
  72245. else {
  72246. this._absoluteTransform.copyFrom(this._localMatrix);
  72247. var poseMatrix = this._skeleton.getPoseMatrix();
  72248. if (poseMatrix) {
  72249. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  72250. }
  72251. }
  72252. var children = this.children;
  72253. var len = children.length;
  72254. for (var i = 0; i < len; i++) {
  72255. children[i].computeAbsoluteTransforms();
  72256. }
  72257. };
  72258. Bone.prototype._syncScaleVector = function () {
  72259. var lm = this.getLocalMatrix();
  72260. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  72261. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  72262. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  72263. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  72264. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  72265. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  72266. this._scaleVector.x = xs * Math.sqrt(xsq);
  72267. this._scaleVector.y = ys * Math.sqrt(ysq);
  72268. this._scaleVector.z = zs * Math.sqrt(zsq);
  72269. if (this._parent) {
  72270. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  72271. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  72272. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  72273. }
  72274. 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);
  72275. };
  72276. /**
  72277. * Get the world direction from an axis that is in the local space of the bone.
  72278. * @param localAxis The local direction that is used to compute the world direction.
  72279. * @param mesh The mesh that this bone is attached to.
  72280. * @returns The world direction
  72281. */
  72282. Bone.prototype.getDirection = function (localAxis, mesh) {
  72283. if (mesh === void 0) { mesh = null; }
  72284. var result = BABYLON.Vector3.Zero();
  72285. this.getDirectionToRef(localAxis, mesh, result);
  72286. return result;
  72287. };
  72288. /**
  72289. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  72290. * @param localAxis The local direction that is used to compute the world direction.
  72291. * @param mesh The mesh that this bone is attached to.
  72292. * @param result The vector3 that the world direction will be copied to.
  72293. */
  72294. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  72295. if (mesh === void 0) { mesh = null; }
  72296. var wm = null;
  72297. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72298. if (mesh) {
  72299. wm = mesh.getWorldMatrix();
  72300. }
  72301. this._skeleton.computeAbsoluteTransforms();
  72302. var mat = Bone._tmpMats[0];
  72303. mat.copyFrom(this.getAbsoluteTransform());
  72304. if (mesh && wm) {
  72305. mat.multiplyToRef(wm, mat);
  72306. }
  72307. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  72308. result.normalize();
  72309. };
  72310. /**
  72311. * Get the euler rotation of the bone in local or world space.
  72312. * @param space The space that the rotation should be in.
  72313. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72314. * @returns The euler rotation
  72315. */
  72316. Bone.prototype.getRotation = function (space, mesh) {
  72317. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72318. if (mesh === void 0) { mesh = null; }
  72319. var result = BABYLON.Vector3.Zero();
  72320. this.getRotationToRef(space, mesh, result);
  72321. return result;
  72322. };
  72323. /**
  72324. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  72325. * @param space The space that the rotation should be in.
  72326. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72327. * @param result The vector3 that the rotation should be copied to.
  72328. */
  72329. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  72330. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72331. if (mesh === void 0) { mesh = null; }
  72332. var quat = Bone._tmpQuat;
  72333. this.getRotationQuaternionToRef(space, mesh, quat);
  72334. quat.toEulerAnglesToRef(result);
  72335. };
  72336. /**
  72337. * Get the quaternion rotation of the bone in either local or world space.
  72338. * @param space The space that the rotation should be in.
  72339. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72340. * @returns The quaternion rotation
  72341. */
  72342. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  72343. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72344. if (mesh === void 0) { mesh = null; }
  72345. var result = BABYLON.Quaternion.Identity();
  72346. this.getRotationQuaternionToRef(space, mesh, result);
  72347. return result;
  72348. };
  72349. /**
  72350. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  72351. * @param space The space that the rotation should be in.
  72352. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72353. * @param result The quaternion that the rotation should be copied to.
  72354. */
  72355. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  72356. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72357. if (mesh === void 0) { mesh = null; }
  72358. if (space == BABYLON.Space.LOCAL) {
  72359. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72360. }
  72361. else {
  72362. var mat = Bone._tmpMats[0];
  72363. var amat = this.getAbsoluteTransform();
  72364. if (mesh) {
  72365. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  72366. }
  72367. else {
  72368. mat.copyFrom(amat);
  72369. }
  72370. mat.m[0] *= this._scalingDeterminant;
  72371. mat.m[1] *= this._scalingDeterminant;
  72372. mat.m[2] *= this._scalingDeterminant;
  72373. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72374. }
  72375. };
  72376. /**
  72377. * Get the rotation matrix of the bone in local or world space.
  72378. * @param space The space that the rotation should be in.
  72379. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72380. * @returns The rotation matrix
  72381. */
  72382. Bone.prototype.getRotationMatrix = function (space, mesh) {
  72383. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72384. var result = BABYLON.Matrix.Identity();
  72385. this.getRotationMatrixToRef(space, mesh, result);
  72386. return result;
  72387. };
  72388. /**
  72389. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  72390. * @param space The space that the rotation should be in.
  72391. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72392. * @param result The quaternion that the rotation should be copied to.
  72393. */
  72394. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  72395. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72396. if (space == BABYLON.Space.LOCAL) {
  72397. this.getLocalMatrix().getRotationMatrixToRef(result);
  72398. }
  72399. else {
  72400. var mat = Bone._tmpMats[0];
  72401. var amat = this.getAbsoluteTransform();
  72402. if (mesh) {
  72403. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  72404. }
  72405. else {
  72406. mat.copyFrom(amat);
  72407. }
  72408. mat.m[0] *= this._scalingDeterminant;
  72409. mat.m[1] *= this._scalingDeterminant;
  72410. mat.m[2] *= this._scalingDeterminant;
  72411. mat.getRotationMatrixToRef(result);
  72412. }
  72413. };
  72414. /**
  72415. * Get the world position of a point that is in the local space of the bone.
  72416. * @param position The local position
  72417. * @param mesh The mesh that this bone is attached to.
  72418. * @returns The world position
  72419. */
  72420. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  72421. if (mesh === void 0) { mesh = null; }
  72422. var result = BABYLON.Vector3.Zero();
  72423. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  72424. return result;
  72425. };
  72426. /**
  72427. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  72428. * @param position The local position
  72429. * @param mesh The mesh that this bone is attached to.
  72430. * @param result The vector3 that the world position should be copied to.
  72431. */
  72432. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  72433. if (mesh === void 0) { mesh = null; }
  72434. var wm = null;
  72435. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72436. if (mesh) {
  72437. wm = mesh.getWorldMatrix();
  72438. }
  72439. this._skeleton.computeAbsoluteTransforms();
  72440. var tmat = Bone._tmpMats[0];
  72441. if (mesh && wm) {
  72442. tmat.copyFrom(this.getAbsoluteTransform());
  72443. tmat.multiplyToRef(wm, tmat);
  72444. }
  72445. else {
  72446. tmat = this.getAbsoluteTransform();
  72447. }
  72448. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  72449. };
  72450. /**
  72451. * Get the local position of a point that is in world space.
  72452. * @param position The world position
  72453. * @param mesh The mesh that this bone is attached to.
  72454. * @returns The local position
  72455. */
  72456. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  72457. if (mesh === void 0) { mesh = null; }
  72458. var result = BABYLON.Vector3.Zero();
  72459. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  72460. return result;
  72461. };
  72462. /**
  72463. * Get the local position of a point that is in world space and copy it to the result param.
  72464. * @param position The world position
  72465. * @param mesh The mesh that this bone is attached to.
  72466. * @param result The vector3 that the local position should be copied to.
  72467. */
  72468. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  72469. if (mesh === void 0) { mesh = null; }
  72470. var wm = null;
  72471. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72472. if (mesh) {
  72473. wm = mesh.getWorldMatrix();
  72474. }
  72475. this._skeleton.computeAbsoluteTransforms();
  72476. var tmat = Bone._tmpMats[0];
  72477. tmat.copyFrom(this.getAbsoluteTransform());
  72478. if (mesh && wm) {
  72479. tmat.multiplyToRef(wm, tmat);
  72480. }
  72481. tmat.invert();
  72482. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  72483. };
  72484. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72485. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  72486. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72487. return Bone;
  72488. }(BABYLON.Node));
  72489. BABYLON.Bone = Bone;
  72490. })(BABYLON || (BABYLON = {}));
  72491. //# sourceMappingURL=babylon.bone.js.map
  72492. var BABYLON;
  72493. (function (BABYLON) {
  72494. var BoneIKController = /** @class */ (function () {
  72495. function BoneIKController(mesh, bone, options) {
  72496. this.targetPosition = BABYLON.Vector3.Zero();
  72497. this.poleTargetPosition = BABYLON.Vector3.Zero();
  72498. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  72499. this.poleAngle = 0;
  72500. this.slerpAmount = 1;
  72501. this._bone1Quat = BABYLON.Quaternion.Identity();
  72502. this._bone1Mat = BABYLON.Matrix.Identity();
  72503. this._bone2Ang = Math.PI;
  72504. this._maxAngle = Math.PI;
  72505. this._rightHandedSystem = false;
  72506. this._bendAxis = BABYLON.Vector3.Right();
  72507. this._slerping = false;
  72508. this._adjustRoll = 0;
  72509. this._bone2 = bone;
  72510. this._bone1 = bone.getParent();
  72511. if (!this._bone1) {
  72512. return;
  72513. }
  72514. this.mesh = mesh;
  72515. var bonePos = bone.getPosition();
  72516. if (bone.getAbsoluteTransform().determinant() > 0) {
  72517. this._rightHandedSystem = true;
  72518. this._bendAxis.x = 0;
  72519. this._bendAxis.y = 0;
  72520. this._bendAxis.z = -1;
  72521. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  72522. this._adjustRoll = Math.PI * .5;
  72523. this._bendAxis.z = 1;
  72524. }
  72525. }
  72526. if (this._bone1.length) {
  72527. var boneScale1 = this._bone1.getScale();
  72528. var boneScale2 = this._bone2.getScale();
  72529. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  72530. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  72531. }
  72532. else if (this._bone1.children[0]) {
  72533. mesh.computeWorldMatrix(true);
  72534. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  72535. var pos2 = this._bone2.getAbsolutePosition(mesh);
  72536. var pos3 = this._bone1.getAbsolutePosition(mesh);
  72537. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  72538. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  72539. }
  72540. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  72541. this.maxAngle = Math.PI;
  72542. if (options) {
  72543. if (options.targetMesh) {
  72544. this.targetMesh = options.targetMesh;
  72545. this.targetMesh.computeWorldMatrix(true);
  72546. }
  72547. if (options.poleTargetMesh) {
  72548. this.poleTargetMesh = options.poleTargetMesh;
  72549. this.poleTargetMesh.computeWorldMatrix(true);
  72550. }
  72551. else if (options.poleTargetBone) {
  72552. this.poleTargetBone = options.poleTargetBone;
  72553. }
  72554. else if (this._bone1.getParent()) {
  72555. this.poleTargetBone = this._bone1.getParent();
  72556. }
  72557. if (options.poleTargetLocalOffset) {
  72558. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  72559. }
  72560. if (options.poleAngle) {
  72561. this.poleAngle = options.poleAngle;
  72562. }
  72563. if (options.bendAxis) {
  72564. this._bendAxis.copyFrom(options.bendAxis);
  72565. }
  72566. if (options.maxAngle) {
  72567. this.maxAngle = options.maxAngle;
  72568. }
  72569. if (options.slerpAmount) {
  72570. this.slerpAmount = options.slerpAmount;
  72571. }
  72572. }
  72573. }
  72574. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  72575. get: function () {
  72576. return this._maxAngle;
  72577. },
  72578. set: function (value) {
  72579. this._setMaxAngle(value);
  72580. },
  72581. enumerable: true,
  72582. configurable: true
  72583. });
  72584. BoneIKController.prototype._setMaxAngle = function (ang) {
  72585. if (ang < 0) {
  72586. ang = 0;
  72587. }
  72588. if (ang > Math.PI || ang == undefined) {
  72589. ang = Math.PI;
  72590. }
  72591. this._maxAngle = ang;
  72592. var a = this._bone1Length;
  72593. var b = this._bone2Length;
  72594. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  72595. };
  72596. BoneIKController.prototype.update = function () {
  72597. var bone1 = this._bone1;
  72598. if (!bone1) {
  72599. return;
  72600. }
  72601. var target = this.targetPosition;
  72602. var poleTarget = this.poleTargetPosition;
  72603. var mat1 = BoneIKController._tmpMats[0];
  72604. var mat2 = BoneIKController._tmpMats[1];
  72605. if (this.targetMesh) {
  72606. target.copyFrom(this.targetMesh.getAbsolutePosition());
  72607. }
  72608. if (this.poleTargetBone) {
  72609. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  72610. }
  72611. else if (this.poleTargetMesh) {
  72612. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  72613. }
  72614. var bonePos = BoneIKController._tmpVecs[0];
  72615. var zaxis = BoneIKController._tmpVecs[1];
  72616. var xaxis = BoneIKController._tmpVecs[2];
  72617. var yaxis = BoneIKController._tmpVecs[3];
  72618. var upAxis = BoneIKController._tmpVecs[4];
  72619. var _tmpQuat = BoneIKController._tmpQuat;
  72620. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  72621. poleTarget.subtractToRef(bonePos, upAxis);
  72622. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  72623. upAxis.y = 1;
  72624. }
  72625. else {
  72626. upAxis.normalize();
  72627. }
  72628. target.subtractToRef(bonePos, yaxis);
  72629. yaxis.normalize();
  72630. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  72631. zaxis.normalize();
  72632. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  72633. xaxis.normalize();
  72634. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  72635. var a = this._bone1Length;
  72636. var b = this._bone2Length;
  72637. var c = BABYLON.Vector3.Distance(bonePos, target);
  72638. if (this._maxReach > 0) {
  72639. c = Math.min(this._maxReach, c);
  72640. }
  72641. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  72642. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  72643. if (acosa > 1) {
  72644. acosa = 1;
  72645. }
  72646. if (acosb > 1) {
  72647. acosb = 1;
  72648. }
  72649. if (acosa < -1) {
  72650. acosa = -1;
  72651. }
  72652. if (acosb < -1) {
  72653. acosb = -1;
  72654. }
  72655. var angA = Math.acos(acosa);
  72656. var angB = Math.acos(acosb);
  72657. var angC = -angA - angB;
  72658. if (this._rightHandedSystem) {
  72659. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  72660. mat2.multiplyToRef(mat1, mat1);
  72661. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  72662. mat2.multiplyToRef(mat1, mat1);
  72663. }
  72664. else {
  72665. var _tmpVec = BoneIKController._tmpVecs[5];
  72666. _tmpVec.copyFrom(this._bendAxis);
  72667. _tmpVec.x *= -1;
  72668. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  72669. mat2.multiplyToRef(mat1, mat1);
  72670. }
  72671. if (this.poleAngle) {
  72672. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  72673. mat1.multiplyToRef(mat2, mat1);
  72674. }
  72675. if (this._bone1) {
  72676. if (this.slerpAmount < 1) {
  72677. if (!this._slerping) {
  72678. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  72679. }
  72680. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  72681. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  72682. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  72683. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  72684. this._slerping = true;
  72685. }
  72686. else {
  72687. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  72688. this._bone1Mat.copyFrom(mat1);
  72689. this._slerping = false;
  72690. }
  72691. }
  72692. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  72693. this._bone2Ang = angC;
  72694. };
  72695. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72696. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  72697. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72698. return BoneIKController;
  72699. }());
  72700. BABYLON.BoneIKController = BoneIKController;
  72701. })(BABYLON || (BABYLON = {}));
  72702. //# sourceMappingURL=babylon.boneIKController.js.map
  72703. var BABYLON;
  72704. (function (BABYLON) {
  72705. var BoneLookController = /** @class */ (function () {
  72706. /**
  72707. * Create a BoneLookController
  72708. * @param mesh the mesh that the bone belongs to
  72709. * @param bone the bone that will be looking to the target
  72710. * @param target the target Vector3 to look at
  72711. * @param settings optional settings:
  72712. * - maxYaw: the maximum angle the bone will yaw to
  72713. * - minYaw: the minimum angle the bone will yaw to
  72714. * - maxPitch: the maximum angle the bone will pitch to
  72715. * - minPitch: the minimum angle the bone will yaw to
  72716. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  72717. * - upAxis: the up axis of the coordinate system
  72718. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  72719. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  72720. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  72721. * - adjustYaw: used to make an adjustment to the yaw of the bone
  72722. * - adjustPitch: used to make an adjustment to the pitch of the bone
  72723. * - adjustRoll: used to make an adjustment to the roll of the bone
  72724. **/
  72725. function BoneLookController(mesh, bone, target, options) {
  72726. /**
  72727. * The up axis of the coordinate system that is used when the bone is rotated.
  72728. */
  72729. this.upAxis = BABYLON.Vector3.Up();
  72730. /**
  72731. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  72732. */
  72733. this.upAxisSpace = BABYLON.Space.LOCAL;
  72734. /**
  72735. * Used to make an adjustment to the yaw of the bone.
  72736. */
  72737. this.adjustYaw = 0;
  72738. /**
  72739. * Used to make an adjustment to the pitch of the bone.
  72740. */
  72741. this.adjustPitch = 0;
  72742. /**
  72743. * Used to make an adjustment to the roll of the bone.
  72744. */
  72745. this.adjustRoll = 0;
  72746. /**
  72747. * 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).
  72748. */
  72749. this.slerpAmount = 1;
  72750. this._boneQuat = BABYLON.Quaternion.Identity();
  72751. this._slerping = false;
  72752. this._firstFrameSkipped = false;
  72753. this._fowardAxis = BABYLON.Vector3.Forward();
  72754. this.mesh = mesh;
  72755. this.bone = bone;
  72756. this.target = target;
  72757. if (options) {
  72758. if (options.adjustYaw) {
  72759. this.adjustYaw = options.adjustYaw;
  72760. }
  72761. if (options.adjustPitch) {
  72762. this.adjustPitch = options.adjustPitch;
  72763. }
  72764. if (options.adjustRoll) {
  72765. this.adjustRoll = options.adjustRoll;
  72766. }
  72767. if (options.maxYaw != null) {
  72768. this.maxYaw = options.maxYaw;
  72769. }
  72770. else {
  72771. this.maxYaw = Math.PI;
  72772. }
  72773. if (options.minYaw != null) {
  72774. this.minYaw = options.minYaw;
  72775. }
  72776. else {
  72777. this.minYaw = -Math.PI;
  72778. }
  72779. if (options.maxPitch != null) {
  72780. this.maxPitch = options.maxPitch;
  72781. }
  72782. else {
  72783. this.maxPitch = Math.PI;
  72784. }
  72785. if (options.minPitch != null) {
  72786. this.minPitch = options.minPitch;
  72787. }
  72788. else {
  72789. this.minPitch = -Math.PI;
  72790. }
  72791. if (options.slerpAmount != null) {
  72792. this.slerpAmount = options.slerpAmount;
  72793. }
  72794. if (options.upAxis != null) {
  72795. this.upAxis = options.upAxis;
  72796. }
  72797. if (options.upAxisSpace != null) {
  72798. this.upAxisSpace = options.upAxisSpace;
  72799. }
  72800. if (options.yawAxis != null || options.pitchAxis != null) {
  72801. var newYawAxis = BABYLON.Axis.Y;
  72802. var newPitchAxis = BABYLON.Axis.X;
  72803. if (options.yawAxis != null) {
  72804. newYawAxis = options.yawAxis.clone();
  72805. newYawAxis.normalize();
  72806. }
  72807. if (options.pitchAxis != null) {
  72808. newPitchAxis = options.pitchAxis.clone();
  72809. newPitchAxis.normalize();
  72810. }
  72811. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  72812. this._transformYawPitch = BABYLON.Matrix.Identity();
  72813. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  72814. this._transformYawPitchInv = this._transformYawPitch.clone();
  72815. this._transformYawPitch.invert();
  72816. }
  72817. }
  72818. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  72819. this.upAxisSpace = BABYLON.Space.LOCAL;
  72820. }
  72821. }
  72822. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  72823. /**
  72824. * Get/set the minimum yaw angle that the bone can look to.
  72825. */
  72826. get: function () {
  72827. return this._minYaw;
  72828. },
  72829. set: function (value) {
  72830. this._minYaw = value;
  72831. this._minYawSin = Math.sin(value);
  72832. this._minYawCos = Math.cos(value);
  72833. if (this._maxYaw != null) {
  72834. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  72835. this._yawRange = this._maxYaw - this._minYaw;
  72836. }
  72837. },
  72838. enumerable: true,
  72839. configurable: true
  72840. });
  72841. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  72842. /**
  72843. * Get/set the maximum yaw angle that the bone can look to.
  72844. */
  72845. get: function () {
  72846. return this._maxYaw;
  72847. },
  72848. set: function (value) {
  72849. this._maxYaw = value;
  72850. this._maxYawSin = Math.sin(value);
  72851. this._maxYawCos = Math.cos(value);
  72852. if (this._minYaw != null) {
  72853. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  72854. this._yawRange = this._maxYaw - this._minYaw;
  72855. }
  72856. },
  72857. enumerable: true,
  72858. configurable: true
  72859. });
  72860. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  72861. /**
  72862. * Get/set the minimum pitch angle that the bone can look to.
  72863. */
  72864. get: function () {
  72865. return this._minPitch;
  72866. },
  72867. set: function (value) {
  72868. this._minPitch = value;
  72869. this._minPitchTan = Math.tan(value);
  72870. },
  72871. enumerable: true,
  72872. configurable: true
  72873. });
  72874. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  72875. /**
  72876. * Get/set the maximum pitch angle that the bone can look to.
  72877. */
  72878. get: function () {
  72879. return this._maxPitch;
  72880. },
  72881. set: function (value) {
  72882. this._maxPitch = value;
  72883. this._maxPitchTan = Math.tan(value);
  72884. },
  72885. enumerable: true,
  72886. configurable: true
  72887. });
  72888. /**
  72889. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  72890. */
  72891. BoneLookController.prototype.update = function () {
  72892. //skip the first frame when slerping so that the mesh rotation is correct
  72893. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  72894. this._firstFrameSkipped = true;
  72895. return;
  72896. }
  72897. var bone = this.bone;
  72898. var bonePos = BoneLookController._tmpVecs[0];
  72899. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  72900. var target = this.target;
  72901. var _tmpMat1 = BoneLookController._tmpMats[0];
  72902. var _tmpMat2 = BoneLookController._tmpMats[1];
  72903. var mesh = this.mesh;
  72904. var parentBone = bone.getParent();
  72905. var upAxis = BoneLookController._tmpVecs[1];
  72906. upAxis.copyFrom(this.upAxis);
  72907. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  72908. if (this._transformYawPitch) {
  72909. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  72910. }
  72911. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  72912. }
  72913. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  72914. mesh.getDirectionToRef(upAxis, upAxis);
  72915. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  72916. upAxis.normalize();
  72917. }
  72918. }
  72919. var checkYaw = false;
  72920. var checkPitch = false;
  72921. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  72922. checkYaw = true;
  72923. }
  72924. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  72925. checkPitch = true;
  72926. }
  72927. if (checkYaw || checkPitch) {
  72928. var spaceMat = BoneLookController._tmpMats[2];
  72929. var spaceMatInv = BoneLookController._tmpMats[3];
  72930. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  72931. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  72932. }
  72933. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  72934. spaceMat.copyFrom(mesh.getWorldMatrix());
  72935. }
  72936. else {
  72937. var forwardAxis = BoneLookController._tmpVecs[2];
  72938. forwardAxis.copyFrom(this._fowardAxis);
  72939. if (this._transformYawPitch) {
  72940. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  72941. }
  72942. if (parentBone) {
  72943. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  72944. }
  72945. else {
  72946. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  72947. }
  72948. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  72949. rightAxis.normalize();
  72950. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  72951. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  72952. }
  72953. spaceMat.invertToRef(spaceMatInv);
  72954. var xzlen = null;
  72955. if (checkPitch) {
  72956. var localTarget = BoneLookController._tmpVecs[3];
  72957. target.subtractToRef(bonePos, localTarget);
  72958. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  72959. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72960. var pitch = Math.atan2(localTarget.y, xzlen);
  72961. var newPitch = pitch;
  72962. if (pitch > this._maxPitch) {
  72963. localTarget.y = this._maxPitchTan * xzlen;
  72964. newPitch = this._maxPitch;
  72965. }
  72966. else if (pitch < this._minPitch) {
  72967. localTarget.y = this._minPitchTan * xzlen;
  72968. newPitch = this._minPitch;
  72969. }
  72970. if (pitch != newPitch) {
  72971. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  72972. localTarget.addInPlace(bonePos);
  72973. target = localTarget;
  72974. }
  72975. }
  72976. if (checkYaw) {
  72977. var localTarget = BoneLookController._tmpVecs[4];
  72978. target.subtractToRef(bonePos, localTarget);
  72979. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  72980. var yaw = Math.atan2(localTarget.x, localTarget.z);
  72981. var newYaw = yaw;
  72982. if (yaw > this._maxYaw || yaw < this._minYaw) {
  72983. if (xzlen == null) {
  72984. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72985. }
  72986. if (this._yawRange > Math.PI) {
  72987. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  72988. localTarget.z = this._maxYawCos * xzlen;
  72989. localTarget.x = this._maxYawSin * xzlen;
  72990. newYaw = this._maxYaw;
  72991. }
  72992. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  72993. localTarget.z = this._minYawCos * xzlen;
  72994. localTarget.x = this._minYawSin * xzlen;
  72995. newYaw = this._minYaw;
  72996. }
  72997. }
  72998. else {
  72999. if (yaw > this._maxYaw) {
  73000. localTarget.z = this._maxYawCos * xzlen;
  73001. localTarget.x = this._maxYawSin * xzlen;
  73002. newYaw = this._maxYaw;
  73003. }
  73004. else if (yaw < this._minYaw) {
  73005. localTarget.z = this._minYawCos * xzlen;
  73006. localTarget.x = this._minYawSin * xzlen;
  73007. newYaw = this._minYaw;
  73008. }
  73009. }
  73010. }
  73011. if (this._slerping && this._yawRange > Math.PI) {
  73012. //are we going to be crossing into the min/max region?
  73013. var boneFwd = BoneLookController._tmpVecs[8];
  73014. boneFwd.copyFrom(BABYLON.Axis.Z);
  73015. if (this._transformYawPitch) {
  73016. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  73017. }
  73018. var boneRotMat = BoneLookController._tmpMats[4];
  73019. this._boneQuat.toRotationMatrix(boneRotMat);
  73020. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  73021. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  73022. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  73023. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  73024. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  73025. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  73026. if (angBtwTar > angBtwMidYaw) {
  73027. if (xzlen == null) {
  73028. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73029. }
  73030. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  73031. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  73032. if (angBtwMin < angBtwMax) {
  73033. newYaw = boneYaw + Math.PI * .75;
  73034. localTarget.z = Math.cos(newYaw) * xzlen;
  73035. localTarget.x = Math.sin(newYaw) * xzlen;
  73036. }
  73037. else {
  73038. newYaw = boneYaw - Math.PI * .75;
  73039. localTarget.z = Math.cos(newYaw) * xzlen;
  73040. localTarget.x = Math.sin(newYaw) * xzlen;
  73041. }
  73042. }
  73043. }
  73044. if (yaw != newYaw) {
  73045. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  73046. localTarget.addInPlace(bonePos);
  73047. target = localTarget;
  73048. }
  73049. }
  73050. }
  73051. var zaxis = BoneLookController._tmpVecs[5];
  73052. var xaxis = BoneLookController._tmpVecs[6];
  73053. var yaxis = BoneLookController._tmpVecs[7];
  73054. var _tmpQuat = BoneLookController._tmpQuat;
  73055. target.subtractToRef(bonePos, zaxis);
  73056. zaxis.normalize();
  73057. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  73058. xaxis.normalize();
  73059. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  73060. yaxis.normalize();
  73061. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  73062. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  73063. return;
  73064. }
  73065. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  73066. return;
  73067. }
  73068. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  73069. return;
  73070. }
  73071. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  73072. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  73073. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  73074. }
  73075. if (this.slerpAmount < 1) {
  73076. if (!this._slerping) {
  73077. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  73078. }
  73079. if (this._transformYawPitch) {
  73080. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  73081. }
  73082. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  73083. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  73084. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  73085. this._slerping = true;
  73086. }
  73087. else {
  73088. if (this._transformYawPitch) {
  73089. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  73090. }
  73091. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  73092. this._slerping = false;
  73093. }
  73094. };
  73095. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  73096. var angDiff = ang2 - ang1;
  73097. angDiff %= Math.PI * 2;
  73098. if (angDiff > Math.PI) {
  73099. angDiff -= Math.PI * 2;
  73100. }
  73101. else if (angDiff < -Math.PI) {
  73102. angDiff += Math.PI * 2;
  73103. }
  73104. return angDiff;
  73105. };
  73106. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  73107. ang1 %= (2 * Math.PI);
  73108. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  73109. ang2 %= (2 * Math.PI);
  73110. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  73111. var ab = 0;
  73112. if (ang1 < ang2) {
  73113. ab = ang2 - ang1;
  73114. }
  73115. else {
  73116. ab = ang1 - ang2;
  73117. }
  73118. if (ab > Math.PI) {
  73119. ab = Math.PI * 2 - ab;
  73120. }
  73121. return ab;
  73122. };
  73123. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  73124. ang %= (2 * Math.PI);
  73125. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  73126. ang1 %= (2 * Math.PI);
  73127. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  73128. ang2 %= (2 * Math.PI);
  73129. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  73130. if (ang1 < ang2) {
  73131. if (ang > ang1 && ang < ang2) {
  73132. return true;
  73133. }
  73134. }
  73135. else {
  73136. if (ang > ang2 && ang < ang1) {
  73137. return true;
  73138. }
  73139. }
  73140. return false;
  73141. };
  73142. 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()];
  73143. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  73144. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73145. return BoneLookController;
  73146. }());
  73147. BABYLON.BoneLookController = BoneLookController;
  73148. })(BABYLON || (BABYLON = {}));
  73149. //# sourceMappingURL=babylon.boneLookController.js.map
  73150. var BABYLON;
  73151. (function (BABYLON) {
  73152. var Skeleton = /** @class */ (function () {
  73153. function Skeleton(name, id, scene) {
  73154. this.name = name;
  73155. this.id = id;
  73156. this.bones = new Array();
  73157. this.needInitialSkinMatrix = false;
  73158. this._isDirty = true;
  73159. this._meshesWithPoseMatrix = new Array();
  73160. this._identity = BABYLON.Matrix.Identity();
  73161. this._ranges = {};
  73162. this._lastAbsoluteTransformsUpdateId = -1;
  73163. /**
  73164. * Specifies if the skeleton should be serialized.
  73165. */
  73166. this.doNotSerialize = false;
  73167. // Events
  73168. /**
  73169. * An event triggered before computing the skeleton's matrices
  73170. * @type {BABYLON.Observable}
  73171. */
  73172. this.onBeforeComputeObservable = new BABYLON.Observable();
  73173. this.bones = [];
  73174. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  73175. scene.skeletons.push(this);
  73176. //make sure it will recalculate the matrix next time prepare is called.
  73177. this._isDirty = true;
  73178. }
  73179. // Members
  73180. Skeleton.prototype.getTransformMatrices = function (mesh) {
  73181. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  73182. return mesh._bonesTransformMatrices;
  73183. }
  73184. if (!this._transformMatrices) {
  73185. this.prepare();
  73186. }
  73187. return this._transformMatrices;
  73188. };
  73189. Skeleton.prototype.getScene = function () {
  73190. return this._scene;
  73191. };
  73192. // Methods
  73193. /**
  73194. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  73195. */
  73196. Skeleton.prototype.toString = function (fullDetails) {
  73197. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  73198. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  73199. if (fullDetails) {
  73200. ret += ", Ranges: {";
  73201. var first = true;
  73202. for (var name_1 in this._ranges) {
  73203. if (first) {
  73204. ret += ", ";
  73205. first = false;
  73206. }
  73207. ret += name_1;
  73208. }
  73209. ret += "}";
  73210. }
  73211. return ret;
  73212. };
  73213. /**
  73214. * Get bone's index searching by name
  73215. * @param {string} name is bone's name to search for
  73216. * @return {number} Indice of the bone. Returns -1 if not found
  73217. */
  73218. Skeleton.prototype.getBoneIndexByName = function (name) {
  73219. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  73220. if (this.bones[boneIndex].name === name) {
  73221. return boneIndex;
  73222. }
  73223. }
  73224. return -1;
  73225. };
  73226. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  73227. // check name not already in use
  73228. if (!this._ranges[name]) {
  73229. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  73230. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73231. if (this.bones[i].animations[0]) {
  73232. this.bones[i].animations[0].createRange(name, from, to);
  73233. }
  73234. }
  73235. }
  73236. };
  73237. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  73238. if (deleteFrames === void 0) { deleteFrames = true; }
  73239. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73240. if (this.bones[i].animations[0]) {
  73241. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  73242. }
  73243. }
  73244. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  73245. };
  73246. Skeleton.prototype.getAnimationRange = function (name) {
  73247. return this._ranges[name];
  73248. };
  73249. /**
  73250. * Returns as an Array, all AnimationRanges defined on this skeleton
  73251. */
  73252. Skeleton.prototype.getAnimationRanges = function () {
  73253. var animationRanges = [];
  73254. var name;
  73255. var i = 0;
  73256. for (name in this._ranges) {
  73257. animationRanges[i] = this._ranges[name];
  73258. i++;
  73259. }
  73260. return animationRanges;
  73261. };
  73262. /**
  73263. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  73264. */
  73265. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  73266. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  73267. if (this._ranges[name] || !source.getAnimationRange(name)) {
  73268. return false;
  73269. }
  73270. var ret = true;
  73271. var frameOffset = this._getHighestAnimationFrame() + 1;
  73272. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  73273. var boneDict = {};
  73274. var sourceBones = source.bones;
  73275. var nBones;
  73276. var i;
  73277. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  73278. boneDict[sourceBones[i].name] = sourceBones[i];
  73279. }
  73280. if (this.bones.length !== sourceBones.length) {
  73281. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  73282. ret = false;
  73283. }
  73284. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  73285. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  73286. var boneName = this.bones[i].name;
  73287. var sourceBone = boneDict[boneName];
  73288. if (sourceBone) {
  73289. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  73290. }
  73291. else {
  73292. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  73293. ret = false;
  73294. }
  73295. }
  73296. // do not call createAnimationRange(), since it also is done to bones, which was already done
  73297. var range = source.getAnimationRange(name);
  73298. if (range) {
  73299. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  73300. }
  73301. return ret;
  73302. };
  73303. Skeleton.prototype.returnToRest = function () {
  73304. for (var index = 0; index < this.bones.length; index++) {
  73305. this.bones[index].returnToRest();
  73306. }
  73307. };
  73308. Skeleton.prototype._getHighestAnimationFrame = function () {
  73309. var ret = 0;
  73310. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73311. if (this.bones[i].animations[0]) {
  73312. var highest = this.bones[i].animations[0].getHighestFrame();
  73313. if (ret < highest) {
  73314. ret = highest;
  73315. }
  73316. }
  73317. }
  73318. return ret;
  73319. };
  73320. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  73321. var range = this.getAnimationRange(name);
  73322. if (!range) {
  73323. return null;
  73324. }
  73325. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  73326. };
  73327. Skeleton.prototype._markAsDirty = function () {
  73328. this._isDirty = true;
  73329. };
  73330. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  73331. this._meshesWithPoseMatrix.push(mesh);
  73332. };
  73333. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  73334. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  73335. if (index > -1) {
  73336. this._meshesWithPoseMatrix.splice(index, 1);
  73337. }
  73338. };
  73339. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  73340. this.onBeforeComputeObservable.notifyObservers(this);
  73341. for (var index = 0; index < this.bones.length; index++) {
  73342. var bone = this.bones[index];
  73343. var parentBone = bone.getParent();
  73344. if (parentBone) {
  73345. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  73346. }
  73347. else {
  73348. if (initialSkinMatrix) {
  73349. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  73350. }
  73351. else {
  73352. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  73353. }
  73354. }
  73355. if (bone._index !== -1) {
  73356. var mappedIndex = bone._index === null ? index : bone._index;
  73357. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  73358. }
  73359. }
  73360. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  73361. };
  73362. Skeleton.prototype.prepare = function () {
  73363. if (!this._isDirty) {
  73364. return;
  73365. }
  73366. if (this.needInitialSkinMatrix) {
  73367. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  73368. var mesh = this._meshesWithPoseMatrix[index];
  73369. var poseMatrix = mesh.getPoseMatrix();
  73370. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  73371. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  73372. }
  73373. if (this._synchronizedWithMesh !== mesh) {
  73374. this._synchronizedWithMesh = mesh;
  73375. // Prepare bones
  73376. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  73377. var bone = this.bones[boneIndex];
  73378. if (!bone.getParent()) {
  73379. var matrix = bone.getBaseMatrix();
  73380. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  73381. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  73382. }
  73383. }
  73384. }
  73385. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  73386. }
  73387. }
  73388. else {
  73389. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  73390. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  73391. }
  73392. this._computeTransformMatrices(this._transformMatrices, null);
  73393. }
  73394. this._isDirty = false;
  73395. this._scene._activeBones.addCount(this.bones.length, false);
  73396. };
  73397. Skeleton.prototype.getAnimatables = function () {
  73398. if (!this._animatables || this._animatables.length !== this.bones.length) {
  73399. this._animatables = [];
  73400. for (var index = 0; index < this.bones.length; index++) {
  73401. this._animatables.push(this.bones[index]);
  73402. }
  73403. }
  73404. return this._animatables;
  73405. };
  73406. Skeleton.prototype.clone = function (name, id) {
  73407. var result = new Skeleton(name, id || name, this._scene);
  73408. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  73409. for (var index = 0; index < this.bones.length; index++) {
  73410. var source = this.bones[index];
  73411. var parentBone = null;
  73412. var parent_1 = source.getParent();
  73413. if (parent_1) {
  73414. var parentIndex = this.bones.indexOf(parent_1);
  73415. parentBone = result.bones[parentIndex];
  73416. }
  73417. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  73418. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  73419. }
  73420. if (this._ranges) {
  73421. result._ranges = {};
  73422. for (var rangeName in this._ranges) {
  73423. var range = this._ranges[rangeName];
  73424. if (range) {
  73425. result._ranges[rangeName] = range.clone();
  73426. }
  73427. }
  73428. }
  73429. this._isDirty = true;
  73430. return result;
  73431. };
  73432. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  73433. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  73434. this.bones.forEach(function (bone) {
  73435. bone.animations.forEach(function (animation) {
  73436. animation.enableBlending = true;
  73437. animation.blendingSpeed = blendingSpeed;
  73438. });
  73439. });
  73440. };
  73441. Skeleton.prototype.dispose = function () {
  73442. this._meshesWithPoseMatrix = [];
  73443. // Animations
  73444. this.getScene().stopAnimation(this);
  73445. // Remove from scene
  73446. this.getScene().removeSkeleton(this);
  73447. };
  73448. Skeleton.prototype.serialize = function () {
  73449. var serializationObject = {};
  73450. serializationObject.name = this.name;
  73451. serializationObject.id = this.id;
  73452. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  73453. serializationObject.bones = [];
  73454. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  73455. for (var index = 0; index < this.bones.length; index++) {
  73456. var bone = this.bones[index];
  73457. var parent_2 = bone.getParent();
  73458. var serializedBone = {
  73459. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  73460. name: bone.name,
  73461. matrix: bone.getBaseMatrix().toArray(),
  73462. rest: bone.getRestPose().toArray()
  73463. };
  73464. serializationObject.bones.push(serializedBone);
  73465. if (bone.length) {
  73466. serializedBone.length = bone.length;
  73467. }
  73468. if (bone.animations && bone.animations.length > 0) {
  73469. serializedBone.animation = bone.animations[0].serialize();
  73470. }
  73471. serializationObject.ranges = [];
  73472. for (var name in this._ranges) {
  73473. var source = this._ranges[name];
  73474. if (!source) {
  73475. continue;
  73476. }
  73477. var range = {};
  73478. range.name = name;
  73479. range.from = source.from;
  73480. range.to = source.to;
  73481. serializationObject.ranges.push(range);
  73482. }
  73483. }
  73484. return serializationObject;
  73485. };
  73486. Skeleton.Parse = function (parsedSkeleton, scene) {
  73487. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  73488. if (parsedSkeleton.dimensionsAtRest) {
  73489. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  73490. }
  73491. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  73492. var index;
  73493. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  73494. var parsedBone = parsedSkeleton.bones[index];
  73495. var parentBone = null;
  73496. if (parsedBone.parentBoneIndex > -1) {
  73497. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  73498. }
  73499. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  73500. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  73501. if (parsedBone.length) {
  73502. bone.length = parsedBone.length;
  73503. }
  73504. if (parsedBone.animation) {
  73505. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  73506. }
  73507. }
  73508. // placed after bones, so createAnimationRange can cascade down
  73509. if (parsedSkeleton.ranges) {
  73510. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  73511. var data = parsedSkeleton.ranges[index];
  73512. skeleton.createAnimationRange(data.name, data.from, data.to);
  73513. }
  73514. }
  73515. return skeleton;
  73516. };
  73517. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  73518. if (forceUpdate === void 0) { forceUpdate = false; }
  73519. var renderId = this._scene.getRenderId();
  73520. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  73521. this.bones[0].computeAbsoluteTransforms();
  73522. this._lastAbsoluteTransformsUpdateId = renderId;
  73523. }
  73524. };
  73525. Skeleton.prototype.getPoseMatrix = function () {
  73526. var poseMatrix = null;
  73527. if (this._meshesWithPoseMatrix.length > 0) {
  73528. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  73529. }
  73530. return poseMatrix;
  73531. };
  73532. Skeleton.prototype.sortBones = function () {
  73533. var bones = new Array();
  73534. var visited = new Array(this.bones.length);
  73535. for (var index = 0; index < this.bones.length; index++) {
  73536. this._sortBones(index, bones, visited);
  73537. }
  73538. this.bones = bones;
  73539. };
  73540. Skeleton.prototype._sortBones = function (index, bones, visited) {
  73541. if (visited[index]) {
  73542. return;
  73543. }
  73544. visited[index] = true;
  73545. var bone = this.bones[index];
  73546. if (bone._index === undefined) {
  73547. bone._index = index;
  73548. }
  73549. var parentBone = bone.getParent();
  73550. if (parentBone) {
  73551. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  73552. }
  73553. bones.push(bone);
  73554. };
  73555. return Skeleton;
  73556. }());
  73557. BABYLON.Skeleton = Skeleton;
  73558. })(BABYLON || (BABYLON = {}));
  73559. //# sourceMappingURL=babylon.skeleton.js.map
  73560. var BABYLON;
  73561. (function (BABYLON) {
  73562. var SphericalPolynomial = /** @class */ (function () {
  73563. function SphericalPolynomial() {
  73564. this.x = BABYLON.Vector3.Zero();
  73565. this.y = BABYLON.Vector3.Zero();
  73566. this.z = BABYLON.Vector3.Zero();
  73567. this.xx = BABYLON.Vector3.Zero();
  73568. this.yy = BABYLON.Vector3.Zero();
  73569. this.zz = BABYLON.Vector3.Zero();
  73570. this.xy = BABYLON.Vector3.Zero();
  73571. this.yz = BABYLON.Vector3.Zero();
  73572. this.zx = BABYLON.Vector3.Zero();
  73573. }
  73574. SphericalPolynomial.prototype.addAmbient = function (color) {
  73575. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  73576. this.xx = this.xx.add(colorVector);
  73577. this.yy = this.yy.add(colorVector);
  73578. this.zz = this.zz.add(colorVector);
  73579. };
  73580. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  73581. var result = new SphericalPolynomial();
  73582. result.x = harmonics.L11.scale(1.02333);
  73583. result.y = harmonics.L1_1.scale(1.02333);
  73584. result.z = harmonics.L10.scale(1.02333);
  73585. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  73586. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  73587. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  73588. result.yz = harmonics.L2_1.scale(0.858086);
  73589. result.zx = harmonics.L21.scale(0.858086);
  73590. result.xy = harmonics.L2_2.scale(0.858086);
  73591. result.scale(1.0 / Math.PI);
  73592. return result;
  73593. };
  73594. SphericalPolynomial.prototype.scale = function (scale) {
  73595. this.x = this.x.scale(scale);
  73596. this.y = this.y.scale(scale);
  73597. this.z = this.z.scale(scale);
  73598. this.xx = this.xx.scale(scale);
  73599. this.yy = this.yy.scale(scale);
  73600. this.zz = this.zz.scale(scale);
  73601. this.yz = this.yz.scale(scale);
  73602. this.zx = this.zx.scale(scale);
  73603. this.xy = this.xy.scale(scale);
  73604. };
  73605. return SphericalPolynomial;
  73606. }());
  73607. BABYLON.SphericalPolynomial = SphericalPolynomial;
  73608. var SphericalHarmonics = /** @class */ (function () {
  73609. function SphericalHarmonics() {
  73610. this.L00 = BABYLON.Vector3.Zero();
  73611. this.L1_1 = BABYLON.Vector3.Zero();
  73612. this.L10 = BABYLON.Vector3.Zero();
  73613. this.L11 = BABYLON.Vector3.Zero();
  73614. this.L2_2 = BABYLON.Vector3.Zero();
  73615. this.L2_1 = BABYLON.Vector3.Zero();
  73616. this.L20 = BABYLON.Vector3.Zero();
  73617. this.L21 = BABYLON.Vector3.Zero();
  73618. this.L22 = BABYLON.Vector3.Zero();
  73619. }
  73620. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  73621. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  73622. var c = colorVector.scale(deltaSolidAngle);
  73623. this.L00 = this.L00.add(c.scale(0.282095));
  73624. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  73625. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  73626. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  73627. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  73628. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  73629. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  73630. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  73631. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  73632. };
  73633. SphericalHarmonics.prototype.scale = function (scale) {
  73634. this.L00 = this.L00.scale(scale);
  73635. this.L1_1 = this.L1_1.scale(scale);
  73636. this.L10 = this.L10.scale(scale);
  73637. this.L11 = this.L11.scale(scale);
  73638. this.L2_2 = this.L2_2.scale(scale);
  73639. this.L2_1 = this.L2_1.scale(scale);
  73640. this.L20 = this.L20.scale(scale);
  73641. this.L21 = this.L21.scale(scale);
  73642. this.L22 = this.L22.scale(scale);
  73643. };
  73644. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  73645. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  73646. //
  73647. // E_lm = A_l * L_lm
  73648. //
  73649. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  73650. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  73651. // the scaling factors are given in equation 9.
  73652. // Constant (Band 0)
  73653. this.L00 = this.L00.scale(3.141593);
  73654. // Linear (Band 1)
  73655. this.L1_1 = this.L1_1.scale(2.094395);
  73656. this.L10 = this.L10.scale(2.094395);
  73657. this.L11 = this.L11.scale(2.094395);
  73658. // Quadratic (Band 2)
  73659. this.L2_2 = this.L2_2.scale(0.785398);
  73660. this.L2_1 = this.L2_1.scale(0.785398);
  73661. this.L20 = this.L20.scale(0.785398);
  73662. this.L21 = this.L21.scale(0.785398);
  73663. this.L22 = this.L22.scale(0.785398);
  73664. };
  73665. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  73666. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  73667. // L = (1/pi) * E * rho
  73668. //
  73669. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  73670. this.scale(1.0 / Math.PI);
  73671. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  73672. // (The pixel shader must apply albedo after texture fetches, etc).
  73673. };
  73674. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  73675. var result = new SphericalHarmonics();
  73676. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  73677. result.L1_1 = polynomial.y.scale(0.977204);
  73678. result.L10 = polynomial.z.scale(0.977204);
  73679. result.L11 = polynomial.x.scale(0.977204);
  73680. result.L2_2 = polynomial.xy.scale(1.16538);
  73681. result.L2_1 = polynomial.yz.scale(1.16538);
  73682. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  73683. result.L21 = polynomial.zx.scale(1.16538);
  73684. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  73685. result.scale(Math.PI);
  73686. return result;
  73687. };
  73688. return SphericalHarmonics;
  73689. }());
  73690. BABYLON.SphericalHarmonics = SphericalHarmonics;
  73691. })(BABYLON || (BABYLON = {}));
  73692. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  73693. var BABYLON;
  73694. (function (BABYLON) {
  73695. var FileFaceOrientation = /** @class */ (function () {
  73696. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  73697. this.name = name;
  73698. this.worldAxisForNormal = worldAxisForNormal;
  73699. this.worldAxisForFileX = worldAxisForFileX;
  73700. this.worldAxisForFileY = worldAxisForFileY;
  73701. }
  73702. return FileFaceOrientation;
  73703. }());
  73704. ;
  73705. /**
  73706. * Helper class dealing with the extraction of spherical polynomial dataArray
  73707. * from a cube map.
  73708. */
  73709. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  73710. function CubeMapToSphericalPolynomialTools() {
  73711. }
  73712. /**
  73713. * Converts a texture to the according Spherical Polynomial data.
  73714. * This extracts the first 3 orders only as they are the only one used in the lighting.
  73715. *
  73716. * @param texture The texture to extract the information from.
  73717. * @return The Spherical Polynomial data.
  73718. */
  73719. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  73720. if (!texture.isCube) {
  73721. // Only supports cube Textures currently.
  73722. return null;
  73723. }
  73724. var size = texture.getSize().width;
  73725. var right = texture.readPixels(0);
  73726. var left = texture.readPixels(1);
  73727. var up;
  73728. var down;
  73729. if (texture.isRenderTarget) {
  73730. up = texture.readPixels(3);
  73731. down = texture.readPixels(2);
  73732. }
  73733. else {
  73734. up = texture.readPixels(2);
  73735. down = texture.readPixels(3);
  73736. }
  73737. var front = texture.readPixels(4);
  73738. var back = texture.readPixels(5);
  73739. var gammaSpace = texture.gammaSpace;
  73740. // Always read as RGBA.
  73741. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  73742. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73743. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73744. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73745. }
  73746. var cubeInfo = {
  73747. size: size,
  73748. right: right,
  73749. left: left,
  73750. up: up,
  73751. down: down,
  73752. front: front,
  73753. back: back,
  73754. format: format,
  73755. type: type,
  73756. gammaSpace: gammaSpace,
  73757. };
  73758. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  73759. };
  73760. /**
  73761. * Converts a cubemap to the according Spherical Polynomial data.
  73762. * This extracts the first 3 orders only as they are the only one used in the lighting.
  73763. *
  73764. * @param cubeInfo The Cube map to extract the information from.
  73765. * @return The Spherical Polynomial data.
  73766. */
  73767. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  73768. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  73769. var totalSolidAngle = 0.0;
  73770. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  73771. var du = 2.0 / cubeInfo.size;
  73772. var dv = du;
  73773. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  73774. var minUV = du * 0.5 - 1.0;
  73775. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73776. var fileFace = this.FileFaces[faceIndex];
  73777. var dataArray = cubeInfo[fileFace.name];
  73778. var v = minUV;
  73779. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  73780. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  73781. // Because SP is still linear, so summation is fine in that basis.
  73782. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  73783. for (var y = 0; y < cubeInfo.size; y++) {
  73784. var u = minUV;
  73785. for (var x = 0; x < cubeInfo.size; x++) {
  73786. // World direction (not normalised)
  73787. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  73788. worldDirection.normalize();
  73789. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  73790. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  73791. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  73792. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  73793. // Handle Integer types.
  73794. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73795. r /= 255;
  73796. g /= 255;
  73797. b /= 255;
  73798. }
  73799. // Handle Gamma space textures.
  73800. if (cubeInfo.gammaSpace) {
  73801. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  73802. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  73803. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  73804. }
  73805. var color = new BABYLON.Color3(r, g, b);
  73806. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  73807. totalSolidAngle += deltaSolidAngle;
  73808. u += du;
  73809. }
  73810. v += dv;
  73811. }
  73812. }
  73813. // Solid angle for entire sphere is 4*pi
  73814. var sphereSolidAngle = 4.0 * Math.PI;
  73815. // Adjust the solid angle to allow for how many faces we processed.
  73816. var facesProcessed = 6.0;
  73817. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  73818. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  73819. // This is needed because the numerical integration over the cube uses a
  73820. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  73821. // and also to compensate for accumulative error due to float precision in the summation.
  73822. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  73823. sphericalHarmonics.scale(correctionFactor);
  73824. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  73825. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  73826. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  73827. };
  73828. CubeMapToSphericalPolynomialTools.FileFaces = [
  73829. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  73830. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  73831. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  73832. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  73833. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  73834. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  73835. ];
  73836. return CubeMapToSphericalPolynomialTools;
  73837. }());
  73838. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  73839. })(BABYLON || (BABYLON = {}));
  73840. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  73841. var BABYLON;
  73842. (function (BABYLON) {
  73843. /**
  73844. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  73845. */
  73846. var PanoramaToCubeMapTools = /** @class */ (function () {
  73847. function PanoramaToCubeMapTools() {
  73848. }
  73849. /**
  73850. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  73851. *
  73852. * @param float32Array The source data.
  73853. * @param inputWidth The width of the input panorama.
  73854. * @param inputhHeight The height of the input panorama.
  73855. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  73856. * @return The cubemap data
  73857. */
  73858. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  73859. if (!float32Array) {
  73860. throw "ConvertPanoramaToCubemap: input cannot be null";
  73861. }
  73862. if (float32Array.length != inputWidth * inputHeight * 3) {
  73863. throw "ConvertPanoramaToCubemap: input size is wrong";
  73864. }
  73865. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  73866. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  73867. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  73868. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  73869. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  73870. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  73871. return {
  73872. front: textureFront,
  73873. back: textureBack,
  73874. left: textureLeft,
  73875. right: textureRight,
  73876. up: textureUp,
  73877. down: textureDown,
  73878. size: size,
  73879. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  73880. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  73881. gammaSpace: false,
  73882. };
  73883. };
  73884. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  73885. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  73886. var textureArray = new Float32Array(buffer);
  73887. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  73888. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  73889. var dy = 1 / texSize;
  73890. var fy = 0;
  73891. for (var y = 0; y < texSize; y++) {
  73892. var xv1 = faceData[0];
  73893. var xv2 = faceData[2];
  73894. for (var x = 0; x < texSize; x++) {
  73895. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  73896. v.normalize();
  73897. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  73898. // 3 channels per pixels
  73899. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  73900. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  73901. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  73902. xv1 = xv1.add(rotDX1);
  73903. xv2 = xv2.add(rotDX2);
  73904. }
  73905. fy += dy;
  73906. }
  73907. return textureArray;
  73908. };
  73909. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  73910. var theta = Math.atan2(vDir.z, vDir.x);
  73911. var phi = Math.acos(vDir.y);
  73912. while (theta < -Math.PI)
  73913. theta += 2 * Math.PI;
  73914. while (theta > Math.PI)
  73915. theta -= 2 * Math.PI;
  73916. var dx = theta / Math.PI;
  73917. var dy = phi / Math.PI;
  73918. // recenter.
  73919. dx = dx * 0.5 + 0.5;
  73920. var px = Math.round(dx * inputWidth);
  73921. if (px < 0)
  73922. px = 0;
  73923. else if (px >= inputWidth)
  73924. px = inputWidth - 1;
  73925. var py = Math.round(dy * inputHeight);
  73926. if (py < 0)
  73927. py = 0;
  73928. else if (py >= inputHeight)
  73929. py = inputHeight - 1;
  73930. var inputY = (inputHeight - py - 1);
  73931. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  73932. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  73933. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  73934. return {
  73935. r: r,
  73936. g: g,
  73937. b: b
  73938. };
  73939. };
  73940. PanoramaToCubeMapTools.FACE_FRONT = [
  73941. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73942. new BABYLON.Vector3(1.0, -1.0, -1.0),
  73943. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  73944. new BABYLON.Vector3(1.0, 1.0, -1.0)
  73945. ];
  73946. PanoramaToCubeMapTools.FACE_BACK = [
  73947. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73948. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73949. new BABYLON.Vector3(1.0, 1.0, 1.0),
  73950. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  73951. ];
  73952. PanoramaToCubeMapTools.FACE_RIGHT = [
  73953. new BABYLON.Vector3(1.0, -1.0, -1.0),
  73954. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73955. new BABYLON.Vector3(1.0, 1.0, -1.0),
  73956. new BABYLON.Vector3(1.0, 1.0, 1.0)
  73957. ];
  73958. PanoramaToCubeMapTools.FACE_LEFT = [
  73959. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73960. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73961. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  73962. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  73963. ];
  73964. PanoramaToCubeMapTools.FACE_DOWN = [
  73965. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  73966. new BABYLON.Vector3(1.0, 1.0, -1.0),
  73967. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  73968. new BABYLON.Vector3(1.0, 1.0, 1.0)
  73969. ];
  73970. PanoramaToCubeMapTools.FACE_UP = [
  73971. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73972. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73973. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73974. new BABYLON.Vector3(1.0, -1.0, -1.0)
  73975. ];
  73976. return PanoramaToCubeMapTools;
  73977. }());
  73978. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  73979. })(BABYLON || (BABYLON = {}));
  73980. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  73981. var BABYLON;
  73982. (function (BABYLON) {
  73983. ;
  73984. /**
  73985. * This groups tools to convert HDR texture to native colors array.
  73986. */
  73987. var HDRTools = /** @class */ (function () {
  73988. function HDRTools() {
  73989. }
  73990. HDRTools.Ldexp = function (mantissa, exponent) {
  73991. if (exponent > 1023) {
  73992. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  73993. }
  73994. if (exponent < -1074) {
  73995. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  73996. }
  73997. return mantissa * Math.pow(2, exponent);
  73998. };
  73999. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  74000. if (exponent > 0) {
  74001. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  74002. float32array[index + 0] = red * exponent;
  74003. float32array[index + 1] = green * exponent;
  74004. float32array[index + 2] = blue * exponent;
  74005. }
  74006. else {
  74007. float32array[index + 0] = 0;
  74008. float32array[index + 1] = 0;
  74009. float32array[index + 2] = 0;
  74010. }
  74011. };
  74012. HDRTools.readStringLine = function (uint8array, startIndex) {
  74013. var line = "";
  74014. var character = "";
  74015. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  74016. character = String.fromCharCode(uint8array[i]);
  74017. if (character == "\n") {
  74018. break;
  74019. }
  74020. line += character;
  74021. }
  74022. return line;
  74023. };
  74024. /**
  74025. * Reads header information from an RGBE texture stored in a native array.
  74026. * More information on this format are available here:
  74027. * https://en.wikipedia.org/wiki/RGBE_image_format
  74028. *
  74029. * @param uint8array The binary file stored in native array.
  74030. * @return The header information.
  74031. */
  74032. HDRTools.RGBE_ReadHeader = function (uint8array) {
  74033. var height = 0;
  74034. var width = 0;
  74035. var line = this.readStringLine(uint8array, 0);
  74036. if (line[0] != '#' || line[1] != '?') {
  74037. throw "Bad HDR Format.";
  74038. }
  74039. var endOfHeader = false;
  74040. var findFormat = false;
  74041. var lineIndex = 0;
  74042. do {
  74043. lineIndex += (line.length + 1);
  74044. line = this.readStringLine(uint8array, lineIndex);
  74045. if (line == "FORMAT=32-bit_rle_rgbe") {
  74046. findFormat = true;
  74047. }
  74048. else if (line.length == 0) {
  74049. endOfHeader = true;
  74050. }
  74051. } while (!endOfHeader);
  74052. if (!findFormat) {
  74053. throw "HDR Bad header format, unsupported FORMAT";
  74054. }
  74055. lineIndex += (line.length + 1);
  74056. line = this.readStringLine(uint8array, lineIndex);
  74057. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  74058. var match = sizeRegexp.exec(line);
  74059. // TODO. Support +Y and -X if needed.
  74060. if (!match || match.length < 3) {
  74061. throw "HDR Bad header format, no size";
  74062. }
  74063. width = parseInt(match[2]);
  74064. height = parseInt(match[1]);
  74065. if (width < 8 || width > 0x7fff) {
  74066. throw "HDR Bad header format, unsupported size";
  74067. }
  74068. lineIndex += (line.length + 1);
  74069. return {
  74070. height: height,
  74071. width: width,
  74072. dataPosition: lineIndex
  74073. };
  74074. };
  74075. /**
  74076. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  74077. * This RGBE texture needs to store the information as a panorama.
  74078. *
  74079. * More information on this format are available here:
  74080. * https://en.wikipedia.org/wiki/RGBE_image_format
  74081. *
  74082. * @param buffer The binary file stored in an array buffer.
  74083. * @param size The expected size of the extracted cubemap.
  74084. * @return The Cube Map information.
  74085. */
  74086. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  74087. var uint8array = new Uint8Array(buffer);
  74088. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  74089. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  74090. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  74091. return cubeMapData;
  74092. };
  74093. /**
  74094. * Returns the pixels data extracted from an RGBE texture.
  74095. * This pixels will be stored left to right up to down in the R G B order in one array.
  74096. *
  74097. * More information on this format are available here:
  74098. * https://en.wikipedia.org/wiki/RGBE_image_format
  74099. *
  74100. * @param uint8array The binary file stored in an array buffer.
  74101. * @param hdrInfo The header information of the file.
  74102. * @return The pixels data in RGB right to left up to down order.
  74103. */
  74104. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  74105. // Keep for multi format supports.
  74106. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  74107. };
  74108. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  74109. var num_scanlines = hdrInfo.height;
  74110. var scanline_width = hdrInfo.width;
  74111. var a, b, c, d, count;
  74112. var dataIndex = hdrInfo.dataPosition;
  74113. var index = 0, endIndex = 0, i = 0;
  74114. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  74115. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  74116. // 3 channels of 4 bytes per pixel in float.
  74117. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  74118. var resultArray = new Float32Array(resultBuffer);
  74119. // read in each successive scanline
  74120. while (num_scanlines > 0) {
  74121. a = uint8array[dataIndex++];
  74122. b = uint8array[dataIndex++];
  74123. c = uint8array[dataIndex++];
  74124. d = uint8array[dataIndex++];
  74125. if (a != 2 || b != 2 || (c & 0x80)) {
  74126. // this file is not run length encoded
  74127. throw "HDR Bad header format, not RLE";
  74128. }
  74129. if (((c << 8) | d) != scanline_width) {
  74130. throw "HDR Bad header format, wrong scan line width";
  74131. }
  74132. index = 0;
  74133. // read each of the four channels for the scanline into the buffer
  74134. for (i = 0; i < 4; i++) {
  74135. endIndex = (i + 1) * scanline_width;
  74136. while (index < endIndex) {
  74137. a = uint8array[dataIndex++];
  74138. b = uint8array[dataIndex++];
  74139. if (a > 128) {
  74140. // a run of the same value
  74141. count = a - 128;
  74142. if ((count == 0) || (count > endIndex - index)) {
  74143. throw "HDR Bad Format, bad scanline data (run)";
  74144. }
  74145. while (count-- > 0) {
  74146. scanLineArray[index++] = b;
  74147. }
  74148. }
  74149. else {
  74150. // a non-run
  74151. count = a;
  74152. if ((count == 0) || (count > endIndex - index)) {
  74153. throw "HDR Bad Format, bad scanline data (non-run)";
  74154. }
  74155. scanLineArray[index++] = b;
  74156. if (--count > 0) {
  74157. for (var j = 0; j < count; j++) {
  74158. scanLineArray[index++] = uint8array[dataIndex++];
  74159. }
  74160. }
  74161. }
  74162. }
  74163. }
  74164. // now convert data from buffer into floats
  74165. for (i = 0; i < scanline_width; i++) {
  74166. a = scanLineArray[i];
  74167. b = scanLineArray[i + scanline_width];
  74168. c = scanLineArray[i + 2 * scanline_width];
  74169. d = scanLineArray[i + 3 * scanline_width];
  74170. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  74171. }
  74172. num_scanlines--;
  74173. }
  74174. return resultArray;
  74175. };
  74176. return HDRTools;
  74177. }());
  74178. BABYLON.HDRTools = HDRTools;
  74179. })(BABYLON || (BABYLON = {}));
  74180. //# sourceMappingURL=babylon.hdr.js.map
  74181. var BABYLON;
  74182. (function (BABYLON) {
  74183. /**
  74184. * This represents a texture coming from an HDR input.
  74185. *
  74186. * The only supported format is currently panorama picture stored in RGBE format.
  74187. * Example of such files can be found on HDRLib: http://hdrlib.com/
  74188. */
  74189. var HDRCubeTexture = /** @class */ (function (_super) {
  74190. __extends(HDRCubeTexture, _super);
  74191. /**
  74192. * Instantiates an HDRTexture from the following parameters.
  74193. *
  74194. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  74195. * @param scene The scene the texture will be used in
  74196. * @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.
  74197. * @param noMipmap Forces to not generate the mipmap if true
  74198. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  74199. * @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)
  74200. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  74201. */
  74202. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  74203. if (noMipmap === void 0) { noMipmap = false; }
  74204. if (generateHarmonics === void 0) { generateHarmonics = true; }
  74205. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  74206. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  74207. if (onLoad === void 0) { onLoad = null; }
  74208. if (onError === void 0) { onError = null; }
  74209. var _this = _super.call(this, scene) || this;
  74210. _this._useInGammaSpace = false;
  74211. _this._generateHarmonics = true;
  74212. _this._isBABYLONPreprocessed = false;
  74213. _this._onLoad = null;
  74214. _this._onError = null;
  74215. /**
  74216. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  74217. */
  74218. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  74219. /**
  74220. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  74221. * This is usefull at run time to apply the good shader.
  74222. */
  74223. _this.isPMREM = false;
  74224. _this._isBlocking = true;
  74225. /**
  74226. * Gets or sets the center of the bounding box associated with the cube texture
  74227. * It must define where the camera used to render the texture was set
  74228. */
  74229. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  74230. if (!url) {
  74231. return _this;
  74232. }
  74233. _this.name = url;
  74234. _this.url = url;
  74235. _this.hasAlpha = false;
  74236. _this.isCube = true;
  74237. _this._textureMatrix = BABYLON.Matrix.Identity();
  74238. _this._onLoad = onLoad;
  74239. _this._onError = onError;
  74240. _this.gammaSpace = false;
  74241. var caps = scene.getEngine().getCaps();
  74242. if (size) {
  74243. _this._isBABYLONPreprocessed = false;
  74244. _this._noMipmap = noMipmap;
  74245. _this._size = size;
  74246. _this._useInGammaSpace = useInGammaSpace;
  74247. _this._usePMREMGenerator = usePMREMGenerator &&
  74248. caps.textureLOD &&
  74249. caps.textureFloat &&
  74250. !_this._useInGammaSpace;
  74251. }
  74252. else {
  74253. _this._isBABYLONPreprocessed = true;
  74254. _this._noMipmap = false;
  74255. _this._useInGammaSpace = false;
  74256. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  74257. !_this._useInGammaSpace;
  74258. }
  74259. _this.isPMREM = _this._usePMREMGenerator;
  74260. _this._texture = _this._getFromCache(url, _this._noMipmap);
  74261. if (!_this._texture) {
  74262. if (!scene.useDelayedTextureLoading) {
  74263. _this.loadTexture();
  74264. }
  74265. else {
  74266. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  74267. }
  74268. }
  74269. return _this;
  74270. }
  74271. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  74272. /**
  74273. * Gets wether or not the texture is blocking during loading.
  74274. */
  74275. get: function () {
  74276. return this._isBlocking;
  74277. },
  74278. /**
  74279. * Sets wether or not the texture is blocking during loading.
  74280. */
  74281. set: function (value) {
  74282. this._isBlocking = value;
  74283. },
  74284. enumerable: true,
  74285. configurable: true
  74286. });
  74287. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  74288. get: function () {
  74289. return this._boundingBoxSize;
  74290. },
  74291. /**
  74292. * Gets or sets the size of the bounding box associated with the cube texture
  74293. * When defined, the cubemap will switch to local mode
  74294. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  74295. * @example https://www.babylonjs-playground.com/#RNASML
  74296. */
  74297. set: function (value) {
  74298. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  74299. return;
  74300. }
  74301. this._boundingBoxSize = value;
  74302. var scene = this.getScene();
  74303. if (scene) {
  74304. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  74305. }
  74306. },
  74307. enumerable: true,
  74308. configurable: true
  74309. });
  74310. /**
  74311. * Occurs when the file is a preprocessed .babylon.hdr file.
  74312. */
  74313. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  74314. var _this = this;
  74315. var mipLevels = 0;
  74316. var floatArrayView = null;
  74317. var scene = this.getScene();
  74318. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  74319. var mips = new Array();
  74320. if (!floatArrayView) {
  74321. return mips;
  74322. }
  74323. var startIndex = 30;
  74324. for (var level = 0; level < mipLevels; level++) {
  74325. mips.push([]);
  74326. // Fill each pixel of the mip level.
  74327. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  74328. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74329. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  74330. mips[level].push(faceData);
  74331. startIndex += faceSize;
  74332. }
  74333. }
  74334. return mips;
  74335. } : null;
  74336. var callback = function (buffer) {
  74337. var scene = _this.getScene();
  74338. if (!scene) {
  74339. return null;
  74340. }
  74341. // Create Native Array Views
  74342. var intArrayView = new Int32Array(buffer);
  74343. floatArrayView = new Float32Array(buffer);
  74344. // Fill header.
  74345. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  74346. _this._size = intArrayView[1]; // CubeMap max mip face size.
  74347. // Update Texture Information.
  74348. if (!_this._texture) {
  74349. return null;
  74350. }
  74351. _this._texture.updateSize(_this._size, _this._size);
  74352. // Fill polynomial information.
  74353. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  74354. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  74355. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  74356. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  74357. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  74358. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  74359. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  74360. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  74361. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  74362. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  74363. _this.sphericalPolynomial = sphericalPolynomial;
  74364. // Fill pixel data.
  74365. mipLevels = intArrayView[29]; // Number of mip levels.
  74366. var startIndex = 30;
  74367. var data = [];
  74368. var faceSize = Math.pow(_this._size, 2) * 3;
  74369. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74370. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  74371. startIndex += faceSize;
  74372. }
  74373. var results = [];
  74374. var byteArray = null;
  74375. // Push each faces.
  74376. for (var k = 0; k < 6; k++) {
  74377. var dataFace = null;
  74378. // To be deprecated.
  74379. if (version === 1) {
  74380. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  74381. dataFace = data[j];
  74382. }
  74383. // If special cases.
  74384. if (!mipmapGenerator && dataFace) {
  74385. if (!scene.getEngine().getCaps().textureFloat) {
  74386. // 3 channels of 1 bytes per pixel in bytes.
  74387. var byteBuffer = new ArrayBuffer(faceSize);
  74388. byteArray = new Uint8Array(byteBuffer);
  74389. }
  74390. for (var i = 0; i < _this._size * _this._size; i++) {
  74391. // Put in gamma space if requested.
  74392. if (_this._useInGammaSpace) {
  74393. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  74394. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  74395. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  74396. }
  74397. // Convert to int texture for fallback.
  74398. if (byteArray) {
  74399. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  74400. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  74401. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  74402. // May use luminance instead if the result is not accurate.
  74403. var max = Math.max(Math.max(r, g), b);
  74404. if (max > 255) {
  74405. var scale = 255 / max;
  74406. r *= scale;
  74407. g *= scale;
  74408. b *= scale;
  74409. }
  74410. byteArray[(i * 3) + 0] = r;
  74411. byteArray[(i * 3) + 1] = g;
  74412. byteArray[(i * 3) + 2] = b;
  74413. }
  74414. }
  74415. }
  74416. // Fill the array accordingly.
  74417. if (byteArray) {
  74418. results.push(byteArray);
  74419. }
  74420. else {
  74421. results.push(dataFace);
  74422. }
  74423. }
  74424. return results;
  74425. };
  74426. if (scene) {
  74427. 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);
  74428. }
  74429. };
  74430. /**
  74431. * Occurs when the file is raw .hdr file.
  74432. */
  74433. HDRCubeTexture.prototype.loadHDRTexture = function () {
  74434. var _this = this;
  74435. var callback = function (buffer) {
  74436. var scene = _this.getScene();
  74437. if (!scene) {
  74438. return null;
  74439. }
  74440. // Extract the raw linear data.
  74441. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  74442. // Generate harmonics if needed.
  74443. if (_this._generateHarmonics) {
  74444. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  74445. _this.sphericalPolynomial = sphericalPolynomial;
  74446. }
  74447. var results = [];
  74448. var byteArray = null;
  74449. // Push each faces.
  74450. for (var j = 0; j < 6; j++) {
  74451. // Create uintarray fallback.
  74452. if (!scene.getEngine().getCaps().textureFloat) {
  74453. // 3 channels of 1 bytes per pixel in bytes.
  74454. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  74455. byteArray = new Uint8Array(byteBuffer);
  74456. }
  74457. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  74458. // If special cases.
  74459. if (_this._useInGammaSpace || byteArray) {
  74460. for (var i = 0; i < _this._size * _this._size; i++) {
  74461. // Put in gamma space if requested.
  74462. if (_this._useInGammaSpace) {
  74463. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  74464. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  74465. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  74466. }
  74467. // Convert to int texture for fallback.
  74468. if (byteArray) {
  74469. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  74470. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  74471. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  74472. // May use luminance instead if the result is not accurate.
  74473. var max = Math.max(Math.max(r, g), b);
  74474. if (max > 255) {
  74475. var scale = 255 / max;
  74476. r *= scale;
  74477. g *= scale;
  74478. b *= scale;
  74479. }
  74480. byteArray[(i * 3) + 0] = r;
  74481. byteArray[(i * 3) + 1] = g;
  74482. byteArray[(i * 3) + 2] = b;
  74483. }
  74484. }
  74485. }
  74486. if (byteArray) {
  74487. results.push(byteArray);
  74488. }
  74489. else {
  74490. results.push(dataFace);
  74491. }
  74492. }
  74493. return results;
  74494. };
  74495. var mipmapGenerator = null;
  74496. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  74497. // if (!this._noMipmap &&
  74498. // this._usePMREMGenerator) {
  74499. // mipmapGenerator = (data: ArrayBufferView[]) => {
  74500. // // Custom setup of the generator matching with the PBR shader values.
  74501. // var generator = new BABYLON.PMREMGenerator(data,
  74502. // this._size,
  74503. // this._size,
  74504. // 0,
  74505. // 3,
  74506. // this.getScene().getEngine().getCaps().textureFloat,
  74507. // 2048,
  74508. // 0.25,
  74509. // false,
  74510. // true);
  74511. // return generator.filterCubeMap();
  74512. // };
  74513. // }
  74514. var scene = this.getScene();
  74515. if (scene) {
  74516. 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);
  74517. }
  74518. };
  74519. /**
  74520. * Starts the loading process of the texture.
  74521. */
  74522. HDRCubeTexture.prototype.loadTexture = function () {
  74523. if (this._isBABYLONPreprocessed) {
  74524. this.loadBabylonTexture();
  74525. }
  74526. else {
  74527. this.loadHDRTexture();
  74528. }
  74529. };
  74530. HDRCubeTexture.prototype.clone = function () {
  74531. var scene = this.getScene();
  74532. if (!scene) {
  74533. return this;
  74534. }
  74535. var size = (this._isBABYLONPreprocessed ? null : this._size);
  74536. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  74537. // Base texture
  74538. newTexture.level = this.level;
  74539. newTexture.wrapU = this.wrapU;
  74540. newTexture.wrapV = this.wrapV;
  74541. newTexture.coordinatesIndex = this.coordinatesIndex;
  74542. newTexture.coordinatesMode = this.coordinatesMode;
  74543. return newTexture;
  74544. };
  74545. // Methods
  74546. HDRCubeTexture.prototype.delayLoad = function () {
  74547. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  74548. return;
  74549. }
  74550. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  74551. this._texture = this._getFromCache(this.url, this._noMipmap);
  74552. if (!this._texture) {
  74553. this.loadTexture();
  74554. }
  74555. };
  74556. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  74557. return this._textureMatrix;
  74558. };
  74559. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  74560. this._textureMatrix = value;
  74561. };
  74562. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  74563. var texture = null;
  74564. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  74565. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  74566. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  74567. texture.name = parsedTexture.name;
  74568. texture.hasAlpha = parsedTexture.hasAlpha;
  74569. texture.level = parsedTexture.level;
  74570. texture.coordinatesMode = parsedTexture.coordinatesMode;
  74571. texture.isBlocking = parsedTexture.isBlocking;
  74572. }
  74573. if (texture) {
  74574. if (parsedTexture.boundingBoxPosition) {
  74575. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  74576. }
  74577. if (parsedTexture.boundingBoxSize) {
  74578. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  74579. }
  74580. }
  74581. return texture;
  74582. };
  74583. HDRCubeTexture.prototype.serialize = function () {
  74584. if (!this.name) {
  74585. return null;
  74586. }
  74587. var serializationObject = {};
  74588. serializationObject.name = this.name;
  74589. serializationObject.hasAlpha = this.hasAlpha;
  74590. serializationObject.isCube = true;
  74591. serializationObject.level = this.level;
  74592. serializationObject.size = this._size;
  74593. serializationObject.coordinatesMode = this.coordinatesMode;
  74594. serializationObject.useInGammaSpace = this._useInGammaSpace;
  74595. serializationObject.generateHarmonics = this._generateHarmonics;
  74596. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  74597. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  74598. serializationObject.customType = "BABYLON.HDRCubeTexture";
  74599. serializationObject.noMipmap = this._noMipmap;
  74600. serializationObject.isBlocking = this._isBlocking;
  74601. return serializationObject;
  74602. };
  74603. /**
  74604. * Saves as a file the data contained in the texture in a binary format.
  74605. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  74606. * as the spherical used in the lighting.
  74607. * @param url The HDR file url.
  74608. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  74609. * @param onError Method called if any error happens during download.
  74610. * @return The packed binary data.
  74611. */
  74612. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  74613. if (onError === void 0) { onError = null; }
  74614. var callback = function (buffer) {
  74615. var data = new Blob([buffer], { type: 'application/octet-stream' });
  74616. // Returns a URL you can use as a href.
  74617. var objUrl = window.URL.createObjectURL(data);
  74618. // Simulates a link to it and click to dowload.
  74619. var a = document.createElement("a");
  74620. document.body.appendChild(a);
  74621. a.style.display = "none";
  74622. a.href = objUrl;
  74623. a.download = "envmap.babylon.hdr";
  74624. a.click();
  74625. };
  74626. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  74627. };
  74628. /**
  74629. * Serializes the data contained in the texture in a binary format.
  74630. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  74631. * as the spherical used in the lighting.
  74632. * @param url The HDR file url.
  74633. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  74634. * @param onError Method called if any error happens during download.
  74635. * @return The packed binary data.
  74636. */
  74637. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  74638. if (onError === void 0) { onError = null; }
  74639. // Needs the url tho create the texture.
  74640. if (!url) {
  74641. return;
  74642. }
  74643. // Check Power of two size.
  74644. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  74645. return;
  74646. }
  74647. // Coming Back in 3.x.
  74648. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  74649. };
  74650. HDRCubeTexture._facesMapping = [
  74651. "right",
  74652. "left",
  74653. "up",
  74654. "down",
  74655. "front",
  74656. "back"
  74657. ];
  74658. return HDRCubeTexture;
  74659. }(BABYLON.BaseTexture));
  74660. BABYLON.HDRCubeTexture = HDRCubeTexture;
  74661. })(BABYLON || (BABYLON = {}));
  74662. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  74663. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  74664. // Huge respect for a such great lib.
  74665. // Earcut license:
  74666. // Copyright (c) 2016, Mapbox
  74667. //
  74668. // Permission to use, copy, modify, and/or distribute this software for any purpose
  74669. // with or without fee is hereby granted, provided that the above copyright notice
  74670. // and this permission notice appear in all copies.
  74671. //
  74672. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  74673. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  74674. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  74675. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  74676. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  74677. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  74678. // THIS SOFTWARE.
  74679. var Earcut;
  74680. (function (Earcut) {
  74681. /**
  74682. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  74683. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  74684. * @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).
  74685. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  74686. */
  74687. function earcut(data, holeIndices, dim) {
  74688. dim = dim || 2;
  74689. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  74690. if (!outerNode)
  74691. return triangles;
  74692. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  74693. if (hasHoles)
  74694. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  74695. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  74696. if (data.length > 80 * dim) {
  74697. minX = maxX = data[0];
  74698. minY = maxY = data[1];
  74699. for (var i = dim; i < outerLen; i += dim) {
  74700. x = data[i];
  74701. y = data[i + 1];
  74702. if (x < minX)
  74703. minX = x;
  74704. if (y < minY)
  74705. minY = y;
  74706. if (x > maxX)
  74707. maxX = x;
  74708. if (y > maxY)
  74709. maxY = y;
  74710. }
  74711. // minX, minY and size are later used to transform coords into integers for z-order calculation
  74712. size = Math.max(maxX - minX, maxY - minY);
  74713. }
  74714. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  74715. return triangles;
  74716. }
  74717. Earcut.earcut = earcut;
  74718. var Node = /** @class */ (function () {
  74719. function Node(i, x, y) {
  74720. this.i = i;
  74721. this.x = x;
  74722. this.y = y;
  74723. this.prev = null;
  74724. this.next = null;
  74725. this.z = null;
  74726. this.prevZ = null;
  74727. this.nextZ = null;
  74728. this.steiner = false;
  74729. }
  74730. return Node;
  74731. }());
  74732. // create a circular doubly linked list from polygon points in the specified winding order
  74733. function linkedList(data, start, end, dim, clockwise) {
  74734. var i, last = null;
  74735. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  74736. for (i = start; i < end; i += dim)
  74737. last = insertNode(i, data[i], data[i + 1], last);
  74738. }
  74739. else {
  74740. for (i = end - dim; i >= start; i -= dim)
  74741. last = insertNode(i, data[i], data[i + 1], last);
  74742. }
  74743. if (last && equals(last, last.next)) {
  74744. removeNode(last);
  74745. last = last.next;
  74746. }
  74747. return last;
  74748. }
  74749. // eliminate colinear or duplicate points
  74750. function filterPoints(start, end) {
  74751. if (!start)
  74752. return start;
  74753. if (!end)
  74754. end = start;
  74755. var p = start, again;
  74756. do {
  74757. again = false;
  74758. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  74759. removeNode(p);
  74760. p = end = p.prev;
  74761. if (p === p.next)
  74762. return undefined;
  74763. again = true;
  74764. }
  74765. else {
  74766. p = p.next;
  74767. }
  74768. } while (again || p !== end);
  74769. return end;
  74770. }
  74771. // main ear slicing loop which triangulates a polygon (given as a linked list)
  74772. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  74773. if (!ear)
  74774. return;
  74775. // interlink polygon nodes in z-order
  74776. if (!pass && size)
  74777. indexCurve(ear, minX, minY, size);
  74778. var stop = ear, prev, next;
  74779. // iterate through ears, slicing them one by one
  74780. while (ear.prev !== ear.next) {
  74781. prev = ear.prev;
  74782. next = ear.next;
  74783. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  74784. // cut off the triangle
  74785. triangles.push(prev.i / dim);
  74786. triangles.push(ear.i / dim);
  74787. triangles.push(next.i / dim);
  74788. removeNode(ear);
  74789. // skipping the next vertice leads to less sliver triangles
  74790. ear = next.next;
  74791. stop = next.next;
  74792. continue;
  74793. }
  74794. ear = next;
  74795. // if we looped through the whole remaining polygon and can't find any more ears
  74796. if (ear === stop) {
  74797. // try filtering points and slicing again
  74798. if (!pass) {
  74799. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  74800. // if this didn't work, try curing all small self-intersections locally
  74801. }
  74802. else if (pass === 1) {
  74803. ear = cureLocalIntersections(ear, triangles, dim);
  74804. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  74805. // as a last resort, try splitting the remaining polygon into two
  74806. }
  74807. else if (pass === 2) {
  74808. splitEarcut(ear, triangles, dim, minX, minY, size);
  74809. }
  74810. break;
  74811. }
  74812. }
  74813. }
  74814. // check whether a polygon node forms a valid ear with adjacent nodes
  74815. function isEar(ear) {
  74816. var a = ear.prev, b = ear, c = ear.next;
  74817. if (area(a, b, c) >= 0)
  74818. return false; // reflex, can't be an ear
  74819. // now make sure we don't have other points inside the potential ear
  74820. var p = ear.next.next;
  74821. while (p !== ear.prev) {
  74822. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74823. area(p.prev, p, p.next) >= 0)
  74824. return false;
  74825. p = p.next;
  74826. }
  74827. return true;
  74828. }
  74829. function isEarHashed(ear, minX, minY, size) {
  74830. var a = ear.prev, b = ear, c = ear.next;
  74831. if (area(a, b, c) >= 0)
  74832. return false; // reflex, can't be an ear
  74833. // triangle bbox; min & max are calculated like this for speed
  74834. 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);
  74835. // z-order range for the current triangle bbox;
  74836. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  74837. // first look for points inside the triangle in increasing z-order
  74838. var p = ear.nextZ;
  74839. while (p && p.z <= maxZ) {
  74840. if (p !== ear.prev &&
  74841. p !== ear.next &&
  74842. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74843. area(p.prev, p, p.next) >= 0)
  74844. return false;
  74845. p = p.nextZ;
  74846. }
  74847. // then look for points in decreasing z-order
  74848. p = ear.prevZ;
  74849. while (p && p.z >= minZ) {
  74850. if (p !== ear.prev &&
  74851. p !== ear.next &&
  74852. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74853. area(p.prev, p, p.next) >= 0)
  74854. return false;
  74855. p = p.prevZ;
  74856. }
  74857. return true;
  74858. }
  74859. // go through all polygon nodes and cure small local self-intersections
  74860. function cureLocalIntersections(start, triangles, dim) {
  74861. var p = start;
  74862. do {
  74863. var a = p.prev, b = p.next.next;
  74864. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  74865. triangles.push(a.i / dim);
  74866. triangles.push(p.i / dim);
  74867. triangles.push(b.i / dim);
  74868. // remove two nodes involved
  74869. removeNode(p);
  74870. removeNode(p.next);
  74871. p = start = b;
  74872. }
  74873. p = p.next;
  74874. } while (p !== start);
  74875. return p;
  74876. }
  74877. // try splitting polygon into two and triangulate them independently
  74878. function splitEarcut(start, triangles, dim, minX, minY, size) {
  74879. // look for a valid diagonal that divides the polygon into two
  74880. var a = start;
  74881. do {
  74882. var b = a.next.next;
  74883. while (b !== a.prev) {
  74884. if (a.i !== b.i && isValidDiagonal(a, b)) {
  74885. // split the polygon in two by the diagonal
  74886. var c = splitPolygon(a, b);
  74887. // filter colinear points around the cuts
  74888. a = filterPoints(a, a.next);
  74889. c = filterPoints(c, c.next);
  74890. // run earcut on each half
  74891. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  74892. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  74893. return;
  74894. }
  74895. b = b.next;
  74896. }
  74897. a = a.next;
  74898. } while (a !== start);
  74899. }
  74900. // link every hole into the outer loop, producing a single-ring polygon without holes
  74901. function eliminateHoles(data, holeIndices, outerNode, dim) {
  74902. var queue = [], i, len, start, end, list;
  74903. for (i = 0, len = holeIndices.length; i < len; i++) {
  74904. start = holeIndices[i] * dim;
  74905. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  74906. list = linkedList(data, start, end, dim, false);
  74907. if (list === list.next)
  74908. list.steiner = true;
  74909. queue.push(getLeftmost(list));
  74910. }
  74911. queue.sort(compareX);
  74912. // process holes from left to right
  74913. for (i = 0; i < queue.length; i++) {
  74914. eliminateHole(queue[i], outerNode);
  74915. outerNode = filterPoints(outerNode, outerNode.next);
  74916. }
  74917. return outerNode;
  74918. }
  74919. function compareX(a, b) {
  74920. return a.x - b.x;
  74921. }
  74922. // find a bridge between vertices that connects hole with an outer ring and and link it
  74923. function eliminateHole(hole, outerNode) {
  74924. outerNode = findHoleBridge(hole, outerNode);
  74925. if (outerNode) {
  74926. var b = splitPolygon(outerNode, hole);
  74927. filterPoints(b, b.next);
  74928. }
  74929. }
  74930. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  74931. function findHoleBridge(hole, outerNode) {
  74932. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  74933. // find a segment intersected by a ray from the hole's leftmost point to the left;
  74934. // segment's endpoint with lesser x will be potential connection point
  74935. do {
  74936. if (hy <= p.y && hy >= p.next.y) {
  74937. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  74938. if (x <= hx && x > qx) {
  74939. qx = x;
  74940. if (x === hx) {
  74941. if (hy === p.y)
  74942. return p;
  74943. if (hy === p.next.y)
  74944. return p.next;
  74945. }
  74946. m = p.x < p.next.x ? p : p.next;
  74947. }
  74948. }
  74949. p = p.next;
  74950. } while (p !== outerNode);
  74951. if (!m)
  74952. return null;
  74953. if (hx === qx)
  74954. return m.prev; // hole touches outer segment; pick lower endpoint
  74955. // look for points inside the triangle of hole point, segment intersection and endpoint;
  74956. // if there are no points found, we have a valid connection;
  74957. // otherwise choose the point of the minimum angle with the ray as connection point
  74958. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  74959. p = m.next;
  74960. while (p !== stop) {
  74961. if (hx >= p.x &&
  74962. p.x >= mx &&
  74963. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  74964. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  74965. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  74966. m = p;
  74967. tanMin = tan;
  74968. }
  74969. }
  74970. p = p.next;
  74971. }
  74972. return m;
  74973. }
  74974. // interlink polygon nodes in z-order
  74975. function indexCurve(start, minX, minY, size) {
  74976. var p = start;
  74977. do {
  74978. if (p.z === null)
  74979. p.z = zOrder(p.x, p.y, minX, minY, size);
  74980. p.prevZ = p.prev;
  74981. p.nextZ = p.next;
  74982. p = p.next;
  74983. } while (p !== start);
  74984. p.prevZ.nextZ = null;
  74985. p.prevZ = null;
  74986. sortLinked(p);
  74987. }
  74988. // Simon Tatham's linked list merge sort algorithm
  74989. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  74990. function sortLinked(list) {
  74991. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  74992. do {
  74993. p = list;
  74994. list = null;
  74995. tail = null;
  74996. numMerges = 0;
  74997. while (p) {
  74998. numMerges++;
  74999. q = p;
  75000. pSize = 0;
  75001. for (i = 0; i < inSize; i++) {
  75002. pSize++;
  75003. q = q.nextZ;
  75004. if (!q)
  75005. break;
  75006. }
  75007. qSize = inSize;
  75008. while (pSize > 0 || (qSize > 0 && q)) {
  75009. if (pSize === 0) {
  75010. e = q;
  75011. q = q.nextZ;
  75012. qSize--;
  75013. }
  75014. else if (qSize === 0 || !q) {
  75015. e = p;
  75016. p = p.nextZ;
  75017. pSize--;
  75018. }
  75019. else if (p.z <= q.z) {
  75020. e = p;
  75021. p = p.nextZ;
  75022. pSize--;
  75023. }
  75024. else {
  75025. e = q;
  75026. q = q.nextZ;
  75027. qSize--;
  75028. }
  75029. if (tail)
  75030. tail.nextZ = e;
  75031. else
  75032. list = e;
  75033. e.prevZ = tail;
  75034. tail = e;
  75035. }
  75036. p = q;
  75037. }
  75038. tail.nextZ = null;
  75039. inSize *= 2;
  75040. } while (numMerges > 1);
  75041. return list;
  75042. }
  75043. // z-order of a point given coords and size of the data bounding box
  75044. function zOrder(x, y, minX, minY, size) {
  75045. // coords are transformed into non-negative 15-bit integer range
  75046. x = 32767 * (x - minX) / size;
  75047. y = 32767 * (y - minY) / size;
  75048. x = (x | (x << 8)) & 0x00FF00FF;
  75049. x = (x | (x << 4)) & 0x0F0F0F0F;
  75050. x = (x | (x << 2)) & 0x33333333;
  75051. x = (x | (x << 1)) & 0x55555555;
  75052. y = (y | (y << 8)) & 0x00FF00FF;
  75053. y = (y | (y << 4)) & 0x0F0F0F0F;
  75054. y = (y | (y << 2)) & 0x33333333;
  75055. y = (y | (y << 1)) & 0x55555555;
  75056. return x | (y << 1);
  75057. }
  75058. // find the leftmost node of a polygon ring
  75059. function getLeftmost(start) {
  75060. var p = start, leftmost = start;
  75061. do {
  75062. if (p.x < leftmost.x)
  75063. leftmost = p;
  75064. p = p.next;
  75065. } while (p !== start);
  75066. return leftmost;
  75067. }
  75068. // check if a point lies within a convex triangle
  75069. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  75070. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  75071. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  75072. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  75073. }
  75074. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  75075. function isValidDiagonal(a, b) {
  75076. return a.next.i !== b.i &&
  75077. a.prev.i !== b.i &&
  75078. !intersectsPolygon(a, b) &&
  75079. locallyInside(a, b) &&
  75080. locallyInside(b, a) &&
  75081. middleInside(a, b);
  75082. }
  75083. // signed area of a triangle
  75084. function area(p, q, r) {
  75085. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  75086. }
  75087. // check if two points are equal
  75088. function equals(p1, p2) {
  75089. return p1.x === p2.x && p1.y === p2.y;
  75090. }
  75091. // check if two segments intersect
  75092. function intersects(p1, q1, p2, q2) {
  75093. if ((equals(p1, q1) && equals(p2, q2)) ||
  75094. (equals(p1, q2) && equals(p2, q1)))
  75095. return true;
  75096. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  75097. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  75098. }
  75099. // check if a polygon diagonal intersects any polygon segments
  75100. function intersectsPolygon(a, b) {
  75101. var p = a;
  75102. do {
  75103. if (p.i !== a.i &&
  75104. p.next.i !== a.i &&
  75105. p.i !== b.i &&
  75106. p.next.i !== b.i &&
  75107. intersects(p, p.next, a, b))
  75108. return true;
  75109. p = p.next;
  75110. } while (p !== a);
  75111. return false;
  75112. }
  75113. // check if a polygon diagonal is locally inside the polygon
  75114. function locallyInside(a, b) {
  75115. return area(a.prev, a, a.next) < 0
  75116. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  75117. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  75118. }
  75119. // check if the middle point of a polygon diagonal is inside the polygon
  75120. function middleInside(a, b) {
  75121. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  75122. do {
  75123. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  75124. inside = !inside;
  75125. p = p.next;
  75126. } while (p !== a);
  75127. return inside;
  75128. }
  75129. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  75130. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  75131. function splitPolygon(a, b) {
  75132. 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;
  75133. a.next = b;
  75134. b.prev = a;
  75135. a2.next = an;
  75136. an.prev = a2;
  75137. b2.next = a2;
  75138. a2.prev = b2;
  75139. bp.next = b2;
  75140. b2.prev = bp;
  75141. return b2;
  75142. }
  75143. // create a node and optionally link it with previous one (in a circular doubly linked list)
  75144. function insertNode(i, x, y, last) {
  75145. var p = new Node(i, x, y);
  75146. if (!last) {
  75147. p.prev = p;
  75148. p.next = p;
  75149. }
  75150. else {
  75151. p.next = last.next;
  75152. p.prev = last;
  75153. last.next.prev = p;
  75154. last.next = p;
  75155. }
  75156. return p;
  75157. }
  75158. function removeNode(p) {
  75159. p.next.prev = p.prev;
  75160. p.prev.next = p.next;
  75161. if (p.prevZ)
  75162. p.prevZ.nextZ = p.nextZ;
  75163. if (p.nextZ)
  75164. p.nextZ.prevZ = p.prevZ;
  75165. }
  75166. /**
  75167. * return a percentage difference between the polygon area and its triangulation area;
  75168. * used to verify correctness of triangulation
  75169. */
  75170. function deviation(data, holeIndices, dim, triangles) {
  75171. var hasHoles = holeIndices && holeIndices.length;
  75172. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  75173. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  75174. if (hasHoles) {
  75175. for (var i = 0, len = holeIndices.length; i < len; i++) {
  75176. var start = holeIndices[i] * dim;
  75177. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  75178. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  75179. }
  75180. }
  75181. var trianglesArea = 0;
  75182. for (i = 0; i < triangles.length; i += 3) {
  75183. var a = triangles[i] * dim;
  75184. var b = triangles[i + 1] * dim;
  75185. var c = triangles[i + 2] * dim;
  75186. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  75187. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  75188. }
  75189. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  75190. }
  75191. Earcut.deviation = deviation;
  75192. ;
  75193. function signedArea(data, start, end, dim) {
  75194. var sum = 0;
  75195. for (var i = start, j = end - dim; i < end; i += dim) {
  75196. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  75197. j = i;
  75198. }
  75199. return sum;
  75200. }
  75201. /**
  75202. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  75203. */
  75204. function flatten(data) {
  75205. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  75206. for (var i = 0; i < data.length; i++) {
  75207. for (var j = 0; j < data[i].length; j++) {
  75208. for (var d = 0; d < dim; d++)
  75209. result.vertices.push(data[i][j][d]);
  75210. }
  75211. if (i > 0) {
  75212. holeIndex += data[i - 1].length;
  75213. result.holes.push(holeIndex);
  75214. }
  75215. }
  75216. return result;
  75217. }
  75218. Earcut.flatten = flatten;
  75219. ;
  75220. })(Earcut || (Earcut = {}));
  75221. //# sourceMappingURL=babylon.earcut.js.map
  75222. var BABYLON;
  75223. (function (BABYLON) {
  75224. var IndexedVector2 = /** @class */ (function (_super) {
  75225. __extends(IndexedVector2, _super);
  75226. function IndexedVector2(original, index) {
  75227. var _this = _super.call(this, original.x, original.y) || this;
  75228. _this.index = index;
  75229. return _this;
  75230. }
  75231. return IndexedVector2;
  75232. }(BABYLON.Vector2));
  75233. var PolygonPoints = /** @class */ (function () {
  75234. function PolygonPoints() {
  75235. this.elements = new Array();
  75236. }
  75237. PolygonPoints.prototype.add = function (originalPoints) {
  75238. var _this = this;
  75239. var result = new Array();
  75240. originalPoints.forEach(function (point) {
  75241. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  75242. var newPoint = new IndexedVector2(point, _this.elements.length);
  75243. result.push(newPoint);
  75244. _this.elements.push(newPoint);
  75245. }
  75246. });
  75247. return result;
  75248. };
  75249. PolygonPoints.prototype.computeBounds = function () {
  75250. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  75251. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  75252. this.elements.forEach(function (point) {
  75253. // x
  75254. if (point.x < lmin.x) {
  75255. lmin.x = point.x;
  75256. }
  75257. else if (point.x > lmax.x) {
  75258. lmax.x = point.x;
  75259. }
  75260. // y
  75261. if (point.y < lmin.y) {
  75262. lmin.y = point.y;
  75263. }
  75264. else if (point.y > lmax.y) {
  75265. lmax.y = point.y;
  75266. }
  75267. });
  75268. return {
  75269. min: lmin,
  75270. max: lmax,
  75271. width: lmax.x - lmin.x,
  75272. height: lmax.y - lmin.y
  75273. };
  75274. };
  75275. return PolygonPoints;
  75276. }());
  75277. var Polygon = /** @class */ (function () {
  75278. function Polygon() {
  75279. }
  75280. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  75281. return [
  75282. new BABYLON.Vector2(xmin, ymin),
  75283. new BABYLON.Vector2(xmax, ymin),
  75284. new BABYLON.Vector2(xmax, ymax),
  75285. new BABYLON.Vector2(xmin, ymax)
  75286. ];
  75287. };
  75288. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  75289. if (cx === void 0) { cx = 0; }
  75290. if (cy === void 0) { cy = 0; }
  75291. if (numberOfSides === void 0) { numberOfSides = 32; }
  75292. var result = new Array();
  75293. var angle = 0;
  75294. var increment = (Math.PI * 2) / numberOfSides;
  75295. for (var i = 0; i < numberOfSides; i++) {
  75296. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  75297. angle -= increment;
  75298. }
  75299. return result;
  75300. };
  75301. Polygon.Parse = function (input) {
  75302. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  75303. var i, result = [];
  75304. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  75305. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  75306. }
  75307. return result;
  75308. };
  75309. Polygon.StartingAt = function (x, y) {
  75310. return BABYLON.Path2.StartingAt(x, y);
  75311. };
  75312. return Polygon;
  75313. }());
  75314. BABYLON.Polygon = Polygon;
  75315. var PolygonMeshBuilder = /** @class */ (function () {
  75316. function PolygonMeshBuilder(name, contours, scene) {
  75317. this._points = new PolygonPoints();
  75318. this._outlinepoints = new PolygonPoints();
  75319. this._holes = new Array();
  75320. this._epoints = new Array();
  75321. this._eholes = new Array();
  75322. this._name = name;
  75323. this._scene = scene;
  75324. var points;
  75325. if (contours instanceof BABYLON.Path2) {
  75326. points = contours.getPoints();
  75327. }
  75328. else {
  75329. points = contours;
  75330. }
  75331. this._addToepoint(points);
  75332. this._points.add(points);
  75333. this._outlinepoints.add(points);
  75334. }
  75335. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  75336. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  75337. var p = points_1[_i];
  75338. this._epoints.push(p.x, p.y);
  75339. }
  75340. };
  75341. PolygonMeshBuilder.prototype.addHole = function (hole) {
  75342. this._points.add(hole);
  75343. var holepoints = new PolygonPoints();
  75344. holepoints.add(hole);
  75345. this._holes.push(holepoints);
  75346. this._eholes.push(this._epoints.length / 2);
  75347. this._addToepoint(hole);
  75348. return this;
  75349. };
  75350. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  75351. var _this = this;
  75352. if (updatable === void 0) { updatable = false; }
  75353. if (depth === void 0) { depth = 0; }
  75354. var result = new BABYLON.Mesh(this._name, this._scene);
  75355. var normals = new Array();
  75356. var positions = new Array();
  75357. var uvs = new Array();
  75358. var bounds = this._points.computeBounds();
  75359. this._points.elements.forEach(function (p) {
  75360. normals.push(0, 1.0, 0);
  75361. positions.push(p.x, 0, p.y);
  75362. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  75363. });
  75364. var indices = new Array();
  75365. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  75366. for (var i = 0; i < res.length; i++) {
  75367. indices.push(res[i]);
  75368. }
  75369. if (depth > 0) {
  75370. var positionscount = (positions.length / 3); //get the current pointcount
  75371. this._points.elements.forEach(function (p) {
  75372. normals.push(0, -1.0, 0);
  75373. positions.push(p.x, -depth, p.y);
  75374. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  75375. });
  75376. var totalCount = indices.length;
  75377. for (var i = 0; i < totalCount; i += 3) {
  75378. var i0 = indices[i + 0];
  75379. var i1 = indices[i + 1];
  75380. var i2 = indices[i + 2];
  75381. indices.push(i2 + positionscount);
  75382. indices.push(i1 + positionscount);
  75383. indices.push(i0 + positionscount);
  75384. }
  75385. //Add the sides
  75386. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  75387. this._holes.forEach(function (hole) {
  75388. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  75389. });
  75390. }
  75391. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  75392. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  75393. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  75394. result.setIndices(indices);
  75395. return result;
  75396. };
  75397. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  75398. var StartIndex = positions.length / 3;
  75399. var ulength = 0;
  75400. for (var i = 0; i < points.elements.length; i++) {
  75401. var p = points.elements[i];
  75402. var p1;
  75403. if ((i + 1) > points.elements.length - 1) {
  75404. p1 = points.elements[0];
  75405. }
  75406. else {
  75407. p1 = points.elements[i + 1];
  75408. }
  75409. positions.push(p.x, 0, p.y);
  75410. positions.push(p.x, -depth, p.y);
  75411. positions.push(p1.x, 0, p1.y);
  75412. positions.push(p1.x, -depth, p1.y);
  75413. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  75414. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  75415. var v3 = v2.subtract(v1);
  75416. var v4 = new BABYLON.Vector3(0, 1, 0);
  75417. var vn = BABYLON.Vector3.Cross(v3, v4);
  75418. vn = vn.normalize();
  75419. uvs.push(ulength / bounds.width, 0);
  75420. uvs.push(ulength / bounds.width, 1);
  75421. ulength += v3.length();
  75422. uvs.push((ulength / bounds.width), 0);
  75423. uvs.push((ulength / bounds.width), 1);
  75424. if (!flip) {
  75425. normals.push(-vn.x, -vn.y, -vn.z);
  75426. normals.push(-vn.x, -vn.y, -vn.z);
  75427. normals.push(-vn.x, -vn.y, -vn.z);
  75428. normals.push(-vn.x, -vn.y, -vn.z);
  75429. indices.push(StartIndex);
  75430. indices.push(StartIndex + 1);
  75431. indices.push(StartIndex + 2);
  75432. indices.push(StartIndex + 1);
  75433. indices.push(StartIndex + 3);
  75434. indices.push(StartIndex + 2);
  75435. }
  75436. else {
  75437. normals.push(vn.x, vn.y, vn.z);
  75438. normals.push(vn.x, vn.y, vn.z);
  75439. normals.push(vn.x, vn.y, vn.z);
  75440. normals.push(vn.x, vn.y, vn.z);
  75441. indices.push(StartIndex);
  75442. indices.push(StartIndex + 2);
  75443. indices.push(StartIndex + 1);
  75444. indices.push(StartIndex + 1);
  75445. indices.push(StartIndex + 2);
  75446. indices.push(StartIndex + 3);
  75447. }
  75448. StartIndex += 4;
  75449. }
  75450. ;
  75451. };
  75452. return PolygonMeshBuilder;
  75453. }());
  75454. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  75455. })(BABYLON || (BABYLON = {}));
  75456. //# sourceMappingURL=babylon.polygonMesh.js.map
  75457. var BABYLON;
  75458. (function (BABYLON) {
  75459. // Unique ID when we import meshes from Babylon to CSG
  75460. var currentCSGMeshId = 0;
  75461. // # class Vertex
  75462. // Represents a vertex of a polygon. Use your own vertex class instead of this
  75463. // one to provide additional features like texture coordinates and vertex
  75464. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  75465. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  75466. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  75467. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  75468. // is not used anywhere else.
  75469. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  75470. var Vertex = /** @class */ (function () {
  75471. function Vertex(pos, normal, uv) {
  75472. this.pos = pos;
  75473. this.normal = normal;
  75474. this.uv = uv;
  75475. }
  75476. Vertex.prototype.clone = function () {
  75477. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  75478. };
  75479. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  75480. // orientation of a polygon is flipped.
  75481. Vertex.prototype.flip = function () {
  75482. this.normal = this.normal.scale(-1);
  75483. };
  75484. // Create a new vertex between this vertex and `other` by linearly
  75485. // interpolating all properties using a parameter of `t`. Subclasses should
  75486. // override this to interpolate additional properties.
  75487. Vertex.prototype.interpolate = function (other, t) {
  75488. 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));
  75489. };
  75490. return Vertex;
  75491. }());
  75492. // # class Plane
  75493. // Represents a plane in 3D space.
  75494. var Plane = /** @class */ (function () {
  75495. function Plane(normal, w) {
  75496. this.normal = normal;
  75497. this.w = w;
  75498. }
  75499. Plane.FromPoints = function (a, b, c) {
  75500. var v0 = c.subtract(a);
  75501. var v1 = b.subtract(a);
  75502. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  75503. return null;
  75504. }
  75505. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  75506. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  75507. };
  75508. Plane.prototype.clone = function () {
  75509. return new Plane(this.normal.clone(), this.w);
  75510. };
  75511. Plane.prototype.flip = function () {
  75512. this.normal.scaleInPlace(-1);
  75513. this.w = -this.w;
  75514. };
  75515. // Split `polygon` by this plane if needed, then put the polygon or polygon
  75516. // fragments in the appropriate lists. Coplanar polygons go into either
  75517. // `coplanarFront` or `coplanarBack` depending on their orientation with
  75518. // respect to this plane. Polygons in front or in back of this plane go into
  75519. // either `front` or `back`.
  75520. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  75521. var COPLANAR = 0;
  75522. var FRONT = 1;
  75523. var BACK = 2;
  75524. var SPANNING = 3;
  75525. // Classify each point as well as the entire polygon into one of the above
  75526. // four classes.
  75527. var polygonType = 0;
  75528. var types = [];
  75529. var i;
  75530. var t;
  75531. for (i = 0; i < polygon.vertices.length; i++) {
  75532. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  75533. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  75534. polygonType |= type;
  75535. types.push(type);
  75536. }
  75537. // Put the polygon in the correct list, splitting it when necessary.
  75538. switch (polygonType) {
  75539. case COPLANAR:
  75540. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  75541. break;
  75542. case FRONT:
  75543. front.push(polygon);
  75544. break;
  75545. case BACK:
  75546. back.push(polygon);
  75547. break;
  75548. case SPANNING:
  75549. var f = [], b = [];
  75550. for (i = 0; i < polygon.vertices.length; i++) {
  75551. var j = (i + 1) % polygon.vertices.length;
  75552. var ti = types[i], tj = types[j];
  75553. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  75554. if (ti !== BACK)
  75555. f.push(vi);
  75556. if (ti !== FRONT)
  75557. b.push(ti !== BACK ? vi.clone() : vi);
  75558. if ((ti | tj) === SPANNING) {
  75559. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  75560. var v = vi.interpolate(vj, t);
  75561. f.push(v);
  75562. b.push(v.clone());
  75563. }
  75564. }
  75565. var poly;
  75566. if (f.length >= 3) {
  75567. poly = new Polygon(f, polygon.shared);
  75568. if (poly.plane)
  75569. front.push(poly);
  75570. }
  75571. if (b.length >= 3) {
  75572. poly = new Polygon(b, polygon.shared);
  75573. if (poly.plane)
  75574. back.push(poly);
  75575. }
  75576. break;
  75577. }
  75578. };
  75579. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  75580. // point is on the plane.
  75581. Plane.EPSILON = 1e-5;
  75582. return Plane;
  75583. }());
  75584. // # class Polygon
  75585. // Represents a convex polygon. The vertices used to initialize a polygon must
  75586. // be coplanar and form a convex loop.
  75587. //
  75588. // Each convex polygon has a `shared` property, which is shared between all
  75589. // polygons that are clones of each other or were split from the same polygon.
  75590. // This can be used to define per-polygon properties (such as surface color).
  75591. var Polygon = /** @class */ (function () {
  75592. function Polygon(vertices, shared) {
  75593. this.vertices = vertices;
  75594. this.shared = shared;
  75595. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  75596. }
  75597. Polygon.prototype.clone = function () {
  75598. var vertices = this.vertices.map(function (v) { return v.clone(); });
  75599. return new Polygon(vertices, this.shared);
  75600. };
  75601. Polygon.prototype.flip = function () {
  75602. this.vertices.reverse().map(function (v) { v.flip(); });
  75603. this.plane.flip();
  75604. };
  75605. return Polygon;
  75606. }());
  75607. // # class Node
  75608. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  75609. // by picking a polygon to split along. That polygon (and all other coplanar
  75610. // polygons) are added directly to that node and the other polygons are added to
  75611. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  75612. // no distinction between internal and leaf nodes.
  75613. var Node = /** @class */ (function () {
  75614. function Node(polygons) {
  75615. this.plane = null;
  75616. this.front = null;
  75617. this.back = null;
  75618. this.polygons = new Array();
  75619. if (polygons) {
  75620. this.build(polygons);
  75621. }
  75622. }
  75623. Node.prototype.clone = function () {
  75624. var node = new Node();
  75625. node.plane = this.plane && this.plane.clone();
  75626. node.front = this.front && this.front.clone();
  75627. node.back = this.back && this.back.clone();
  75628. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  75629. return node;
  75630. };
  75631. // Convert solid space to empty space and empty space to solid space.
  75632. Node.prototype.invert = function () {
  75633. for (var i = 0; i < this.polygons.length; i++) {
  75634. this.polygons[i].flip();
  75635. }
  75636. if (this.plane) {
  75637. this.plane.flip();
  75638. }
  75639. if (this.front) {
  75640. this.front.invert();
  75641. }
  75642. if (this.back) {
  75643. this.back.invert();
  75644. }
  75645. var temp = this.front;
  75646. this.front = this.back;
  75647. this.back = temp;
  75648. };
  75649. // Recursively remove all polygons in `polygons` that are inside this BSP
  75650. // tree.
  75651. Node.prototype.clipPolygons = function (polygons) {
  75652. if (!this.plane)
  75653. return polygons.slice();
  75654. var front = new Array(), back = new Array();
  75655. for (var i = 0; i < polygons.length; i++) {
  75656. this.plane.splitPolygon(polygons[i], front, back, front, back);
  75657. }
  75658. if (this.front) {
  75659. front = this.front.clipPolygons(front);
  75660. }
  75661. if (this.back) {
  75662. back = this.back.clipPolygons(back);
  75663. }
  75664. else {
  75665. back = [];
  75666. }
  75667. return front.concat(back);
  75668. };
  75669. // Remove all polygons in this BSP tree that are inside the other BSP tree
  75670. // `bsp`.
  75671. Node.prototype.clipTo = function (bsp) {
  75672. this.polygons = bsp.clipPolygons(this.polygons);
  75673. if (this.front)
  75674. this.front.clipTo(bsp);
  75675. if (this.back)
  75676. this.back.clipTo(bsp);
  75677. };
  75678. // Return a list of all polygons in this BSP tree.
  75679. Node.prototype.allPolygons = function () {
  75680. var polygons = this.polygons.slice();
  75681. if (this.front)
  75682. polygons = polygons.concat(this.front.allPolygons());
  75683. if (this.back)
  75684. polygons = polygons.concat(this.back.allPolygons());
  75685. return polygons;
  75686. };
  75687. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  75688. // new polygons are filtered down to the bottom of the tree and become new
  75689. // nodes there. Each set of polygons is partitioned using the first polygon
  75690. // (no heuristic is used to pick a good split).
  75691. Node.prototype.build = function (polygons) {
  75692. if (!polygons.length)
  75693. return;
  75694. if (!this.plane)
  75695. this.plane = polygons[0].plane.clone();
  75696. var front = new Array(), back = new Array();
  75697. for (var i = 0; i < polygons.length; i++) {
  75698. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  75699. }
  75700. if (front.length) {
  75701. if (!this.front)
  75702. this.front = new Node();
  75703. this.front.build(front);
  75704. }
  75705. if (back.length) {
  75706. if (!this.back)
  75707. this.back = new Node();
  75708. this.back.build(back);
  75709. }
  75710. };
  75711. return Node;
  75712. }());
  75713. var CSG = /** @class */ (function () {
  75714. function CSG() {
  75715. this.polygons = new Array();
  75716. }
  75717. // Convert BABYLON.Mesh to BABYLON.CSG
  75718. CSG.FromMesh = function (mesh) {
  75719. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  75720. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  75721. if (mesh instanceof BABYLON.Mesh) {
  75722. mesh.computeWorldMatrix(true);
  75723. matrix = mesh.getWorldMatrix();
  75724. meshPosition = mesh.position.clone();
  75725. meshRotation = mesh.rotation.clone();
  75726. if (mesh.rotationQuaternion) {
  75727. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  75728. }
  75729. meshScaling = mesh.scaling.clone();
  75730. }
  75731. else {
  75732. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  75733. }
  75734. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  75735. var subMeshes = mesh.subMeshes;
  75736. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  75737. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  75738. vertices = [];
  75739. for (var j = 0; j < 3; j++) {
  75740. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  75741. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  75742. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  75743. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  75744. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  75745. vertex = new Vertex(position, normal, uv);
  75746. vertices.push(vertex);
  75747. }
  75748. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  75749. // To handle the case of degenerated triangle
  75750. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  75751. if (polygon.plane)
  75752. polygons.push(polygon);
  75753. }
  75754. }
  75755. var csg = CSG.FromPolygons(polygons);
  75756. csg.matrix = matrix;
  75757. csg.position = meshPosition;
  75758. csg.rotation = meshRotation;
  75759. csg.scaling = meshScaling;
  75760. csg.rotationQuaternion = meshRotationQuaternion;
  75761. currentCSGMeshId++;
  75762. return csg;
  75763. };
  75764. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  75765. CSG.FromPolygons = function (polygons) {
  75766. var csg = new CSG();
  75767. csg.polygons = polygons;
  75768. return csg;
  75769. };
  75770. CSG.prototype.clone = function () {
  75771. var csg = new CSG();
  75772. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  75773. csg.copyTransformAttributes(this);
  75774. return csg;
  75775. };
  75776. CSG.prototype.union = function (csg) {
  75777. var a = new Node(this.clone().polygons);
  75778. var b = new Node(csg.clone().polygons);
  75779. a.clipTo(b);
  75780. b.clipTo(a);
  75781. b.invert();
  75782. b.clipTo(a);
  75783. b.invert();
  75784. a.build(b.allPolygons());
  75785. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75786. };
  75787. CSG.prototype.unionInPlace = function (csg) {
  75788. var a = new Node(this.polygons);
  75789. var b = new Node(csg.polygons);
  75790. a.clipTo(b);
  75791. b.clipTo(a);
  75792. b.invert();
  75793. b.clipTo(a);
  75794. b.invert();
  75795. a.build(b.allPolygons());
  75796. this.polygons = a.allPolygons();
  75797. };
  75798. CSG.prototype.subtract = function (csg) {
  75799. var a = new Node(this.clone().polygons);
  75800. var b = new Node(csg.clone().polygons);
  75801. a.invert();
  75802. a.clipTo(b);
  75803. b.clipTo(a);
  75804. b.invert();
  75805. b.clipTo(a);
  75806. b.invert();
  75807. a.build(b.allPolygons());
  75808. a.invert();
  75809. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75810. };
  75811. CSG.prototype.subtractInPlace = function (csg) {
  75812. var a = new Node(this.polygons);
  75813. var b = new Node(csg.polygons);
  75814. a.invert();
  75815. a.clipTo(b);
  75816. b.clipTo(a);
  75817. b.invert();
  75818. b.clipTo(a);
  75819. b.invert();
  75820. a.build(b.allPolygons());
  75821. a.invert();
  75822. this.polygons = a.allPolygons();
  75823. };
  75824. CSG.prototype.intersect = function (csg) {
  75825. var a = new Node(this.clone().polygons);
  75826. var b = new Node(csg.clone().polygons);
  75827. a.invert();
  75828. b.clipTo(a);
  75829. b.invert();
  75830. a.clipTo(b);
  75831. b.clipTo(a);
  75832. a.build(b.allPolygons());
  75833. a.invert();
  75834. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75835. };
  75836. CSG.prototype.intersectInPlace = function (csg) {
  75837. var a = new Node(this.polygons);
  75838. var b = new Node(csg.polygons);
  75839. a.invert();
  75840. b.clipTo(a);
  75841. b.invert();
  75842. a.clipTo(b);
  75843. b.clipTo(a);
  75844. a.build(b.allPolygons());
  75845. a.invert();
  75846. this.polygons = a.allPolygons();
  75847. };
  75848. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  75849. // not modified.
  75850. CSG.prototype.inverse = function () {
  75851. var csg = this.clone();
  75852. csg.inverseInPlace();
  75853. return csg;
  75854. };
  75855. CSG.prototype.inverseInPlace = function () {
  75856. this.polygons.map(function (p) { p.flip(); });
  75857. };
  75858. // This is used to keep meshes transformations so they can be restored
  75859. // when we build back a Babylon Mesh
  75860. // NB : All CSG operations are performed in world coordinates
  75861. CSG.prototype.copyTransformAttributes = function (csg) {
  75862. this.matrix = csg.matrix;
  75863. this.position = csg.position;
  75864. this.rotation = csg.rotation;
  75865. this.scaling = csg.scaling;
  75866. this.rotationQuaternion = csg.rotationQuaternion;
  75867. return this;
  75868. };
  75869. // Build Raw mesh from CSG
  75870. // Coordinates here are in world space
  75871. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  75872. var matrix = this.matrix.clone();
  75873. matrix.invert();
  75874. 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;
  75875. if (keepSubMeshes) {
  75876. // Sort Polygons, since subMeshes are indices range
  75877. polygons.sort(function (a, b) {
  75878. if (a.shared.meshId === b.shared.meshId) {
  75879. return a.shared.subMeshId - b.shared.subMeshId;
  75880. }
  75881. else {
  75882. return a.shared.meshId - b.shared.meshId;
  75883. }
  75884. });
  75885. }
  75886. for (var i = 0, il = polygons.length; i < il; i++) {
  75887. polygon = polygons[i];
  75888. // Building SubMeshes
  75889. if (!subMesh_dict[polygon.shared.meshId]) {
  75890. subMesh_dict[polygon.shared.meshId] = {};
  75891. }
  75892. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  75893. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  75894. indexStart: +Infinity,
  75895. indexEnd: -Infinity,
  75896. materialIndex: polygon.shared.materialIndex
  75897. };
  75898. }
  75899. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  75900. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  75901. polygonIndices[0] = 0;
  75902. polygonIndices[1] = j - 1;
  75903. polygonIndices[2] = j;
  75904. for (var k = 0; k < 3; k++) {
  75905. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  75906. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  75907. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  75908. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  75909. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  75910. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  75911. // Check if 2 points can be merged
  75912. if (!(typeof vertex_idx !== 'undefined' &&
  75913. normals[vertex_idx * 3] === localNormal.x &&
  75914. normals[vertex_idx * 3 + 1] === localNormal.y &&
  75915. normals[vertex_idx * 3 + 2] === localNormal.z &&
  75916. uvs[vertex_idx * 2] === uv.x &&
  75917. uvs[vertex_idx * 2 + 1] === uv.y)) {
  75918. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  75919. uvs.push(uv.x, uv.y);
  75920. normals.push(normal.x, normal.y, normal.z);
  75921. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  75922. }
  75923. indices.push(vertex_idx);
  75924. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  75925. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  75926. currentIndex++;
  75927. }
  75928. }
  75929. }
  75930. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  75931. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  75932. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  75933. mesh.setIndices(indices, null);
  75934. if (keepSubMeshes) {
  75935. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  75936. var materialIndexOffset = 0, materialMaxIndex;
  75937. mesh.subMeshes = new Array();
  75938. for (var m in subMesh_dict) {
  75939. materialMaxIndex = -1;
  75940. for (var sm in subMesh_dict[m]) {
  75941. subMesh_obj = subMesh_dict[m][sm];
  75942. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  75943. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  75944. }
  75945. materialIndexOffset += ++materialMaxIndex;
  75946. }
  75947. }
  75948. return mesh;
  75949. };
  75950. // Build Mesh from CSG taking material and transforms into account
  75951. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  75952. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  75953. mesh.material = material;
  75954. mesh.position.copyFrom(this.position);
  75955. mesh.rotation.copyFrom(this.rotation);
  75956. if (this.rotationQuaternion) {
  75957. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  75958. }
  75959. mesh.scaling.copyFrom(this.scaling);
  75960. mesh.computeWorldMatrix(true);
  75961. return mesh;
  75962. };
  75963. return CSG;
  75964. }());
  75965. BABYLON.CSG = CSG;
  75966. })(BABYLON || (BABYLON = {}));
  75967. //# sourceMappingURL=babylon.csg.js.map
  75968. var BABYLON;
  75969. (function (BABYLON) {
  75970. var LensFlare = /** @class */ (function () {
  75971. function LensFlare(size, position, color, imgUrl, system) {
  75972. this.size = size;
  75973. this.position = position;
  75974. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  75975. this.color = color || new BABYLON.Color3(1, 1, 1);
  75976. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  75977. this._system = system;
  75978. system.lensFlares.push(this);
  75979. }
  75980. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  75981. return new LensFlare(size, position, color, imgUrl, system);
  75982. };
  75983. LensFlare.prototype.dispose = function () {
  75984. if (this.texture) {
  75985. this.texture.dispose();
  75986. }
  75987. // Remove from scene
  75988. var index = this._system.lensFlares.indexOf(this);
  75989. this._system.lensFlares.splice(index, 1);
  75990. };
  75991. ;
  75992. return LensFlare;
  75993. }());
  75994. BABYLON.LensFlare = LensFlare;
  75995. })(BABYLON || (BABYLON = {}));
  75996. //# sourceMappingURL=babylon.lensFlare.js.map
  75997. var BABYLON;
  75998. (function (BABYLON) {
  75999. var LensFlareSystem = /** @class */ (function () {
  76000. function LensFlareSystem(name, emitter, scene) {
  76001. this.name = name;
  76002. this.lensFlares = new Array();
  76003. this.borderLimit = 300;
  76004. this.viewportBorder = 0;
  76005. this.layerMask = 0x0FFFFFFF;
  76006. this._vertexBuffers = {};
  76007. this._isEnabled = true;
  76008. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76009. this._emitter = emitter;
  76010. this.id = name;
  76011. scene.lensFlareSystems.push(this);
  76012. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  76013. var engine = scene.getEngine();
  76014. // VBO
  76015. var vertices = [];
  76016. vertices.push(1, 1);
  76017. vertices.push(-1, 1);
  76018. vertices.push(-1, -1);
  76019. vertices.push(1, -1);
  76020. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76021. // Indices
  76022. var indices = [];
  76023. indices.push(0);
  76024. indices.push(1);
  76025. indices.push(2);
  76026. indices.push(0);
  76027. indices.push(2);
  76028. indices.push(3);
  76029. this._indexBuffer = engine.createIndexBuffer(indices);
  76030. // Effects
  76031. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  76032. }
  76033. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  76034. get: function () {
  76035. return this._isEnabled;
  76036. },
  76037. set: function (value) {
  76038. this._isEnabled = value;
  76039. },
  76040. enumerable: true,
  76041. configurable: true
  76042. });
  76043. LensFlareSystem.prototype.getScene = function () {
  76044. return this._scene;
  76045. };
  76046. LensFlareSystem.prototype.getEmitter = function () {
  76047. return this._emitter;
  76048. };
  76049. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  76050. this._emitter = newEmitter;
  76051. };
  76052. LensFlareSystem.prototype.getEmitterPosition = function () {
  76053. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  76054. };
  76055. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  76056. var position = this.getEmitterPosition();
  76057. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  76058. this._positionX = position.x;
  76059. this._positionY = position.y;
  76060. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  76061. if (this.viewportBorder > 0) {
  76062. globalViewport.x -= this.viewportBorder;
  76063. globalViewport.y -= this.viewportBorder;
  76064. globalViewport.width += this.viewportBorder * 2;
  76065. globalViewport.height += this.viewportBorder * 2;
  76066. position.x += this.viewportBorder;
  76067. position.y += this.viewportBorder;
  76068. this._positionX += this.viewportBorder;
  76069. this._positionY += this.viewportBorder;
  76070. }
  76071. if (position.z > 0) {
  76072. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  76073. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  76074. return true;
  76075. }
  76076. return true;
  76077. }
  76078. return false;
  76079. };
  76080. LensFlareSystem.prototype._isVisible = function () {
  76081. if (!this._isEnabled || !this._scene.activeCamera) {
  76082. return false;
  76083. }
  76084. var emitterPosition = this.getEmitterPosition();
  76085. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  76086. var distance = direction.length();
  76087. direction.normalize();
  76088. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  76089. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  76090. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  76091. };
  76092. LensFlareSystem.prototype.render = function () {
  76093. if (!this._effect.isReady() || !this._scene.activeCamera)
  76094. return false;
  76095. var engine = this._scene.getEngine();
  76096. var viewport = this._scene.activeCamera.viewport;
  76097. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  76098. // Position
  76099. if (!this.computeEffectivePosition(globalViewport)) {
  76100. return false;
  76101. }
  76102. // Visibility
  76103. if (!this._isVisible()) {
  76104. return false;
  76105. }
  76106. // Intensity
  76107. var awayX;
  76108. var awayY;
  76109. if (this._positionX < this.borderLimit + globalViewport.x) {
  76110. awayX = this.borderLimit + globalViewport.x - this._positionX;
  76111. }
  76112. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  76113. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  76114. }
  76115. else {
  76116. awayX = 0;
  76117. }
  76118. if (this._positionY < this.borderLimit + globalViewport.y) {
  76119. awayY = this.borderLimit + globalViewport.y - this._positionY;
  76120. }
  76121. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  76122. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  76123. }
  76124. else {
  76125. awayY = 0;
  76126. }
  76127. var away = (awayX > awayY) ? awayX : awayY;
  76128. away -= this.viewportBorder;
  76129. if (away > this.borderLimit) {
  76130. away = this.borderLimit;
  76131. }
  76132. var intensity = 1.0 - (away / this.borderLimit);
  76133. if (intensity < 0) {
  76134. return false;
  76135. }
  76136. if (intensity > 1.0) {
  76137. intensity = 1.0;
  76138. }
  76139. if (this.viewportBorder > 0) {
  76140. globalViewport.x += this.viewportBorder;
  76141. globalViewport.y += this.viewportBorder;
  76142. globalViewport.width -= this.viewportBorder * 2;
  76143. globalViewport.height -= this.viewportBorder * 2;
  76144. this._positionX -= this.viewportBorder;
  76145. this._positionY -= this.viewportBorder;
  76146. }
  76147. // Position
  76148. var centerX = globalViewport.x + globalViewport.width / 2;
  76149. var centerY = globalViewport.y + globalViewport.height / 2;
  76150. var distX = centerX - this._positionX;
  76151. var distY = centerY - this._positionY;
  76152. // Effects
  76153. engine.enableEffect(this._effect);
  76154. engine.setState(false);
  76155. engine.setDepthBuffer(false);
  76156. // VBOs
  76157. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76158. // Flares
  76159. for (var index = 0; index < this.lensFlares.length; index++) {
  76160. var flare = this.lensFlares[index];
  76161. engine.setAlphaMode(flare.alphaMode);
  76162. var x = centerX - (distX * flare.position);
  76163. var y = centerY - (distY * flare.position);
  76164. var cw = flare.size;
  76165. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  76166. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  76167. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  76168. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  76169. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  76170. // Texture
  76171. this._effect.setTexture("textureSampler", flare.texture);
  76172. // Color
  76173. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  76174. // Draw order
  76175. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76176. }
  76177. engine.setDepthBuffer(true);
  76178. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76179. return true;
  76180. };
  76181. LensFlareSystem.prototype.dispose = function () {
  76182. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76183. if (vertexBuffer) {
  76184. vertexBuffer.dispose();
  76185. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76186. }
  76187. if (this._indexBuffer) {
  76188. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76189. this._indexBuffer = null;
  76190. }
  76191. while (this.lensFlares.length) {
  76192. this.lensFlares[0].dispose();
  76193. }
  76194. // Remove from scene
  76195. var index = this._scene.lensFlareSystems.indexOf(this);
  76196. this._scene.lensFlareSystems.splice(index, 1);
  76197. };
  76198. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  76199. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  76200. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  76201. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  76202. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  76203. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  76204. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  76205. var parsedFlare = parsedLensFlareSystem.flares[index];
  76206. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  76207. }
  76208. return lensFlareSystem;
  76209. };
  76210. LensFlareSystem.prototype.serialize = function () {
  76211. var serializationObject = {};
  76212. serializationObject.id = this.id;
  76213. serializationObject.name = this.name;
  76214. serializationObject.emitterId = this.getEmitter().id;
  76215. serializationObject.borderLimit = this.borderLimit;
  76216. serializationObject.flares = [];
  76217. for (var index = 0; index < this.lensFlares.length; index++) {
  76218. var flare = this.lensFlares[index];
  76219. serializationObject.flares.push({
  76220. size: flare.size,
  76221. position: flare.position,
  76222. color: flare.color.asArray(),
  76223. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  76224. });
  76225. }
  76226. return serializationObject;
  76227. };
  76228. return LensFlareSystem;
  76229. }());
  76230. BABYLON.LensFlareSystem = LensFlareSystem;
  76231. })(BABYLON || (BABYLON = {}));
  76232. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  76233. var BABYLON;
  76234. (function (BABYLON) {
  76235. /**
  76236. * This is a holder class for the physics joint created by the physics plugin.
  76237. * It holds a set of functions to control the underlying joint.
  76238. */
  76239. var PhysicsJoint = /** @class */ (function () {
  76240. function PhysicsJoint(type, jointData) {
  76241. this.type = type;
  76242. this.jointData = jointData;
  76243. jointData.nativeParams = jointData.nativeParams || {};
  76244. }
  76245. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  76246. get: function () {
  76247. return this._physicsJoint;
  76248. },
  76249. set: function (newJoint) {
  76250. if (this._physicsJoint) {
  76251. //remove from the wolrd
  76252. }
  76253. this._physicsJoint = newJoint;
  76254. },
  76255. enumerable: true,
  76256. configurable: true
  76257. });
  76258. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  76259. set: function (physicsPlugin) {
  76260. this._physicsPlugin = physicsPlugin;
  76261. },
  76262. enumerable: true,
  76263. configurable: true
  76264. });
  76265. /**
  76266. * Execute a function that is physics-plugin specific.
  76267. * @param {Function} func the function that will be executed.
  76268. * It accepts two parameters: the physics world and the physics joint.
  76269. */
  76270. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  76271. func(this._physicsPlugin.world, this._physicsJoint);
  76272. };
  76273. //TODO check if the native joints are the same
  76274. //Joint Types
  76275. PhysicsJoint.DistanceJoint = 0;
  76276. PhysicsJoint.HingeJoint = 1;
  76277. PhysicsJoint.BallAndSocketJoint = 2;
  76278. PhysicsJoint.WheelJoint = 3;
  76279. PhysicsJoint.SliderJoint = 4;
  76280. //OIMO
  76281. PhysicsJoint.PrismaticJoint = 5;
  76282. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  76283. PhysicsJoint.UniversalJoint = 6;
  76284. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  76285. //Cannon
  76286. //Similar to a Ball-Joint. Different in params
  76287. PhysicsJoint.PointToPointJoint = 8;
  76288. //Cannon only at the moment
  76289. PhysicsJoint.SpringJoint = 9;
  76290. PhysicsJoint.LockJoint = 10;
  76291. return PhysicsJoint;
  76292. }());
  76293. BABYLON.PhysicsJoint = PhysicsJoint;
  76294. /**
  76295. * A class representing a physics distance joint.
  76296. */
  76297. var DistanceJoint = /** @class */ (function (_super) {
  76298. __extends(DistanceJoint, _super);
  76299. function DistanceJoint(jointData) {
  76300. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  76301. }
  76302. /**
  76303. * Update the predefined distance.
  76304. */
  76305. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  76306. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  76307. };
  76308. return DistanceJoint;
  76309. }(PhysicsJoint));
  76310. BABYLON.DistanceJoint = DistanceJoint;
  76311. var MotorEnabledJoint = /** @class */ (function (_super) {
  76312. __extends(MotorEnabledJoint, _super);
  76313. function MotorEnabledJoint(type, jointData) {
  76314. return _super.call(this, type, jointData) || this;
  76315. }
  76316. /**
  76317. * Set the motor values.
  76318. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76319. * @param {number} force the force to apply
  76320. * @param {number} maxForce max force for this motor.
  76321. */
  76322. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  76323. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76324. };
  76325. /**
  76326. * Set the motor's limits.
  76327. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76328. */
  76329. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76330. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76331. };
  76332. return MotorEnabledJoint;
  76333. }(PhysicsJoint));
  76334. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  76335. /**
  76336. * This class represents a single hinge physics joint
  76337. */
  76338. var HingeJoint = /** @class */ (function (_super) {
  76339. __extends(HingeJoint, _super);
  76340. function HingeJoint(jointData) {
  76341. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  76342. }
  76343. /**
  76344. * Set the motor values.
  76345. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76346. * @param {number} force the force to apply
  76347. * @param {number} maxForce max force for this motor.
  76348. */
  76349. HingeJoint.prototype.setMotor = function (force, maxForce) {
  76350. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76351. };
  76352. /**
  76353. * Set the motor's limits.
  76354. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76355. */
  76356. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76357. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76358. };
  76359. return HingeJoint;
  76360. }(MotorEnabledJoint));
  76361. BABYLON.HingeJoint = HingeJoint;
  76362. /**
  76363. * This class represents a dual hinge physics joint (same as wheel joint)
  76364. */
  76365. var Hinge2Joint = /** @class */ (function (_super) {
  76366. __extends(Hinge2Joint, _super);
  76367. function Hinge2Joint(jointData) {
  76368. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  76369. }
  76370. /**
  76371. * Set the motor values.
  76372. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76373. * @param {number} force the force to apply
  76374. * @param {number} maxForce max force for this motor.
  76375. * @param {motorIndex} the motor's index, 0 or 1.
  76376. */
  76377. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  76378. if (motorIndex === void 0) { motorIndex = 0; }
  76379. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  76380. };
  76381. /**
  76382. * Set the motor limits.
  76383. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76384. * @param {number} upperLimit the upper limit
  76385. * @param {number} lowerLimit lower limit
  76386. * @param {motorIndex} the motor's index, 0 or 1.
  76387. */
  76388. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  76389. if (motorIndex === void 0) { motorIndex = 0; }
  76390. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  76391. };
  76392. return Hinge2Joint;
  76393. }(MotorEnabledJoint));
  76394. BABYLON.Hinge2Joint = Hinge2Joint;
  76395. })(BABYLON || (BABYLON = {}));
  76396. //# sourceMappingURL=babylon.physicsJoint.js.map
  76397. var BABYLON;
  76398. (function (BABYLON) {
  76399. var PhysicsImpostor = /** @class */ (function () {
  76400. function PhysicsImpostor(object, type, _options, _scene) {
  76401. if (_options === void 0) { _options = { mass: 0 }; }
  76402. var _this = this;
  76403. this.object = object;
  76404. this.type = type;
  76405. this._options = _options;
  76406. this._scene = _scene;
  76407. this._bodyUpdateRequired = false;
  76408. this._onBeforePhysicsStepCallbacks = new Array();
  76409. this._onAfterPhysicsStepCallbacks = new Array();
  76410. this._onPhysicsCollideCallbacks = [];
  76411. this._deltaPosition = BABYLON.Vector3.Zero();
  76412. this._isDisposed = false;
  76413. //temp variables for parent rotation calculations
  76414. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  76415. this._tmpQuat = new BABYLON.Quaternion();
  76416. this._tmpQuat2 = new BABYLON.Quaternion();
  76417. /**
  76418. * this function is executed by the physics engine.
  76419. */
  76420. this.beforeStep = function () {
  76421. if (!_this._physicsEngine) {
  76422. return;
  76423. }
  76424. _this.object.translate(_this._deltaPosition, -1);
  76425. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  76426. _this.object.computeWorldMatrix(false);
  76427. if (_this.object.parent && _this.object.rotationQuaternion) {
  76428. _this.getParentsRotation();
  76429. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  76430. }
  76431. else {
  76432. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  76433. }
  76434. if (!_this._options.disableBidirectionalTransformation) {
  76435. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  76436. }
  76437. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  76438. func(_this);
  76439. });
  76440. };
  76441. /**
  76442. * this function is executed by the physics engine.
  76443. */
  76444. this.afterStep = function () {
  76445. if (!_this._physicsEngine) {
  76446. return;
  76447. }
  76448. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  76449. func(_this);
  76450. });
  76451. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  76452. // object has now its world rotation. needs to be converted to local.
  76453. if (_this.object.parent && _this.object.rotationQuaternion) {
  76454. _this.getParentsRotation();
  76455. _this._tmpQuat.conjugateInPlace();
  76456. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  76457. }
  76458. // take the position set and make it the absolute position of this object.
  76459. _this.object.setAbsolutePosition(_this.object.position);
  76460. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  76461. _this.object.translate(_this._deltaPosition, 1);
  76462. };
  76463. /**
  76464. * Legacy collision detection event support
  76465. */
  76466. this.onCollideEvent = null;
  76467. //event and body object due to cannon's event-based architecture.
  76468. this.onCollide = function (e) {
  76469. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  76470. return;
  76471. }
  76472. if (!_this._physicsEngine) {
  76473. return;
  76474. }
  76475. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  76476. if (otherImpostor) {
  76477. // Legacy collision detection event support
  76478. if (_this.onCollideEvent) {
  76479. _this.onCollideEvent(_this, otherImpostor);
  76480. }
  76481. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  76482. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  76483. }).forEach(function (obj) {
  76484. obj.callback(_this, otherImpostor);
  76485. });
  76486. }
  76487. };
  76488. //sanity check!
  76489. if (!this.object) {
  76490. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  76491. return;
  76492. }
  76493. //legacy support for old syntax.
  76494. if (!this._scene && object.getScene) {
  76495. this._scene = object.getScene();
  76496. }
  76497. if (!this._scene) {
  76498. return;
  76499. }
  76500. this._physicsEngine = this._scene.getPhysicsEngine();
  76501. if (!this._physicsEngine) {
  76502. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  76503. }
  76504. else {
  76505. //set the object's quaternion, if not set
  76506. if (!this.object.rotationQuaternion) {
  76507. if (this.object.rotation) {
  76508. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  76509. }
  76510. else {
  76511. this.object.rotationQuaternion = new BABYLON.Quaternion();
  76512. }
  76513. }
  76514. //default options params
  76515. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  76516. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  76517. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  76518. this._joints = [];
  76519. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  76520. if (!this.object.parent || this._options.ignoreParent) {
  76521. this._init();
  76522. }
  76523. else if (this.object.parent.physicsImpostor) {
  76524. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  76525. }
  76526. }
  76527. }
  76528. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  76529. get: function () {
  76530. return this._isDisposed;
  76531. },
  76532. enumerable: true,
  76533. configurable: true
  76534. });
  76535. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  76536. get: function () {
  76537. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  76538. },
  76539. set: function (value) {
  76540. this.setMass(value);
  76541. },
  76542. enumerable: true,
  76543. configurable: true
  76544. });
  76545. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  76546. get: function () {
  76547. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  76548. },
  76549. set: function (value) {
  76550. if (!this._physicsEngine) {
  76551. return;
  76552. }
  76553. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  76554. },
  76555. enumerable: true,
  76556. configurable: true
  76557. });
  76558. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  76559. get: function () {
  76560. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  76561. },
  76562. set: function (value) {
  76563. if (!this._physicsEngine) {
  76564. return;
  76565. }
  76566. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  76567. },
  76568. enumerable: true,
  76569. configurable: true
  76570. });
  76571. /**
  76572. * This function will completly initialize this impostor.
  76573. * It will create a new body - but only if this mesh has no parent.
  76574. * If it has, this impostor will not be used other than to define the impostor
  76575. * of the child mesh.
  76576. */
  76577. PhysicsImpostor.prototype._init = function () {
  76578. if (!this._physicsEngine) {
  76579. return;
  76580. }
  76581. this._physicsEngine.removeImpostor(this);
  76582. this.physicsBody = null;
  76583. this._parent = this._parent || this._getPhysicsParent();
  76584. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  76585. this._physicsEngine.addImpostor(this);
  76586. }
  76587. };
  76588. PhysicsImpostor.prototype._getPhysicsParent = function () {
  76589. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  76590. var parentMesh = this.object.parent;
  76591. return parentMesh.physicsImpostor;
  76592. }
  76593. return null;
  76594. };
  76595. /**
  76596. * Should a new body be generated.
  76597. */
  76598. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  76599. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  76600. };
  76601. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  76602. this.forceUpdate();
  76603. };
  76604. /**
  76605. * Force a regeneration of this or the parent's impostor's body.
  76606. * Use under cautious - This will remove all joints already implemented.
  76607. */
  76608. PhysicsImpostor.prototype.forceUpdate = function () {
  76609. this._init();
  76610. if (this.parent && !this._options.ignoreParent) {
  76611. this.parent.forceUpdate();
  76612. }
  76613. };
  76614. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  76615. /*public get mesh(): AbstractMesh {
  76616. return this._mesh;
  76617. }*/
  76618. /**
  76619. * Gets the body that holds this impostor. Either its own, or its parent.
  76620. */
  76621. get: function () {
  76622. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  76623. },
  76624. /**
  76625. * Set the physics body. Used mainly by the physics engine/plugin
  76626. */
  76627. set: function (physicsBody) {
  76628. if (this._physicsBody && this._physicsEngine) {
  76629. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  76630. }
  76631. this._physicsBody = physicsBody;
  76632. this.resetUpdateFlags();
  76633. },
  76634. enumerable: true,
  76635. configurable: true
  76636. });
  76637. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  76638. get: function () {
  76639. return !this._options.ignoreParent && this._parent ? this._parent : null;
  76640. },
  76641. set: function (value) {
  76642. this._parent = value;
  76643. },
  76644. enumerable: true,
  76645. configurable: true
  76646. });
  76647. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  76648. this._bodyUpdateRequired = false;
  76649. };
  76650. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  76651. if (this.object.getBoundingInfo) {
  76652. var q = this.object.rotationQuaternion;
  76653. //reset rotation
  76654. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  76655. //calculate the world matrix with no rotation
  76656. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  76657. var boundingInfo = this.object.getBoundingInfo();
  76658. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  76659. //bring back the rotation
  76660. this.object.rotationQuaternion = q;
  76661. //calculate the world matrix with the new rotation
  76662. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  76663. return size;
  76664. }
  76665. else {
  76666. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  76667. }
  76668. };
  76669. PhysicsImpostor.prototype.getObjectCenter = function () {
  76670. if (this.object.getBoundingInfo) {
  76671. var boundingInfo = this.object.getBoundingInfo();
  76672. return boundingInfo.boundingBox.centerWorld;
  76673. }
  76674. else {
  76675. return this.object.position;
  76676. }
  76677. };
  76678. /**
  76679. * Get a specific parametes from the options parameter.
  76680. */
  76681. PhysicsImpostor.prototype.getParam = function (paramName) {
  76682. return this._options[paramName];
  76683. };
  76684. /**
  76685. * Sets a specific parameter in the options given to the physics plugin
  76686. */
  76687. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  76688. this._options[paramName] = value;
  76689. this._bodyUpdateRequired = true;
  76690. };
  76691. /**
  76692. * Specifically change the body's mass option. Won't recreate the physics body object
  76693. */
  76694. PhysicsImpostor.prototype.setMass = function (mass) {
  76695. if (this.getParam("mass") !== mass) {
  76696. this.setParam("mass", mass);
  76697. }
  76698. if (this._physicsEngine) {
  76699. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  76700. }
  76701. };
  76702. PhysicsImpostor.prototype.getLinearVelocity = function () {
  76703. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  76704. };
  76705. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  76706. if (this._physicsEngine) {
  76707. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  76708. }
  76709. };
  76710. PhysicsImpostor.prototype.getAngularVelocity = function () {
  76711. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  76712. };
  76713. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  76714. if (this._physicsEngine) {
  76715. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  76716. }
  76717. };
  76718. /**
  76719. * Execute a function with the physics plugin native code.
  76720. * Provide a function the will have two variables - the world object and the physics body object.
  76721. */
  76722. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  76723. if (this._physicsEngine) {
  76724. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  76725. }
  76726. };
  76727. /**
  76728. * Register a function that will be executed before the physics world is stepping forward.
  76729. */
  76730. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  76731. this._onBeforePhysicsStepCallbacks.push(func);
  76732. };
  76733. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  76734. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  76735. if (index > -1) {
  76736. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  76737. }
  76738. else {
  76739. BABYLON.Tools.Warn("Function to remove was not found");
  76740. }
  76741. };
  76742. /**
  76743. * Register a function that will be executed after the physics step
  76744. */
  76745. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  76746. this._onAfterPhysicsStepCallbacks.push(func);
  76747. };
  76748. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  76749. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  76750. if (index > -1) {
  76751. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  76752. }
  76753. else {
  76754. BABYLON.Tools.Warn("Function to remove was not found");
  76755. }
  76756. };
  76757. /**
  76758. * register a function that will be executed when this impostor collides against a different body.
  76759. */
  76760. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  76761. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  76762. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  76763. };
  76764. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  76765. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  76766. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  76767. if (index > -1) {
  76768. this._onPhysicsCollideCallbacks.splice(index, 1);
  76769. }
  76770. else {
  76771. BABYLON.Tools.Warn("Function to remove was not found");
  76772. }
  76773. };
  76774. PhysicsImpostor.prototype.getParentsRotation = function () {
  76775. var parent = this.object.parent;
  76776. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  76777. while (parent) {
  76778. if (parent.rotationQuaternion) {
  76779. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  76780. }
  76781. else {
  76782. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  76783. }
  76784. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  76785. parent = parent.parent;
  76786. }
  76787. return this._tmpQuat;
  76788. };
  76789. /**
  76790. * Apply a force
  76791. */
  76792. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  76793. if (this._physicsEngine) {
  76794. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  76795. }
  76796. return this;
  76797. };
  76798. /**
  76799. * Apply an impulse
  76800. */
  76801. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  76802. if (this._physicsEngine) {
  76803. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  76804. }
  76805. return this;
  76806. };
  76807. /**
  76808. * A help function to create a joint.
  76809. */
  76810. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  76811. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  76812. this.addJoint(otherImpostor, joint);
  76813. return this;
  76814. };
  76815. /**
  76816. * Add a joint to this impostor with a different impostor.
  76817. */
  76818. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  76819. this._joints.push({
  76820. otherImpostor: otherImpostor,
  76821. joint: joint
  76822. });
  76823. if (this._physicsEngine) {
  76824. this._physicsEngine.addJoint(this, otherImpostor, joint);
  76825. }
  76826. return this;
  76827. };
  76828. /**
  76829. * Will keep this body still, in a sleep mode.
  76830. */
  76831. PhysicsImpostor.prototype.sleep = function () {
  76832. if (this._physicsEngine) {
  76833. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  76834. }
  76835. return this;
  76836. };
  76837. /**
  76838. * Wake the body up.
  76839. */
  76840. PhysicsImpostor.prototype.wakeUp = function () {
  76841. if (this._physicsEngine) {
  76842. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  76843. }
  76844. return this;
  76845. };
  76846. PhysicsImpostor.prototype.clone = function (newObject) {
  76847. if (!newObject)
  76848. return null;
  76849. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  76850. };
  76851. PhysicsImpostor.prototype.dispose = function () {
  76852. var _this = this;
  76853. //no dispose if no physics engine is available.
  76854. if (!this._physicsEngine) {
  76855. return;
  76856. }
  76857. this._joints.forEach(function (j) {
  76858. if (_this._physicsEngine) {
  76859. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  76860. }
  76861. });
  76862. //dispose the physics body
  76863. this._physicsEngine.removeImpostor(this);
  76864. if (this.parent) {
  76865. this.parent.forceUpdate();
  76866. }
  76867. else {
  76868. /*this._object.getChildMeshes().forEach(function(mesh) {
  76869. if (mesh.physicsImpostor) {
  76870. if (disposeChildren) {
  76871. mesh.physicsImpostor.dispose();
  76872. mesh.physicsImpostor = null;
  76873. }
  76874. }
  76875. })*/
  76876. }
  76877. this._isDisposed = true;
  76878. };
  76879. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  76880. this._deltaPosition.copyFrom(position);
  76881. };
  76882. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  76883. if (!this._deltaRotation) {
  76884. this._deltaRotation = new BABYLON.Quaternion();
  76885. }
  76886. this._deltaRotation.copyFrom(rotation);
  76887. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  76888. };
  76889. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  76890. if (this._physicsEngine) {
  76891. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  76892. }
  76893. return this;
  76894. };
  76895. PhysicsImpostor.prototype.getRadius = function () {
  76896. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  76897. };
  76898. /**
  76899. * Sync a bone with this impostor
  76900. * @param bone The bone to sync to the impostor.
  76901. * @param boneMesh The mesh that the bone is influencing.
  76902. * @param jointPivot The pivot of the joint / bone in local space.
  76903. * @param distToJoint Optional distance from the impostor to the joint.
  76904. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  76905. */
  76906. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  76907. var tempVec = PhysicsImpostor._tmpVecs[0];
  76908. var mesh = this.object;
  76909. if (mesh.rotationQuaternion) {
  76910. if (adjustRotation) {
  76911. var tempQuat = PhysicsImpostor._tmpQuat;
  76912. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  76913. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  76914. }
  76915. else {
  76916. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  76917. }
  76918. }
  76919. tempVec.x = 0;
  76920. tempVec.y = 0;
  76921. tempVec.z = 0;
  76922. if (jointPivot) {
  76923. tempVec.x = jointPivot.x;
  76924. tempVec.y = jointPivot.y;
  76925. tempVec.z = jointPivot.z;
  76926. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  76927. if (distToJoint === undefined || distToJoint === null) {
  76928. distToJoint = jointPivot.length();
  76929. }
  76930. tempVec.x *= distToJoint;
  76931. tempVec.y *= distToJoint;
  76932. tempVec.z *= distToJoint;
  76933. }
  76934. if (bone.getParent()) {
  76935. tempVec.addInPlace(mesh.getAbsolutePosition());
  76936. bone.setAbsolutePosition(tempVec, boneMesh);
  76937. }
  76938. else {
  76939. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  76940. boneMesh.position.x -= tempVec.x;
  76941. boneMesh.position.y -= tempVec.y;
  76942. boneMesh.position.z -= tempVec.z;
  76943. }
  76944. };
  76945. /**
  76946. * Sync impostor to a bone
  76947. * @param bone The bone that the impostor will be synced to.
  76948. * @param boneMesh The mesh that the bone is influencing.
  76949. * @param jointPivot The pivot of the joint / bone in local space.
  76950. * @param distToJoint Optional distance from the impostor to the joint.
  76951. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  76952. * @param boneAxis Optional vector3 axis the bone is aligned with
  76953. */
  76954. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  76955. var mesh = this.object;
  76956. if (mesh.rotationQuaternion) {
  76957. if (adjustRotation) {
  76958. var tempQuat = PhysicsImpostor._tmpQuat;
  76959. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  76960. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  76961. }
  76962. else {
  76963. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  76964. }
  76965. }
  76966. var pos = PhysicsImpostor._tmpVecs[0];
  76967. var boneDir = PhysicsImpostor._tmpVecs[1];
  76968. if (!boneAxis) {
  76969. boneAxis = PhysicsImpostor._tmpVecs[2];
  76970. boneAxis.x = 0;
  76971. boneAxis.y = 1;
  76972. boneAxis.z = 0;
  76973. }
  76974. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  76975. bone.getAbsolutePositionToRef(boneMesh, pos);
  76976. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  76977. distToJoint = jointPivot.length();
  76978. }
  76979. if (distToJoint !== undefined && distToJoint !== null) {
  76980. pos.x += boneDir.x * distToJoint;
  76981. pos.y += boneDir.y * distToJoint;
  76982. pos.z += boneDir.z * distToJoint;
  76983. }
  76984. mesh.setAbsolutePosition(pos);
  76985. };
  76986. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  76987. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  76988. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76989. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  76990. //Impostor types
  76991. PhysicsImpostor.NoImpostor = 0;
  76992. PhysicsImpostor.SphereImpostor = 1;
  76993. PhysicsImpostor.BoxImpostor = 2;
  76994. PhysicsImpostor.PlaneImpostor = 3;
  76995. PhysicsImpostor.MeshImpostor = 4;
  76996. PhysicsImpostor.CylinderImpostor = 7;
  76997. PhysicsImpostor.ParticleImpostor = 8;
  76998. PhysicsImpostor.HeightmapImpostor = 9;
  76999. return PhysicsImpostor;
  77000. }());
  77001. BABYLON.PhysicsImpostor = PhysicsImpostor;
  77002. })(BABYLON || (BABYLON = {}));
  77003. //# sourceMappingURL=babylon.physicsImpostor.js.map
  77004. var BABYLON;
  77005. (function (BABYLON) {
  77006. var PhysicsEngine = /** @class */ (function () {
  77007. function PhysicsEngine(gravity, _physicsPlugin) {
  77008. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  77009. this._physicsPlugin = _physicsPlugin;
  77010. //new methods and parameters
  77011. this._impostors = [];
  77012. this._joints = [];
  77013. if (!this._physicsPlugin.isSupported()) {
  77014. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  77015. + "Please make sure it is included.");
  77016. }
  77017. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  77018. this.setGravity(gravity);
  77019. this.setTimeStep();
  77020. }
  77021. PhysicsEngine.prototype.setGravity = function (gravity) {
  77022. this.gravity = gravity;
  77023. this._physicsPlugin.setGravity(this.gravity);
  77024. };
  77025. /**
  77026. * Set the time step of the physics engine.
  77027. * default is 1/60.
  77028. * To slow it down, enter 1/600 for example.
  77029. * To speed it up, 1/30
  77030. * @param {number} newTimeStep the new timestep to apply to this world.
  77031. */
  77032. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  77033. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  77034. this._physicsPlugin.setTimeStep(newTimeStep);
  77035. };
  77036. /**
  77037. * Get the time step of the physics engine.
  77038. */
  77039. PhysicsEngine.prototype.getTimeStep = function () {
  77040. return this._physicsPlugin.getTimeStep();
  77041. };
  77042. PhysicsEngine.prototype.dispose = function () {
  77043. this._impostors.forEach(function (impostor) {
  77044. impostor.dispose();
  77045. });
  77046. this._physicsPlugin.dispose();
  77047. };
  77048. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  77049. return this._physicsPlugin.name;
  77050. };
  77051. /**
  77052. * Adding a new impostor for the impostor tracking.
  77053. * This will be done by the impostor itself.
  77054. * @param {PhysicsImpostor} impostor the impostor to add
  77055. */
  77056. PhysicsEngine.prototype.addImpostor = function (impostor) {
  77057. impostor.uniqueId = this._impostors.push(impostor);
  77058. //if no parent, generate the body
  77059. if (!impostor.parent) {
  77060. this._physicsPlugin.generatePhysicsBody(impostor);
  77061. }
  77062. };
  77063. /**
  77064. * Remove an impostor from the engine.
  77065. * This impostor and its mesh will not longer be updated by the physics engine.
  77066. * @param {PhysicsImpostor} impostor the impostor to remove
  77067. */
  77068. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  77069. var index = this._impostors.indexOf(impostor);
  77070. if (index > -1) {
  77071. var removed = this._impostors.splice(index, 1);
  77072. //Is it needed?
  77073. if (removed.length) {
  77074. //this will also remove it from the world.
  77075. removed[0].physicsBody = null;
  77076. }
  77077. }
  77078. };
  77079. /**
  77080. * Add a joint to the physics engine
  77081. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  77082. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  77083. * @param {PhysicsJoint} the joint that will connect both impostors.
  77084. */
  77085. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  77086. var impostorJoint = {
  77087. mainImpostor: mainImpostor,
  77088. connectedImpostor: connectedImpostor,
  77089. joint: joint
  77090. };
  77091. joint.physicsPlugin = this._physicsPlugin;
  77092. this._joints.push(impostorJoint);
  77093. this._physicsPlugin.generateJoint(impostorJoint);
  77094. };
  77095. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  77096. var matchingJoints = this._joints.filter(function (impostorJoint) {
  77097. return (impostorJoint.connectedImpostor === connectedImpostor
  77098. && impostorJoint.joint === joint
  77099. && impostorJoint.mainImpostor === mainImpostor);
  77100. });
  77101. if (matchingJoints.length) {
  77102. this._physicsPlugin.removeJoint(matchingJoints[0]);
  77103. //TODO remove it from the list as well
  77104. }
  77105. };
  77106. /**
  77107. * Called by the scene. no need to call it.
  77108. */
  77109. PhysicsEngine.prototype._step = function (delta) {
  77110. var _this = this;
  77111. //check if any mesh has no body / requires an update
  77112. this._impostors.forEach(function (impostor) {
  77113. if (impostor.isBodyInitRequired()) {
  77114. _this._physicsPlugin.generatePhysicsBody(impostor);
  77115. }
  77116. });
  77117. if (delta > 0.1) {
  77118. delta = 0.1;
  77119. }
  77120. else if (delta <= 0) {
  77121. delta = 1.0 / 60.0;
  77122. }
  77123. this._physicsPlugin.executeStep(delta, this._impostors);
  77124. };
  77125. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  77126. return this._physicsPlugin;
  77127. };
  77128. PhysicsEngine.prototype.getImpostors = function () {
  77129. return this._impostors;
  77130. };
  77131. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  77132. for (var i = 0; i < this._impostors.length; ++i) {
  77133. if (this._impostors[i].object === object) {
  77134. return this._impostors[i];
  77135. }
  77136. }
  77137. return null;
  77138. };
  77139. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  77140. for (var i = 0; i < this._impostors.length; ++i) {
  77141. if (this._impostors[i].physicsBody === body) {
  77142. return this._impostors[i];
  77143. }
  77144. }
  77145. return null;
  77146. };
  77147. // Statics
  77148. PhysicsEngine.Epsilon = 0.001;
  77149. return PhysicsEngine;
  77150. }());
  77151. BABYLON.PhysicsEngine = PhysicsEngine;
  77152. })(BABYLON || (BABYLON = {}));
  77153. //# sourceMappingURL=babylon.physicsEngine.js.map
  77154. var BABYLON;
  77155. (function (BABYLON) {
  77156. var PhysicsHelper = /** @class */ (function () {
  77157. function PhysicsHelper(scene) {
  77158. this._scene = scene;
  77159. this._physicsEngine = this._scene.getPhysicsEngine();
  77160. if (!this._physicsEngine) {
  77161. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  77162. }
  77163. }
  77164. /**
  77165. * @param {Vector3} origin the origin of the explosion
  77166. * @param {number} radius the explosion radius
  77167. * @param {number} strength the explosion strength
  77168. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77169. */
  77170. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  77171. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77172. if (!this._physicsEngine) {
  77173. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  77174. return null;
  77175. }
  77176. var impostors = this._physicsEngine.getImpostors();
  77177. if (impostors.length === 0) {
  77178. return null;
  77179. }
  77180. var event = new PhysicsRadialExplosionEvent(this._scene);
  77181. impostors.forEach(function (impostor) {
  77182. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77183. if (!impostorForceAndContactPoint) {
  77184. return;
  77185. }
  77186. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77187. });
  77188. event.dispose(false);
  77189. return event;
  77190. };
  77191. /**
  77192. * @param {Vector3} origin the origin of the explosion
  77193. * @param {number} radius the explosion radius
  77194. * @param {number} strength the explosion strength
  77195. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77196. */
  77197. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  77198. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77199. if (!this._physicsEngine) {
  77200. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77201. return null;
  77202. }
  77203. var impostors = this._physicsEngine.getImpostors();
  77204. if (impostors.length === 0) {
  77205. return null;
  77206. }
  77207. var event = new PhysicsRadialExplosionEvent(this._scene);
  77208. impostors.forEach(function (impostor) {
  77209. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77210. if (!impostorForceAndContactPoint) {
  77211. return;
  77212. }
  77213. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77214. });
  77215. event.dispose(false);
  77216. return event;
  77217. };
  77218. /**
  77219. * @param {Vector3} origin the origin of the explosion
  77220. * @param {number} radius the explosion radius
  77221. * @param {number} strength the explosion strength
  77222. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77223. */
  77224. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  77225. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77226. if (!this._physicsEngine) {
  77227. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77228. return null;
  77229. }
  77230. var impostors = this._physicsEngine.getImpostors();
  77231. if (impostors.length === 0) {
  77232. return null;
  77233. }
  77234. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  77235. event.dispose(false);
  77236. return event;
  77237. };
  77238. /**
  77239. * @param {Vector3} origin the origin of the updraft
  77240. * @param {number} radius the radius of the updraft
  77241. * @param {number} strength the strength of the updraft
  77242. * @param {number} height the height of the updraft
  77243. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  77244. */
  77245. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  77246. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  77247. if (!this._physicsEngine) {
  77248. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77249. return null;
  77250. }
  77251. if (this._physicsEngine.getImpostors().length === 0) {
  77252. return null;
  77253. }
  77254. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  77255. event.dispose(false);
  77256. return event;
  77257. };
  77258. /**
  77259. * @param {Vector3} origin the of the vortex
  77260. * @param {number} radius the radius of the vortex
  77261. * @param {number} strength the strength of the vortex
  77262. * @param {number} height the height of the vortex
  77263. */
  77264. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  77265. if (!this._physicsEngine) {
  77266. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77267. return null;
  77268. }
  77269. if (this._physicsEngine.getImpostors().length === 0) {
  77270. return null;
  77271. }
  77272. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  77273. event.dispose(false);
  77274. return event;
  77275. };
  77276. return PhysicsHelper;
  77277. }());
  77278. BABYLON.PhysicsHelper = PhysicsHelper;
  77279. /***** Radial explosion *****/
  77280. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  77281. function PhysicsRadialExplosionEvent(scene) {
  77282. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  77283. this._rays = [];
  77284. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  77285. this._scene = scene;
  77286. }
  77287. /**
  77288. * Returns the data related to the radial explosion event (sphere & rays).
  77289. * @returns {PhysicsRadialExplosionEventData}
  77290. */
  77291. PhysicsRadialExplosionEvent.prototype.getData = function () {
  77292. this._dataFetched = true;
  77293. return {
  77294. sphere: this._sphere,
  77295. rays: this._rays,
  77296. };
  77297. };
  77298. /**
  77299. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  77300. * @param impostor
  77301. * @param {Vector3} origin the origin of the explosion
  77302. * @param {number} radius the explosion radius
  77303. * @param {number} strength the explosion strength
  77304. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  77305. * @returns {Nullable<PhysicsForceAndContactPoint>}
  77306. */
  77307. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  77308. if (impostor.mass === 0) {
  77309. return null;
  77310. }
  77311. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  77312. return null;
  77313. }
  77314. if (impostor.object.getClassName() !== 'Mesh') {
  77315. return null;
  77316. }
  77317. var impostorObject = impostor.object;
  77318. var impostorObjectCenter = impostor.getObjectCenter();
  77319. var direction = impostorObjectCenter.subtract(origin);
  77320. var ray = new BABYLON.Ray(origin, direction, radius);
  77321. this._rays.push(ray);
  77322. var hit = ray.intersectsMesh(impostorObject);
  77323. var contactPoint = hit.pickedPoint;
  77324. if (!contactPoint) {
  77325. return null;
  77326. }
  77327. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  77328. if (distanceFromOrigin > radius) {
  77329. return null;
  77330. }
  77331. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  77332. ? strength
  77333. : strength * (1 - (distanceFromOrigin / radius));
  77334. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  77335. return { force: force, contactPoint: contactPoint };
  77336. };
  77337. /**
  77338. * Disposes the sphere.
  77339. * @param {bolean} force
  77340. */
  77341. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  77342. var _this = this;
  77343. if (force === void 0) { force = true; }
  77344. if (force) {
  77345. this._sphere.dispose();
  77346. }
  77347. else {
  77348. setTimeout(function () {
  77349. if (!_this._dataFetched) {
  77350. _this._sphere.dispose();
  77351. }
  77352. }, 0);
  77353. }
  77354. };
  77355. /*** Helpers ***/
  77356. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  77357. if (!this._sphere) {
  77358. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  77359. this._sphere.isVisible = false;
  77360. }
  77361. };
  77362. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  77363. var impostorObject = impostor.object;
  77364. this._prepareSphere();
  77365. this._sphere.position = origin;
  77366. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  77367. this._sphere._updateBoundingInfo();
  77368. this._sphere.computeWorldMatrix(true);
  77369. return this._sphere.intersectsMesh(impostorObject, true);
  77370. };
  77371. return PhysicsRadialExplosionEvent;
  77372. }());
  77373. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  77374. /***** Gravitational Field *****/
  77375. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  77376. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  77377. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77378. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77379. this._physicsHelper = physicsHelper;
  77380. this._scene = scene;
  77381. this._origin = origin;
  77382. this._radius = radius;
  77383. this._strength = strength;
  77384. this._falloff = falloff;
  77385. this._tickCallback = this._tick.bind(this);
  77386. }
  77387. /**
  77388. * Returns the data related to the gravitational field event (sphere).
  77389. * @returns {PhysicsGravitationalFieldEventData}
  77390. */
  77391. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  77392. this._dataFetched = true;
  77393. return {
  77394. sphere: this._sphere,
  77395. };
  77396. };
  77397. /**
  77398. * Enables the gravitational field.
  77399. */
  77400. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  77401. this._tickCallback.call(this);
  77402. this._scene.registerBeforeRender(this._tickCallback);
  77403. };
  77404. /**
  77405. * Disables the gravitational field.
  77406. */
  77407. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  77408. this._scene.unregisterBeforeRender(this._tickCallback);
  77409. };
  77410. /**
  77411. * Disposes the sphere.
  77412. * @param {bolean} force
  77413. */
  77414. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  77415. var _this = this;
  77416. if (force === void 0) { force = true; }
  77417. if (force) {
  77418. this._sphere.dispose();
  77419. }
  77420. else {
  77421. setTimeout(function () {
  77422. if (!_this._dataFetched) {
  77423. _this._sphere.dispose();
  77424. }
  77425. }, 0);
  77426. }
  77427. };
  77428. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  77429. // Since the params won't change, we fetch the event only once
  77430. if (this._sphere) {
  77431. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  77432. }
  77433. else {
  77434. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  77435. if (radialExplosionEvent) {
  77436. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  77437. }
  77438. }
  77439. };
  77440. return PhysicsGravitationalFieldEvent;
  77441. }());
  77442. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  77443. /***** Updraft *****/
  77444. var PhysicsUpdraftEvent = /** @class */ (function () {
  77445. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  77446. this._scene = _scene;
  77447. this._origin = _origin;
  77448. this._radius = _radius;
  77449. this._strength = _strength;
  77450. this._height = _height;
  77451. this._updraftMode = _updraftMode;
  77452. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  77453. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  77454. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  77455. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77456. this._physicsEngine = this._scene.getPhysicsEngine();
  77457. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  77458. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  77459. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  77460. this._originDirection = this._origin.subtract(this._originTop).normalize();
  77461. }
  77462. this._tickCallback = this._tick.bind(this);
  77463. }
  77464. /**
  77465. * Returns the data related to the updraft event (cylinder).
  77466. * @returns {PhysicsUpdraftEventData}
  77467. */
  77468. PhysicsUpdraftEvent.prototype.getData = function () {
  77469. this._dataFetched = true;
  77470. return {
  77471. cylinder: this._cylinder,
  77472. };
  77473. };
  77474. /**
  77475. * Enables the updraft.
  77476. */
  77477. PhysicsUpdraftEvent.prototype.enable = function () {
  77478. this._tickCallback.call(this);
  77479. this._scene.registerBeforeRender(this._tickCallback);
  77480. };
  77481. /**
  77482. * Disables the cortex.
  77483. */
  77484. PhysicsUpdraftEvent.prototype.disable = function () {
  77485. this._scene.unregisterBeforeRender(this._tickCallback);
  77486. };
  77487. /**
  77488. * Disposes the sphere.
  77489. * @param {bolean} force
  77490. */
  77491. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  77492. var _this = this;
  77493. if (force === void 0) { force = true; }
  77494. if (force) {
  77495. this._cylinder.dispose();
  77496. }
  77497. else {
  77498. setTimeout(function () {
  77499. if (!_this._dataFetched) {
  77500. _this._cylinder.dispose();
  77501. }
  77502. }, 0);
  77503. }
  77504. };
  77505. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  77506. if (impostor.mass === 0) {
  77507. return null;
  77508. }
  77509. if (!this._intersectsWithCylinder(impostor)) {
  77510. return null;
  77511. }
  77512. var impostorObjectCenter = impostor.getObjectCenter();
  77513. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  77514. var direction = this._originDirection;
  77515. }
  77516. else {
  77517. var direction = impostorObjectCenter.subtract(this._originTop);
  77518. }
  77519. var multiplier = this._strength * -1;
  77520. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  77521. return { force: force, contactPoint: impostorObjectCenter };
  77522. };
  77523. PhysicsUpdraftEvent.prototype._tick = function () {
  77524. var _this = this;
  77525. this._physicsEngine.getImpostors().forEach(function (impostor) {
  77526. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  77527. if (!impostorForceAndContactPoint) {
  77528. return;
  77529. }
  77530. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77531. });
  77532. };
  77533. /*** Helpers ***/
  77534. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  77535. if (!this._cylinder) {
  77536. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  77537. height: this._height,
  77538. diameter: this._radius * 2,
  77539. }, this._scene);
  77540. this._cylinder.isVisible = false;
  77541. }
  77542. };
  77543. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  77544. var impostorObject = impostor.object;
  77545. this._prepareCylinder();
  77546. this._cylinder.position = this._cylinderPosition;
  77547. return this._cylinder.intersectsMesh(impostorObject, true);
  77548. };
  77549. return PhysicsUpdraftEvent;
  77550. }());
  77551. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  77552. /***** Vortex *****/
  77553. var PhysicsVortexEvent = /** @class */ (function () {
  77554. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  77555. this._scene = _scene;
  77556. this._origin = _origin;
  77557. this._radius = _radius;
  77558. this._strength = _strength;
  77559. this._height = _height;
  77560. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  77561. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  77562. this._updraftMultiplier = 0.02;
  77563. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  77564. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77565. this._physicsEngine = this._scene.getPhysicsEngine();
  77566. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  77567. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  77568. this._tickCallback = this._tick.bind(this);
  77569. }
  77570. /**
  77571. * Returns the data related to the vortex event (cylinder).
  77572. * @returns {PhysicsVortexEventData}
  77573. */
  77574. PhysicsVortexEvent.prototype.getData = function () {
  77575. this._dataFetched = true;
  77576. return {
  77577. cylinder: this._cylinder,
  77578. };
  77579. };
  77580. /**
  77581. * Enables the vortex.
  77582. */
  77583. PhysicsVortexEvent.prototype.enable = function () {
  77584. this._tickCallback.call(this);
  77585. this._scene.registerBeforeRender(this._tickCallback);
  77586. };
  77587. /**
  77588. * Disables the cortex.
  77589. */
  77590. PhysicsVortexEvent.prototype.disable = function () {
  77591. this._scene.unregisterBeforeRender(this._tickCallback);
  77592. };
  77593. /**
  77594. * Disposes the sphere.
  77595. * @param {bolean} force
  77596. */
  77597. PhysicsVortexEvent.prototype.dispose = function (force) {
  77598. var _this = this;
  77599. if (force === void 0) { force = true; }
  77600. if (force) {
  77601. this._cylinder.dispose();
  77602. }
  77603. else {
  77604. setTimeout(function () {
  77605. if (!_this._dataFetched) {
  77606. _this._cylinder.dispose();
  77607. }
  77608. }, 0);
  77609. }
  77610. };
  77611. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  77612. if (impostor.mass === 0) {
  77613. return null;
  77614. }
  77615. if (!this._intersectsWithCylinder(impostor)) {
  77616. return null;
  77617. }
  77618. if (impostor.object.getClassName() !== 'Mesh') {
  77619. return null;
  77620. }
  77621. var impostorObject = impostor.object;
  77622. var impostorObjectCenter = impostor.getObjectCenter();
  77623. 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)
  77624. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  77625. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  77626. var hit = ray.intersectsMesh(impostorObject);
  77627. var contactPoint = hit.pickedPoint;
  77628. if (!contactPoint) {
  77629. return null;
  77630. }
  77631. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  77632. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  77633. var directionToOrigin = contactPoint.normalize();
  77634. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  77635. directionToOrigin = directionToOrigin.negate();
  77636. }
  77637. // TODO: find a more physically based solution
  77638. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  77639. var forceX = directionToOrigin.x * this._strength / 8;
  77640. var forceY = directionToOrigin.y * this._updraftMultiplier;
  77641. var forceZ = directionToOrigin.z * this._strength / 8;
  77642. }
  77643. else {
  77644. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  77645. var forceY = this._originTop.y * this._updraftMultiplier;
  77646. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  77647. }
  77648. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  77649. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  77650. return { force: force, contactPoint: impostorObjectCenter };
  77651. };
  77652. PhysicsVortexEvent.prototype._tick = function () {
  77653. var _this = this;
  77654. this._physicsEngine.getImpostors().forEach(function (impostor) {
  77655. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  77656. if (!impostorForceAndContactPoint) {
  77657. return;
  77658. }
  77659. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77660. });
  77661. };
  77662. /*** Helpers ***/
  77663. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  77664. if (!this._cylinder) {
  77665. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  77666. height: this._height,
  77667. diameter: this._radius * 2,
  77668. }, this._scene);
  77669. this._cylinder.isVisible = false;
  77670. }
  77671. };
  77672. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  77673. var impostorObject = impostor.object;
  77674. this._prepareCylinder();
  77675. this._cylinder.position = this._cylinderPosition;
  77676. return this._cylinder.intersectsMesh(impostorObject, true);
  77677. };
  77678. return PhysicsVortexEvent;
  77679. }());
  77680. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  77681. /***** Enums *****/
  77682. /**
  77683. * The strenght of the force in correspondence to the distance of the affected object
  77684. */
  77685. var PhysicsRadialImpulseFalloff;
  77686. (function (PhysicsRadialImpulseFalloff) {
  77687. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  77688. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  77689. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  77690. /**
  77691. * The strenght of the force in correspondence to the distance of the affected object
  77692. */
  77693. var PhysicsUpdraftMode;
  77694. (function (PhysicsUpdraftMode) {
  77695. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  77696. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  77697. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  77698. })(BABYLON || (BABYLON = {}));
  77699. //# sourceMappingURL=babylon.physicsHelper.js.map
  77700. var BABYLON;
  77701. (function (BABYLON) {
  77702. var CannonJSPlugin = /** @class */ (function () {
  77703. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  77704. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  77705. if (iterations === void 0) { iterations = 10; }
  77706. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  77707. this.name = "CannonJSPlugin";
  77708. this._physicsMaterials = new Array();
  77709. this._fixedTimeStep = 1 / 60;
  77710. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  77711. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : ( true ? __webpack_require__(17) : undefined);
  77712. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  77713. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  77714. this._tmpPosition = BABYLON.Vector3.Zero();
  77715. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  77716. this._tmpUnityRotation = new BABYLON.Quaternion();
  77717. if (!this.isSupported()) {
  77718. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  77719. return;
  77720. }
  77721. this._extendNamespace();
  77722. this.world = new this.BJSCANNON.World();
  77723. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  77724. this.world.solver.iterations = iterations;
  77725. }
  77726. CannonJSPlugin.prototype.setGravity = function (gravity) {
  77727. this.world.gravity.copy(gravity);
  77728. };
  77729. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  77730. this._fixedTimeStep = timeStep;
  77731. };
  77732. CannonJSPlugin.prototype.getTimeStep = function () {
  77733. return this._fixedTimeStep;
  77734. };
  77735. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  77736. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  77737. };
  77738. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  77739. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  77740. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  77741. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  77742. };
  77743. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  77744. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  77745. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  77746. impostor.physicsBody.applyForce(impulse, worldPoint);
  77747. };
  77748. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  77749. //parent-child relationship. Does this impostor has a parent impostor?
  77750. if (impostor.parent) {
  77751. if (impostor.physicsBody) {
  77752. this.removePhysicsBody(impostor);
  77753. //TODO is that needed?
  77754. impostor.forceUpdate();
  77755. }
  77756. return;
  77757. }
  77758. //should a new body be created for this impostor?
  77759. if (impostor.isBodyInitRequired()) {
  77760. var shape = this._createShape(impostor);
  77761. //unregister events, if body is being changed
  77762. var oldBody = impostor.physicsBody;
  77763. if (oldBody) {
  77764. this.removePhysicsBody(impostor);
  77765. }
  77766. //create the body and material
  77767. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  77768. var bodyCreationObject = {
  77769. mass: impostor.getParam("mass"),
  77770. material: material
  77771. };
  77772. // A simple extend, in case native options were used.
  77773. var nativeOptions = impostor.getParam("nativeOptions");
  77774. for (var key in nativeOptions) {
  77775. if (nativeOptions.hasOwnProperty(key)) {
  77776. bodyCreationObject[key] = nativeOptions[key];
  77777. }
  77778. }
  77779. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  77780. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  77781. this.world.addEventListener("preStep", impostor.beforeStep);
  77782. this.world.addEventListener("postStep", impostor.afterStep);
  77783. impostor.physicsBody.addShape(shape);
  77784. this.world.add(impostor.physicsBody);
  77785. //try to keep the body moving in the right direction by taking old properties.
  77786. //Should be tested!
  77787. if (oldBody) {
  77788. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  77789. impostor.physicsBody[param].copy(oldBody[param]);
  77790. });
  77791. }
  77792. this._processChildMeshes(impostor);
  77793. }
  77794. //now update the body's transformation
  77795. this._updatePhysicsBodyTransformation(impostor);
  77796. };
  77797. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  77798. var _this = this;
  77799. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  77800. var currentRotation = mainImpostor.object.rotationQuaternion;
  77801. if (meshChildren.length) {
  77802. var processMesh = function (localPosition, mesh) {
  77803. if (!currentRotation || !mesh.rotationQuaternion) {
  77804. return;
  77805. }
  77806. var childImpostor = mesh.getPhysicsImpostor();
  77807. if (childImpostor) {
  77808. var parent = childImpostor.parent;
  77809. if (parent !== mainImpostor) {
  77810. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  77811. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  77812. if (childImpostor.physicsBody) {
  77813. _this.removePhysicsBody(childImpostor);
  77814. childImpostor.physicsBody = null;
  77815. }
  77816. childImpostor.parent = mainImpostor;
  77817. childImpostor.resetUpdateFlags();
  77818. 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));
  77819. //Add the mass of the children.
  77820. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  77821. }
  77822. }
  77823. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  77824. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  77825. };
  77826. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  77827. }
  77828. };
  77829. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  77830. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  77831. this.world.removeEventListener("preStep", impostor.beforeStep);
  77832. this.world.removeEventListener("postStep", impostor.afterStep);
  77833. this.world.remove(impostor.physicsBody);
  77834. };
  77835. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  77836. var mainBody = impostorJoint.mainImpostor.physicsBody;
  77837. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  77838. if (!mainBody || !connectedBody) {
  77839. return;
  77840. }
  77841. var constraint;
  77842. var jointData = impostorJoint.joint.jointData;
  77843. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  77844. var constraintData = {
  77845. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  77846. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  77847. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  77848. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  77849. maxForce: jointData.nativeParams.maxForce,
  77850. collideConnected: !!jointData.collision
  77851. };
  77852. switch (impostorJoint.joint.type) {
  77853. case BABYLON.PhysicsJoint.HingeJoint:
  77854. case BABYLON.PhysicsJoint.Hinge2Joint:
  77855. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  77856. break;
  77857. case BABYLON.PhysicsJoint.DistanceJoint:
  77858. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  77859. break;
  77860. case BABYLON.PhysicsJoint.SpringJoint:
  77861. var springData = jointData;
  77862. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  77863. restLength: springData.length,
  77864. stiffness: springData.stiffness,
  77865. damping: springData.damping,
  77866. localAnchorA: constraintData.pivotA,
  77867. localAnchorB: constraintData.pivotB
  77868. });
  77869. break;
  77870. case BABYLON.PhysicsJoint.LockJoint:
  77871. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  77872. break;
  77873. case BABYLON.PhysicsJoint.PointToPointJoint:
  77874. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  77875. default:
  77876. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  77877. break;
  77878. }
  77879. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  77880. constraint.collideConnected = !!jointData.collision;
  77881. impostorJoint.joint.physicsJoint = constraint;
  77882. //don't add spring as constraint, as it is not one.
  77883. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  77884. this.world.addConstraint(constraint);
  77885. }
  77886. else {
  77887. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  77888. constraint.applyForce();
  77889. });
  77890. }
  77891. };
  77892. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  77893. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  77894. };
  77895. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  77896. var index;
  77897. var mat;
  77898. for (index = 0; index < this._physicsMaterials.length; index++) {
  77899. mat = this._physicsMaterials[index];
  77900. if (mat.friction === friction && mat.restitution === restitution) {
  77901. return mat;
  77902. }
  77903. }
  77904. var currentMat = new this.BJSCANNON.Material(name);
  77905. currentMat.friction = friction;
  77906. currentMat.restitution = restitution;
  77907. this._physicsMaterials.push(currentMat);
  77908. return currentMat;
  77909. };
  77910. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  77911. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  77912. };
  77913. CannonJSPlugin.prototype._createShape = function (impostor) {
  77914. var object = impostor.object;
  77915. var returnValue;
  77916. var extendSize = impostor.getObjectExtendSize();
  77917. switch (impostor.type) {
  77918. case BABYLON.PhysicsImpostor.SphereImpostor:
  77919. var radiusX = extendSize.x;
  77920. var radiusY = extendSize.y;
  77921. var radiusZ = extendSize.z;
  77922. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  77923. break;
  77924. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  77925. case BABYLON.PhysicsImpostor.CylinderImpostor:
  77926. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  77927. break;
  77928. case BABYLON.PhysicsImpostor.BoxImpostor:
  77929. var box = extendSize.scale(0.5);
  77930. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  77931. break;
  77932. case BABYLON.PhysicsImpostor.PlaneImpostor:
  77933. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  77934. returnValue = new this.BJSCANNON.Plane();
  77935. break;
  77936. case BABYLON.PhysicsImpostor.MeshImpostor:
  77937. // should transform the vertex data to world coordinates!!
  77938. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  77939. var rawFaces = object.getIndices ? object.getIndices() : [];
  77940. if (!rawVerts)
  77941. return;
  77942. // get only scale! so the object could transform correctly.
  77943. var oldPosition = object.position.clone();
  77944. var oldRotation = object.rotation && object.rotation.clone();
  77945. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  77946. object.position.copyFromFloats(0, 0, 0);
  77947. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  77948. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  77949. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  77950. var transform = object.computeWorldMatrix(true);
  77951. // convert rawVerts to object space
  77952. var temp = new Array();
  77953. var index;
  77954. for (index = 0; index < rawVerts.length; index += 3) {
  77955. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  77956. }
  77957. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  77958. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  77959. //now set back the transformation!
  77960. object.position.copyFrom(oldPosition);
  77961. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  77962. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  77963. break;
  77964. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  77965. var oldPosition2 = object.position.clone();
  77966. var oldRotation2 = object.rotation && object.rotation.clone();
  77967. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  77968. object.position.copyFromFloats(0, 0, 0);
  77969. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  77970. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  77971. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  77972. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  77973. returnValue = this._createHeightmap(object);
  77974. object.position.copyFrom(oldPosition2);
  77975. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  77976. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  77977. object.computeWorldMatrix(true);
  77978. break;
  77979. case BABYLON.PhysicsImpostor.ParticleImpostor:
  77980. returnValue = new this.BJSCANNON.Particle();
  77981. break;
  77982. }
  77983. return returnValue;
  77984. };
  77985. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  77986. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  77987. var transform = object.computeWorldMatrix(true);
  77988. // convert rawVerts to object space
  77989. var temp = new Array();
  77990. var index;
  77991. for (index = 0; index < pos.length; index += 3) {
  77992. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  77993. }
  77994. pos = temp;
  77995. var matrix = new Array();
  77996. //For now pointDepth will not be used and will be automatically calculated.
  77997. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  77998. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  77999. var boundingInfo = object.getBoundingInfo();
  78000. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  78001. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  78002. var elementSize = dim * 2 / arraySize;
  78003. for (var i = 0; i < pos.length; i = i + 3) {
  78004. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  78005. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  78006. var y = -pos[i + 2] + minY;
  78007. if (!matrix[x]) {
  78008. matrix[x] = [];
  78009. }
  78010. if (!matrix[x][z]) {
  78011. matrix[x][z] = y;
  78012. }
  78013. matrix[x][z] = Math.max(y, matrix[x][z]);
  78014. }
  78015. for (var x = 0; x <= arraySize; ++x) {
  78016. if (!matrix[x]) {
  78017. var loc = 1;
  78018. while (!matrix[(x + loc) % arraySize]) {
  78019. loc++;
  78020. }
  78021. matrix[x] = matrix[(x + loc) % arraySize].slice();
  78022. //console.log("missing x", x);
  78023. }
  78024. for (var z = 0; z <= arraySize; ++z) {
  78025. if (!matrix[x][z]) {
  78026. var loc = 1;
  78027. var newValue;
  78028. while (newValue === undefined) {
  78029. newValue = matrix[x][(z + loc++) % arraySize];
  78030. }
  78031. matrix[x][z] = newValue;
  78032. }
  78033. }
  78034. }
  78035. var shape = new this.BJSCANNON.Heightfield(matrix, {
  78036. elementSize: elementSize
  78037. });
  78038. //For future reference, needed for body transformation
  78039. shape.minY = minY;
  78040. return shape;
  78041. };
  78042. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  78043. var object = impostor.object;
  78044. //make sure it is updated...
  78045. object.computeWorldMatrix && object.computeWorldMatrix(true);
  78046. // The delta between the mesh position and the mesh bounding box center
  78047. var bInfo = object.getBoundingInfo();
  78048. if (!bInfo)
  78049. return;
  78050. var center = impostor.getObjectCenter();
  78051. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  78052. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  78053. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  78054. this._tmpPosition.copyFrom(center);
  78055. var quaternion = object.rotationQuaternion;
  78056. if (!quaternion) {
  78057. return;
  78058. }
  78059. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  78060. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  78061. //-90 DEG in X, precalculated
  78062. quaternion = quaternion.multiply(this._minus90X);
  78063. //Invert! (Precalculated, 90 deg in X)
  78064. //No need to clone. this will never change.
  78065. impostor.setDeltaRotation(this._plus90X);
  78066. }
  78067. //If it is a heightfield, if should be centered.
  78068. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  78069. var mesh = object;
  78070. var boundingInfo = mesh.getBoundingInfo();
  78071. //calculate the correct body position:
  78072. var rotationQuaternion = mesh.rotationQuaternion;
  78073. mesh.rotationQuaternion = this._tmpUnityRotation;
  78074. mesh.computeWorldMatrix(true);
  78075. //get original center with no rotation
  78076. var c = center.clone();
  78077. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  78078. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  78079. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  78080. mesh.setPreTransformMatrix(p);
  78081. mesh.computeWorldMatrix(true);
  78082. //calculate the translation
  78083. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  78084. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  78085. //add it inverted to the delta
  78086. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  78087. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  78088. //rotation is back
  78089. mesh.rotationQuaternion = rotationQuaternion;
  78090. mesh.setPreTransformMatrix(oldPivot);
  78091. mesh.computeWorldMatrix(true);
  78092. }
  78093. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  78094. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  78095. //this._tmpPosition.copyFrom(object.position);
  78096. }
  78097. impostor.setDeltaPosition(this._tmpDeltaPosition);
  78098. //Now update the impostor object
  78099. impostor.physicsBody.position.copy(this._tmpPosition);
  78100. impostor.physicsBody.quaternion.copy(quaternion);
  78101. };
  78102. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  78103. impostor.object.position.copyFrom(impostor.physicsBody.position);
  78104. if (impostor.object.rotationQuaternion) {
  78105. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  78106. }
  78107. };
  78108. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  78109. impostor.physicsBody.position.copy(newPosition);
  78110. impostor.physicsBody.quaternion.copy(newRotation);
  78111. };
  78112. CannonJSPlugin.prototype.isSupported = function () {
  78113. return this.BJSCANNON !== undefined;
  78114. };
  78115. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  78116. impostor.physicsBody.velocity.copy(velocity);
  78117. };
  78118. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  78119. impostor.physicsBody.angularVelocity.copy(velocity);
  78120. };
  78121. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  78122. var v = impostor.physicsBody.velocity;
  78123. if (!v) {
  78124. return null;
  78125. }
  78126. return new BABYLON.Vector3(v.x, v.y, v.z);
  78127. };
  78128. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  78129. var v = impostor.physicsBody.angularVelocity;
  78130. if (!v) {
  78131. return null;
  78132. }
  78133. return new BABYLON.Vector3(v.x, v.y, v.z);
  78134. };
  78135. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  78136. impostor.physicsBody.mass = mass;
  78137. impostor.physicsBody.updateMassProperties();
  78138. };
  78139. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  78140. return impostor.physicsBody.mass;
  78141. };
  78142. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  78143. return impostor.physicsBody.material.friction;
  78144. };
  78145. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  78146. impostor.physicsBody.material.friction = friction;
  78147. };
  78148. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  78149. return impostor.physicsBody.material.restitution;
  78150. };
  78151. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  78152. impostor.physicsBody.material.restitution = restitution;
  78153. };
  78154. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  78155. impostor.physicsBody.sleep();
  78156. };
  78157. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  78158. impostor.physicsBody.wakeUp();
  78159. };
  78160. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  78161. joint.physicsJoint.distance = maxDistance;
  78162. };
  78163. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78164. // if (!motorIndex) {
  78165. // joint.physicsJoint.enableMotor();
  78166. // }
  78167. // }
  78168. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78169. // if (!motorIndex) {
  78170. // joint.physicsJoint.disableMotor();
  78171. // }
  78172. // }
  78173. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  78174. if (!motorIndex) {
  78175. joint.physicsJoint.enableMotor();
  78176. joint.physicsJoint.setMotorSpeed(speed);
  78177. if (maxForce) {
  78178. this.setLimit(joint, maxForce);
  78179. }
  78180. }
  78181. };
  78182. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  78183. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  78184. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  78185. };
  78186. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  78187. var body = impostor.physicsBody;
  78188. mesh.position.x = body.position.x;
  78189. mesh.position.y = body.position.y;
  78190. mesh.position.z = body.position.z;
  78191. if (mesh.rotationQuaternion) {
  78192. mesh.rotationQuaternion.x = body.quaternion.x;
  78193. mesh.rotationQuaternion.y = body.quaternion.y;
  78194. mesh.rotationQuaternion.z = body.quaternion.z;
  78195. mesh.rotationQuaternion.w = body.quaternion.w;
  78196. }
  78197. };
  78198. CannonJSPlugin.prototype.getRadius = function (impostor) {
  78199. var shape = impostor.physicsBody.shapes[0];
  78200. return shape.boundingSphereRadius;
  78201. };
  78202. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  78203. var shape = impostor.physicsBody.shapes[0];
  78204. result.x = shape.halfExtents.x * 2;
  78205. result.y = shape.halfExtents.y * 2;
  78206. result.z = shape.halfExtents.z * 2;
  78207. };
  78208. CannonJSPlugin.prototype.dispose = function () {
  78209. };
  78210. CannonJSPlugin.prototype._extendNamespace = function () {
  78211. //this will force cannon to execute at least one step when using interpolation
  78212. var step_tmp1 = new this.BJSCANNON.Vec3();
  78213. var Engine = this.BJSCANNON;
  78214. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  78215. maxSubSteps = maxSubSteps || 10;
  78216. timeSinceLastCalled = timeSinceLastCalled || 0;
  78217. if (timeSinceLastCalled === 0) {
  78218. this.internalStep(dt);
  78219. this.time += dt;
  78220. }
  78221. else {
  78222. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  78223. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  78224. var t0 = performance.now();
  78225. for (var i = 0; i !== internalSteps; i++) {
  78226. this.internalStep(dt);
  78227. if (performance.now() - t0 > dt * 1000) {
  78228. break;
  78229. }
  78230. }
  78231. this.time += timeSinceLastCalled;
  78232. var h = this.time % dt;
  78233. var h_div_dt = h / dt;
  78234. var interpvelo = step_tmp1;
  78235. var bodies = this.bodies;
  78236. for (var j = 0; j !== bodies.length; j++) {
  78237. var b = bodies[j];
  78238. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  78239. b.position.vsub(b.previousPosition, interpvelo);
  78240. interpvelo.scale(h_div_dt, interpvelo);
  78241. b.position.vadd(interpvelo, b.interpolatedPosition);
  78242. }
  78243. else {
  78244. b.interpolatedPosition.copy(b.position);
  78245. b.interpolatedQuaternion.copy(b.quaternion);
  78246. }
  78247. }
  78248. }
  78249. };
  78250. };
  78251. return CannonJSPlugin;
  78252. }());
  78253. BABYLON.CannonJSPlugin = CannonJSPlugin;
  78254. })(BABYLON || (BABYLON = {}));
  78255. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  78256. var BABYLON;
  78257. (function (BABYLON) {
  78258. var OimoJSPlugin = /** @class */ (function () {
  78259. function OimoJSPlugin(iterations) {
  78260. this.name = "OimoJSPlugin";
  78261. this._tmpImpostorsArray = [];
  78262. this._tmpPositionVector = BABYLON.Vector3.Zero();
  78263. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : ( true ? __webpack_require__(18) : undefined);
  78264. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  78265. this.world.worldscale(1);
  78266. this.world.clear();
  78267. //making sure no stats are calculated
  78268. this.world.isNoStat = true;
  78269. }
  78270. OimoJSPlugin.prototype.setGravity = function (gravity) {
  78271. this.world.gravity.copy(gravity);
  78272. };
  78273. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  78274. this.world.timeStep = timeStep;
  78275. };
  78276. OimoJSPlugin.prototype.getTimeStep = function () {
  78277. return this.world.timeStep;
  78278. };
  78279. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  78280. var _this = this;
  78281. impostors.forEach(function (impostor) {
  78282. impostor.beforeStep();
  78283. });
  78284. this.world.step();
  78285. impostors.forEach(function (impostor) {
  78286. impostor.afterStep();
  78287. //update the ordered impostors array
  78288. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  78289. });
  78290. //check for collisions
  78291. var contact = this.world.contacts;
  78292. while (contact !== null) {
  78293. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  78294. contact = contact.next;
  78295. continue;
  78296. }
  78297. //is this body colliding with any other? get the impostor
  78298. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  78299. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  78300. if (!mainImpostor || !collidingImpostor) {
  78301. contact = contact.next;
  78302. continue;
  78303. }
  78304. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  78305. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  78306. contact = contact.next;
  78307. }
  78308. };
  78309. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78310. var mass = impostor.physicsBody.massInfo.mass;
  78311. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  78312. };
  78313. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78314. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  78315. this.applyImpulse(impostor, force, contactPoint);
  78316. };
  78317. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78318. var _this = this;
  78319. //parent-child relationship. Does this impostor has a parent impostor?
  78320. if (impostor.parent) {
  78321. if (impostor.physicsBody) {
  78322. this.removePhysicsBody(impostor);
  78323. //TODO is that needed?
  78324. impostor.forceUpdate();
  78325. }
  78326. return;
  78327. }
  78328. if (impostor.isBodyInitRequired()) {
  78329. var bodyConfig = {
  78330. name: impostor.uniqueId,
  78331. //Oimo must have mass, also for static objects.
  78332. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  78333. size: [],
  78334. type: [],
  78335. pos: [],
  78336. rot: [],
  78337. move: impostor.getParam("mass") !== 0,
  78338. //Supporting older versions of Oimo
  78339. world: this.world
  78340. };
  78341. var impostors = [impostor];
  78342. var addToArray = function (parent) {
  78343. if (!parent.getChildMeshes)
  78344. return;
  78345. parent.getChildMeshes().forEach(function (m) {
  78346. if (m.physicsImpostor) {
  78347. impostors.push(m.physicsImpostor);
  78348. //m.physicsImpostor._init();
  78349. }
  78350. });
  78351. };
  78352. addToArray(impostor.object);
  78353. var checkWithEpsilon_1 = function (value) {
  78354. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  78355. };
  78356. impostors.forEach(function (i) {
  78357. if (!impostor.object.rotationQuaternion) {
  78358. return;
  78359. }
  78360. //get the correct bounding box
  78361. var oldQuaternion = i.object.rotationQuaternion;
  78362. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  78363. x: impostor.object.rotationQuaternion.x,
  78364. y: impostor.object.rotationQuaternion.y,
  78365. z: impostor.object.rotationQuaternion.z,
  78366. s: impostor.object.rotationQuaternion.w
  78367. });
  78368. var extendSize = i.getObjectExtendSize();
  78369. if (i === impostor) {
  78370. var center = impostor.getObjectCenter();
  78371. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  78372. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  78373. //Can also use Array.prototype.push.apply
  78374. bodyConfig.pos.push(center.x);
  78375. bodyConfig.pos.push(center.y);
  78376. bodyConfig.pos.push(center.z);
  78377. //tmp solution
  78378. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  78379. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  78380. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  78381. }
  78382. else {
  78383. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  78384. bodyConfig.pos.push(localPosition.x);
  78385. bodyConfig.pos.push(localPosition.y);
  78386. bodyConfig.pos.push(localPosition.z);
  78387. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  78388. bodyConfig.rot.push(0);
  78389. bodyConfig.rot.push(0);
  78390. bodyConfig.rot.push(0);
  78391. }
  78392. // register mesh
  78393. switch (i.type) {
  78394. case BABYLON.PhysicsImpostor.ParticleImpostor:
  78395. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  78396. case BABYLON.PhysicsImpostor.SphereImpostor:
  78397. var radiusX = extendSize.x;
  78398. var radiusY = extendSize.y;
  78399. var radiusZ = extendSize.z;
  78400. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  78401. bodyConfig.type.push('sphere');
  78402. //due to the way oimo works with compounds, add 3 times
  78403. bodyConfig.size.push(size);
  78404. bodyConfig.size.push(size);
  78405. bodyConfig.size.push(size);
  78406. break;
  78407. case BABYLON.PhysicsImpostor.CylinderImpostor:
  78408. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  78409. var sizeY = checkWithEpsilon_1(extendSize.y);
  78410. bodyConfig.type.push('cylinder');
  78411. bodyConfig.size.push(sizeX);
  78412. bodyConfig.size.push(sizeY);
  78413. //due to the way oimo works with compounds, add one more value.
  78414. bodyConfig.size.push(sizeY);
  78415. break;
  78416. case BABYLON.PhysicsImpostor.PlaneImpostor:
  78417. case BABYLON.PhysicsImpostor.BoxImpostor:
  78418. default:
  78419. var sizeX = checkWithEpsilon_1(extendSize.x);
  78420. var sizeY = checkWithEpsilon_1(extendSize.y);
  78421. var sizeZ = checkWithEpsilon_1(extendSize.z);
  78422. bodyConfig.type.push('box');
  78423. bodyConfig.size.push(sizeX);
  78424. bodyConfig.size.push(sizeY);
  78425. bodyConfig.size.push(sizeZ);
  78426. break;
  78427. }
  78428. //actually not needed, but hey...
  78429. i.object.rotationQuaternion = oldQuaternion;
  78430. });
  78431. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  78432. }
  78433. else {
  78434. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  78435. }
  78436. impostor.setDeltaPosition(this._tmpPositionVector);
  78437. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  78438. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  78439. };
  78440. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78441. //impostor.physicsBody.dispose();
  78442. //Same as : (older oimo versions)
  78443. this.world.removeRigidBody(impostor.physicsBody);
  78444. };
  78445. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  78446. var mainBody = impostorJoint.mainImpostor.physicsBody;
  78447. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  78448. if (!mainBody || !connectedBody) {
  78449. return;
  78450. }
  78451. var jointData = impostorJoint.joint.jointData;
  78452. var options = jointData.nativeParams || {};
  78453. var type;
  78454. var nativeJointData = {
  78455. body1: mainBody,
  78456. body2: connectedBody,
  78457. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  78458. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  78459. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  78460. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  78461. min: options.min,
  78462. max: options.max,
  78463. collision: options.collision || jointData.collision,
  78464. spring: options.spring,
  78465. //supporting older version of Oimo
  78466. world: this.world
  78467. };
  78468. switch (impostorJoint.joint.type) {
  78469. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  78470. type = "jointBall";
  78471. break;
  78472. case BABYLON.PhysicsJoint.SpringJoint:
  78473. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  78474. var springData = jointData;
  78475. nativeJointData.min = springData.length || nativeJointData.min;
  78476. //Max should also be set, just make sure it is at least min
  78477. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  78478. case BABYLON.PhysicsJoint.DistanceJoint:
  78479. type = "jointDistance";
  78480. nativeJointData.max = jointData.maxDistance;
  78481. break;
  78482. case BABYLON.PhysicsJoint.PrismaticJoint:
  78483. type = "jointPrisme";
  78484. break;
  78485. case BABYLON.PhysicsJoint.SliderJoint:
  78486. type = "jointSlide";
  78487. break;
  78488. case BABYLON.PhysicsJoint.WheelJoint:
  78489. type = "jointWheel";
  78490. break;
  78491. case BABYLON.PhysicsJoint.HingeJoint:
  78492. default:
  78493. type = "jointHinge";
  78494. break;
  78495. }
  78496. nativeJointData.type = type;
  78497. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  78498. };
  78499. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  78500. //Bug in Oimo prevents us from disposing a joint in the playground
  78501. //joint.joint.physicsJoint.dispose();
  78502. //So we will bruteforce it!
  78503. try {
  78504. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  78505. }
  78506. catch (e) {
  78507. BABYLON.Tools.Warn(e);
  78508. }
  78509. };
  78510. OimoJSPlugin.prototype.isSupported = function () {
  78511. return this.BJSOIMO !== undefined;
  78512. };
  78513. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  78514. if (!impostor.physicsBody.sleeping) {
  78515. //TODO check that
  78516. if (impostor.physicsBody.shapes.next) {
  78517. var parentShape = this._getLastShape(impostor.physicsBody);
  78518. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  78519. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  78520. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  78521. }
  78522. else {
  78523. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  78524. }
  78525. if (impostor.object.rotationQuaternion) {
  78526. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  78527. impostor.object.rotationQuaternion.normalize();
  78528. }
  78529. }
  78530. };
  78531. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  78532. var body = impostor.physicsBody;
  78533. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  78534. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  78535. body.syncShapes();
  78536. body.awake();
  78537. };
  78538. OimoJSPlugin.prototype._getLastShape = function (body) {
  78539. var lastShape = body.shapes;
  78540. while (lastShape.next) {
  78541. lastShape = lastShape.next;
  78542. }
  78543. return lastShape;
  78544. };
  78545. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  78546. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  78547. };
  78548. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  78549. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  78550. };
  78551. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  78552. var v = impostor.physicsBody.linearVelocity;
  78553. if (!v) {
  78554. return null;
  78555. }
  78556. return new BABYLON.Vector3(v.x, v.y, v.z);
  78557. };
  78558. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  78559. var v = impostor.physicsBody.angularVelocity;
  78560. if (!v) {
  78561. return null;
  78562. }
  78563. return new BABYLON.Vector3(v.x, v.y, v.z);
  78564. };
  78565. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  78566. var staticBody = mass === 0;
  78567. //this will actually set the body's density and not its mass.
  78568. //But this is how oimo treats the mass variable.
  78569. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  78570. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  78571. };
  78572. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  78573. return impostor.physicsBody.shapes.density;
  78574. };
  78575. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  78576. return impostor.physicsBody.shapes.friction;
  78577. };
  78578. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  78579. impostor.physicsBody.shapes.friction = friction;
  78580. };
  78581. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  78582. return impostor.physicsBody.shapes.restitution;
  78583. };
  78584. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  78585. impostor.physicsBody.shapes.restitution = restitution;
  78586. };
  78587. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  78588. impostor.physicsBody.sleep();
  78589. };
  78590. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  78591. impostor.physicsBody.awake();
  78592. };
  78593. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  78594. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  78595. if (minDistance !== void 0) {
  78596. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  78597. }
  78598. };
  78599. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  78600. //TODO separate rotational and transational motors.
  78601. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  78602. if (motor) {
  78603. motor.setMotor(speed, maxForce);
  78604. }
  78605. };
  78606. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  78607. //TODO separate rotational and transational motors.
  78608. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  78609. if (motor) {
  78610. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  78611. }
  78612. };
  78613. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  78614. var body = impostor.physicsBody;
  78615. mesh.position.x = body.position.x;
  78616. mesh.position.y = body.position.y;
  78617. mesh.position.z = body.position.z;
  78618. if (mesh.rotationQuaternion) {
  78619. mesh.rotationQuaternion.x = body.orientation.x;
  78620. mesh.rotationQuaternion.y = body.orientation.y;
  78621. mesh.rotationQuaternion.z = body.orientation.z;
  78622. mesh.rotationQuaternion.w = body.orientation.s;
  78623. }
  78624. };
  78625. OimoJSPlugin.prototype.getRadius = function (impostor) {
  78626. return impostor.physicsBody.shapes.radius;
  78627. };
  78628. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  78629. var shape = impostor.physicsBody.shapes;
  78630. result.x = shape.halfWidth * 2;
  78631. result.y = shape.halfHeight * 2;
  78632. result.z = shape.halfDepth * 2;
  78633. };
  78634. OimoJSPlugin.prototype.dispose = function () {
  78635. this.world.clear();
  78636. };
  78637. return OimoJSPlugin;
  78638. }());
  78639. BABYLON.OimoJSPlugin = OimoJSPlugin;
  78640. })(BABYLON || (BABYLON = {}));
  78641. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  78642. var BABYLON;
  78643. (function (BABYLON) {
  78644. /*
  78645. * Based on jsTGALoader - Javascript loader for TGA file
  78646. * By Vincent Thibault
  78647. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  78648. */
  78649. var TGATools = /** @class */ (function () {
  78650. function TGATools() {
  78651. }
  78652. TGATools.GetTGAHeader = function (data) {
  78653. var offset = 0;
  78654. var header = {
  78655. id_length: data[offset++],
  78656. colormap_type: data[offset++],
  78657. image_type: data[offset++],
  78658. colormap_index: data[offset++] | data[offset++] << 8,
  78659. colormap_length: data[offset++] | data[offset++] << 8,
  78660. colormap_size: data[offset++],
  78661. origin: [
  78662. data[offset++] | data[offset++] << 8,
  78663. data[offset++] | data[offset++] << 8
  78664. ],
  78665. width: data[offset++] | data[offset++] << 8,
  78666. height: data[offset++] | data[offset++] << 8,
  78667. pixel_size: data[offset++],
  78668. flags: data[offset++]
  78669. };
  78670. return header;
  78671. };
  78672. TGATools.UploadContent = function (gl, data) {
  78673. // Not enough data to contain header ?
  78674. if (data.length < 19) {
  78675. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  78676. return;
  78677. }
  78678. // Read Header
  78679. var offset = 18;
  78680. var header = TGATools.GetTGAHeader(data);
  78681. // Assume it's a valid Targa file.
  78682. if (header.id_length + offset > data.length) {
  78683. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  78684. return;
  78685. }
  78686. // Skip not needed data
  78687. offset += header.id_length;
  78688. var use_rle = false;
  78689. var use_pal = false;
  78690. var use_grey = false;
  78691. // Get some informations.
  78692. switch (header.image_type) {
  78693. case TGATools._TYPE_RLE_INDEXED:
  78694. use_rle = true;
  78695. case TGATools._TYPE_INDEXED:
  78696. use_pal = true;
  78697. break;
  78698. case TGATools._TYPE_RLE_RGB:
  78699. use_rle = true;
  78700. case TGATools._TYPE_RGB:
  78701. // use_rgb = true;
  78702. break;
  78703. case TGATools._TYPE_RLE_GREY:
  78704. use_rle = true;
  78705. case TGATools._TYPE_GREY:
  78706. use_grey = true;
  78707. break;
  78708. }
  78709. var pixel_data;
  78710. // var numAlphaBits = header.flags & 0xf;
  78711. var pixel_size = header.pixel_size >> 3;
  78712. var pixel_total = header.width * header.height * pixel_size;
  78713. // Read palettes
  78714. var palettes;
  78715. if (use_pal) {
  78716. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  78717. }
  78718. // Read LRE
  78719. if (use_rle) {
  78720. pixel_data = new Uint8Array(pixel_total);
  78721. var c, count, i;
  78722. var localOffset = 0;
  78723. var pixels = new Uint8Array(pixel_size);
  78724. while (offset < pixel_total && localOffset < pixel_total) {
  78725. c = data[offset++];
  78726. count = (c & 0x7f) + 1;
  78727. // RLE pixels
  78728. if (c & 0x80) {
  78729. // Bind pixel tmp array
  78730. for (i = 0; i < pixel_size; ++i) {
  78731. pixels[i] = data[offset++];
  78732. }
  78733. // Copy pixel array
  78734. for (i = 0; i < count; ++i) {
  78735. pixel_data.set(pixels, localOffset + i * pixel_size);
  78736. }
  78737. localOffset += pixel_size * count;
  78738. }
  78739. else {
  78740. count *= pixel_size;
  78741. for (i = 0; i < count; ++i) {
  78742. pixel_data[localOffset + i] = data[offset++];
  78743. }
  78744. localOffset += count;
  78745. }
  78746. }
  78747. }
  78748. else {
  78749. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  78750. }
  78751. // Load to texture
  78752. var x_start, y_start, x_step, y_step, y_end, x_end;
  78753. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  78754. default:
  78755. case TGATools._ORIGIN_UL:
  78756. x_start = 0;
  78757. x_step = 1;
  78758. x_end = header.width;
  78759. y_start = 0;
  78760. y_step = 1;
  78761. y_end = header.height;
  78762. break;
  78763. case TGATools._ORIGIN_BL:
  78764. x_start = 0;
  78765. x_step = 1;
  78766. x_end = header.width;
  78767. y_start = header.height - 1;
  78768. y_step = -1;
  78769. y_end = -1;
  78770. break;
  78771. case TGATools._ORIGIN_UR:
  78772. x_start = header.width - 1;
  78773. x_step = -1;
  78774. x_end = -1;
  78775. y_start = 0;
  78776. y_step = 1;
  78777. y_end = header.height;
  78778. break;
  78779. case TGATools._ORIGIN_BR:
  78780. x_start = header.width - 1;
  78781. x_step = -1;
  78782. x_end = -1;
  78783. y_start = header.height - 1;
  78784. y_step = -1;
  78785. y_end = -1;
  78786. break;
  78787. }
  78788. // Load the specify method
  78789. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  78790. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  78791. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  78792. };
  78793. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78794. var image = pixel_data, colormap = palettes;
  78795. var width = header.width, height = header.height;
  78796. var color, i = 0, x, y;
  78797. var imageData = new Uint8Array(width * height * 4);
  78798. for (y = y_start; y !== y_end; y += y_step) {
  78799. for (x = x_start; x !== x_end; x += x_step, i++) {
  78800. color = image[i];
  78801. imageData[(x + width * y) * 4 + 3] = 255;
  78802. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  78803. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  78804. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  78805. }
  78806. }
  78807. return imageData;
  78808. };
  78809. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78810. var image = pixel_data;
  78811. var width = header.width, height = header.height;
  78812. var color, i = 0, x, y;
  78813. var imageData = new Uint8Array(width * height * 4);
  78814. for (y = y_start; y !== y_end; y += y_step) {
  78815. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  78816. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  78817. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  78818. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  78819. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  78820. imageData[(x + width * y) * 4 + 0] = r;
  78821. imageData[(x + width * y) * 4 + 1] = g;
  78822. imageData[(x + width * y) * 4 + 2] = b;
  78823. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  78824. }
  78825. }
  78826. return imageData;
  78827. };
  78828. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78829. var image = pixel_data;
  78830. var width = header.width, height = header.height;
  78831. var i = 0, x, y;
  78832. var imageData = new Uint8Array(width * height * 4);
  78833. for (y = y_start; y !== y_end; y += y_step) {
  78834. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  78835. imageData[(x + width * y) * 4 + 3] = 255;
  78836. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78837. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  78838. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  78839. }
  78840. }
  78841. return imageData;
  78842. };
  78843. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78844. var image = pixel_data;
  78845. var width = header.width, height = header.height;
  78846. var i = 0, x, y;
  78847. var imageData = new Uint8Array(width * height * 4);
  78848. for (y = y_start; y !== y_end; y += y_step) {
  78849. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  78850. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78851. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  78852. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  78853. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  78854. }
  78855. }
  78856. return imageData;
  78857. };
  78858. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78859. var image = pixel_data;
  78860. var width = header.width, height = header.height;
  78861. var color, i = 0, x, y;
  78862. var imageData = new Uint8Array(width * height * 4);
  78863. for (y = y_start; y !== y_end; y += y_step) {
  78864. for (x = x_start; x !== x_end; x += x_step, i++) {
  78865. color = image[i];
  78866. imageData[(x + width * y) * 4 + 0] = color;
  78867. imageData[(x + width * y) * 4 + 1] = color;
  78868. imageData[(x + width * y) * 4 + 2] = color;
  78869. imageData[(x + width * y) * 4 + 3] = 255;
  78870. }
  78871. }
  78872. return imageData;
  78873. };
  78874. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78875. var image = pixel_data;
  78876. var width = header.width, height = header.height;
  78877. var i = 0, x, y;
  78878. var imageData = new Uint8Array(width * height * 4);
  78879. for (y = y_start; y !== y_end; y += y_step) {
  78880. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  78881. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  78882. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  78883. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78884. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  78885. }
  78886. }
  78887. return imageData;
  78888. };
  78889. //private static _TYPE_NO_DATA = 0;
  78890. TGATools._TYPE_INDEXED = 1;
  78891. TGATools._TYPE_RGB = 2;
  78892. TGATools._TYPE_GREY = 3;
  78893. TGATools._TYPE_RLE_INDEXED = 9;
  78894. TGATools._TYPE_RLE_RGB = 10;
  78895. TGATools._TYPE_RLE_GREY = 11;
  78896. TGATools._ORIGIN_MASK = 0x30;
  78897. TGATools._ORIGIN_SHIFT = 0x04;
  78898. TGATools._ORIGIN_BL = 0x00;
  78899. TGATools._ORIGIN_BR = 0x01;
  78900. TGATools._ORIGIN_UL = 0x02;
  78901. TGATools._ORIGIN_UR = 0x03;
  78902. return TGATools;
  78903. }());
  78904. BABYLON.TGATools = TGATools;
  78905. })(BABYLON || (BABYLON = {}));
  78906. //# sourceMappingURL=babylon.tga.js.map
  78907. var BABYLON;
  78908. (function (BABYLON) {
  78909. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  78910. // All values and structures referenced from:
  78911. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  78912. var DDS_MAGIC = 0x20534444;
  78913. var
  78914. //DDSD_CAPS = 0x1,
  78915. //DDSD_HEIGHT = 0x2,
  78916. //DDSD_WIDTH = 0x4,
  78917. //DDSD_PITCH = 0x8,
  78918. //DDSD_PIXELFORMAT = 0x1000,
  78919. DDSD_MIPMAPCOUNT = 0x20000;
  78920. //DDSD_LINEARSIZE = 0x80000,
  78921. //DDSD_DEPTH = 0x800000;
  78922. // var DDSCAPS_COMPLEX = 0x8,
  78923. // DDSCAPS_MIPMAP = 0x400000,
  78924. // DDSCAPS_TEXTURE = 0x1000;
  78925. var DDSCAPS2_CUBEMAP = 0x200;
  78926. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  78927. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  78928. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  78929. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  78930. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  78931. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  78932. // DDSCAPS2_VOLUME = 0x200000;
  78933. var
  78934. //DDPF_ALPHAPIXELS = 0x1,
  78935. //DDPF_ALPHA = 0x2,
  78936. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  78937. //DDPF_YUV = 0x200,
  78938. DDPF_LUMINANCE = 0x20000;
  78939. function FourCCToInt32(value) {
  78940. return value.charCodeAt(0) +
  78941. (value.charCodeAt(1) << 8) +
  78942. (value.charCodeAt(2) << 16) +
  78943. (value.charCodeAt(3) << 24);
  78944. }
  78945. function Int32ToFourCC(value) {
  78946. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  78947. }
  78948. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  78949. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  78950. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  78951. var FOURCC_DX10 = FourCCToInt32("DX10");
  78952. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  78953. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  78954. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  78955. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  78956. var headerLengthInt = 31; // The header length in 32 bit ints
  78957. // Offsets into the header array
  78958. var off_magic = 0;
  78959. var off_size = 1;
  78960. var off_flags = 2;
  78961. var off_height = 3;
  78962. var off_width = 4;
  78963. var off_mipmapCount = 7;
  78964. var off_pfFlags = 20;
  78965. var off_pfFourCC = 21;
  78966. var off_RGBbpp = 22;
  78967. var off_RMask = 23;
  78968. var off_GMask = 24;
  78969. var off_BMask = 25;
  78970. var off_AMask = 26;
  78971. // var off_caps1 = 27;
  78972. var off_caps2 = 28;
  78973. // var off_caps3 = 29;
  78974. // var off_caps4 = 30;
  78975. var off_dxgiFormat = 32;
  78976. ;
  78977. var DDSTools = /** @class */ (function () {
  78978. function DDSTools() {
  78979. }
  78980. DDSTools.GetDDSInfo = function (arrayBuffer) {
  78981. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  78982. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  78983. var mipmapCount = 1;
  78984. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  78985. mipmapCount = Math.max(1, header[off_mipmapCount]);
  78986. }
  78987. var fourCC = header[off_pfFourCC];
  78988. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  78989. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78990. switch (fourCC) {
  78991. case FOURCC_D3DFMT_R16G16B16A16F:
  78992. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78993. break;
  78994. case FOURCC_D3DFMT_R32G32B32A32F:
  78995. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78996. break;
  78997. case FOURCC_DX10:
  78998. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  78999. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79000. break;
  79001. }
  79002. }
  79003. return {
  79004. width: header[off_width],
  79005. height: header[off_height],
  79006. mipmapCount: mipmapCount,
  79007. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  79008. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  79009. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  79010. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  79011. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  79012. dxgiFormat: dxgiFormat,
  79013. textureType: textureType
  79014. };
  79015. };
  79016. DDSTools._ToHalfFloat = function (value) {
  79017. if (!DDSTools._FloatView) {
  79018. DDSTools._FloatView = new Float32Array(1);
  79019. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  79020. }
  79021. DDSTools._FloatView[0] = value;
  79022. var x = DDSTools._Int32View[0];
  79023. var bits = (x >> 16) & 0x8000; /* Get the sign */
  79024. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  79025. var e = (x >> 23) & 0xff; /* Using int is faster here */
  79026. /* If zero, or denormal, or exponent underflows too much for a denormal
  79027. * half, return signed zero. */
  79028. if (e < 103) {
  79029. return bits;
  79030. }
  79031. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  79032. if (e > 142) {
  79033. bits |= 0x7c00;
  79034. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  79035. * not Inf, so make sure we set one mantissa bit too. */
  79036. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  79037. return bits;
  79038. }
  79039. /* If exponent underflows but not too much, return a denormal */
  79040. if (e < 113) {
  79041. m |= 0x0800;
  79042. /* Extra rounding may overflow and set mantissa to 0 and exponent
  79043. * to 1, which is OK. */
  79044. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  79045. return bits;
  79046. }
  79047. bits |= ((e - 112) << 10) | (m >> 1);
  79048. bits += m & 1;
  79049. return bits;
  79050. };
  79051. DDSTools._FromHalfFloat = function (value) {
  79052. var s = (value & 0x8000) >> 15;
  79053. var e = (value & 0x7C00) >> 10;
  79054. var f = value & 0x03FF;
  79055. if (e === 0) {
  79056. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  79057. }
  79058. else if (e == 0x1F) {
  79059. return f ? NaN : ((s ? -1 : 1) * Infinity);
  79060. }
  79061. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  79062. };
  79063. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79064. var destArray = new Float32Array(dataLength);
  79065. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79066. var index = 0;
  79067. for (var y = 0; y < height; y++) {
  79068. for (var x = 0; x < width; x++) {
  79069. var srcPos = (x + y * width) * 4;
  79070. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  79071. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  79072. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  79073. if (DDSTools.StoreLODInAlphaChannel) {
  79074. destArray[index + 3] = lod;
  79075. }
  79076. else {
  79077. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  79078. }
  79079. index += 4;
  79080. }
  79081. }
  79082. return destArray;
  79083. };
  79084. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79085. if (DDSTools.StoreLODInAlphaChannel) {
  79086. var destArray = new Uint16Array(dataLength);
  79087. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79088. var index = 0;
  79089. for (var y = 0; y < height; y++) {
  79090. for (var x = 0; x < width; x++) {
  79091. var srcPos = (x + y * width) * 4;
  79092. destArray[index] = srcData[srcPos];
  79093. destArray[index + 1] = srcData[srcPos + 1];
  79094. destArray[index + 2] = srcData[srcPos + 2];
  79095. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  79096. index += 4;
  79097. }
  79098. }
  79099. return destArray;
  79100. }
  79101. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  79102. };
  79103. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79104. if (DDSTools.StoreLODInAlphaChannel) {
  79105. var destArray = new Float32Array(dataLength);
  79106. var srcData = new Float32Array(arrayBuffer, dataOffset);
  79107. var index = 0;
  79108. for (var y = 0; y < height; y++) {
  79109. for (var x = 0; x < width; x++) {
  79110. var srcPos = (x + y * width) * 4;
  79111. destArray[index] = srcData[srcPos];
  79112. destArray[index + 1] = srcData[srcPos + 1];
  79113. destArray[index + 2] = srcData[srcPos + 2];
  79114. destArray[index + 3] = lod;
  79115. index += 4;
  79116. }
  79117. }
  79118. return destArray;
  79119. }
  79120. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  79121. };
  79122. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79123. var destArray = new Uint8Array(dataLength);
  79124. var srcData = new Float32Array(arrayBuffer, dataOffset);
  79125. var index = 0;
  79126. for (var y = 0; y < height; y++) {
  79127. for (var x = 0; x < width; x++) {
  79128. var srcPos = (x + y * width) * 4;
  79129. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  79130. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  79131. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  79132. if (DDSTools.StoreLODInAlphaChannel) {
  79133. destArray[index + 3] = lod;
  79134. }
  79135. else {
  79136. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  79137. }
  79138. index += 4;
  79139. }
  79140. }
  79141. return destArray;
  79142. };
  79143. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79144. var destArray = new Uint8Array(dataLength);
  79145. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79146. var index = 0;
  79147. for (var y = 0; y < height; y++) {
  79148. for (var x = 0; x < width; x++) {
  79149. var srcPos = (x + y * width) * 4;
  79150. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  79151. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  79152. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  79153. if (DDSTools.StoreLODInAlphaChannel) {
  79154. destArray[index + 3] = lod;
  79155. }
  79156. else {
  79157. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  79158. }
  79159. index += 4;
  79160. }
  79161. }
  79162. return destArray;
  79163. };
  79164. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  79165. var byteArray = new Uint8Array(dataLength);
  79166. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79167. var index = 0;
  79168. for (var y = 0; y < height; y++) {
  79169. for (var x = 0; x < width; x++) {
  79170. var srcPos = (x + y * width) * 4;
  79171. byteArray[index] = srcData[srcPos + rOffset];
  79172. byteArray[index + 1] = srcData[srcPos + gOffset];
  79173. byteArray[index + 2] = srcData[srcPos + bOffset];
  79174. byteArray[index + 3] = srcData[srcPos + aOffset];
  79175. index += 4;
  79176. }
  79177. }
  79178. return byteArray;
  79179. };
  79180. DDSTools._ExtractLongWordOrder = function (value) {
  79181. if (value === 0 || value === 255 || value === -16777216) {
  79182. return 0;
  79183. }
  79184. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  79185. };
  79186. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  79187. var byteArray = new Uint8Array(dataLength);
  79188. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79189. var index = 0;
  79190. for (var y = 0; y < height; y++) {
  79191. for (var x = 0; x < width; x++) {
  79192. var srcPos = (x + y * width) * 3;
  79193. byteArray[index] = srcData[srcPos + rOffset];
  79194. byteArray[index + 1] = srcData[srcPos + gOffset];
  79195. byteArray[index + 2] = srcData[srcPos + bOffset];
  79196. index += 3;
  79197. }
  79198. }
  79199. return byteArray;
  79200. };
  79201. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  79202. var byteArray = new Uint8Array(dataLength);
  79203. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79204. var index = 0;
  79205. for (var y = 0; y < height; y++) {
  79206. for (var x = 0; x < width; x++) {
  79207. var srcPos = (x + y * width);
  79208. byteArray[index] = srcData[srcPos];
  79209. index++;
  79210. }
  79211. }
  79212. return byteArray;
  79213. };
  79214. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  79215. if (lodIndex === void 0) { lodIndex = -1; }
  79216. var ext = engine.getCaps().s3tc;
  79217. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79218. var fourCC, width, height, dataLength = 0, dataOffset;
  79219. var byteArray, mipmapCount, mip;
  79220. var internalFormat = 0;
  79221. var format = 0;
  79222. var blockBytes = 1;
  79223. if (header[off_magic] !== DDS_MAGIC) {
  79224. BABYLON.Tools.Error("Invalid magic number in DDS header");
  79225. return;
  79226. }
  79227. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  79228. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  79229. return;
  79230. }
  79231. if (info.isCompressed && !ext) {
  79232. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  79233. return;
  79234. }
  79235. var bpp = header[off_RGBbpp];
  79236. dataOffset = header[off_size] + 4;
  79237. var computeFormats = false;
  79238. if (info.isFourCC) {
  79239. fourCC = header[off_pfFourCC];
  79240. switch (fourCC) {
  79241. case FOURCC_DXT1:
  79242. blockBytes = 8;
  79243. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  79244. break;
  79245. case FOURCC_DXT3:
  79246. blockBytes = 16;
  79247. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  79248. break;
  79249. case FOURCC_DXT5:
  79250. blockBytes = 16;
  79251. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  79252. break;
  79253. case FOURCC_D3DFMT_R16G16B16A16F:
  79254. computeFormats = true;
  79255. break;
  79256. case FOURCC_D3DFMT_R32G32B32A32F:
  79257. computeFormats = true;
  79258. break;
  79259. case FOURCC_DX10:
  79260. // There is an additionnal header so dataOffset need to be changed
  79261. dataOffset += 5 * 4; // 5 uints
  79262. var supported = false;
  79263. switch (info.dxgiFormat) {
  79264. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  79265. computeFormats = true;
  79266. supported = true;
  79267. break;
  79268. case DXGI_FORMAT_B8G8R8X8_UNORM:
  79269. info.isRGB = true;
  79270. info.isFourCC = false;
  79271. bpp = 32;
  79272. supported = true;
  79273. break;
  79274. }
  79275. if (supported) {
  79276. break;
  79277. }
  79278. default:
  79279. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  79280. return;
  79281. }
  79282. }
  79283. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  79284. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  79285. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  79286. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  79287. if (computeFormats) {
  79288. format = engine._getWebGLTextureType(info.textureType);
  79289. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79290. }
  79291. mipmapCount = 1;
  79292. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  79293. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79294. }
  79295. for (var face = 0; face < faces; face++) {
  79296. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  79297. width = header[off_width];
  79298. height = header[off_height];
  79299. for (mip = 0; mip < mipmapCount; ++mip) {
  79300. if (lodIndex === -1 || lodIndex === mip) {
  79301. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  79302. var i = (lodIndex === -1) ? mip : 0;
  79303. if (!info.isCompressed && info.isFourCC) {
  79304. dataLength = width * height * 4;
  79305. var floatArray = null;
  79306. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  79307. if (bpp === 128) {
  79308. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79309. }
  79310. else if (bpp === 64) {
  79311. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79312. }
  79313. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79314. format = engine._getWebGLTextureType(info.textureType);
  79315. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79316. }
  79317. else {
  79318. if (bpp === 128) {
  79319. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79320. }
  79321. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  79322. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79323. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79324. format = engine._getWebGLTextureType(info.textureType);
  79325. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79326. }
  79327. else {
  79328. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79329. }
  79330. }
  79331. if (floatArray) {
  79332. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  79333. }
  79334. }
  79335. else if (info.isRGB) {
  79336. if (bpp === 24) {
  79337. dataLength = width * height * 3;
  79338. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  79339. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  79340. }
  79341. else {
  79342. dataLength = width * height * 4;
  79343. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  79344. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  79345. }
  79346. }
  79347. else if (info.isLuminance) {
  79348. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  79349. var unpaddedRowSize = width;
  79350. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  79351. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  79352. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  79353. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  79354. }
  79355. else {
  79356. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  79357. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  79358. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  79359. }
  79360. }
  79361. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  79362. width *= 0.5;
  79363. height *= 0.5;
  79364. width = Math.max(1.0, width);
  79365. height = Math.max(1.0, height);
  79366. }
  79367. if (currentFace !== undefined) {
  79368. // Loading a single face
  79369. break;
  79370. }
  79371. }
  79372. };
  79373. DDSTools.StoreLODInAlphaChannel = false;
  79374. return DDSTools;
  79375. }());
  79376. BABYLON.DDSTools = DDSTools;
  79377. })(BABYLON || (BABYLON = {}));
  79378. //# sourceMappingURL=babylon.dds.js.map
  79379. var BABYLON;
  79380. (function (BABYLON) {
  79381. /**
  79382. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  79383. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  79384. */
  79385. var KhronosTextureContainer = /** @class */ (function () {
  79386. /**
  79387. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  79388. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  79389. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  79390. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  79391. */
  79392. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  79393. this.arrayBuffer = arrayBuffer;
  79394. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  79395. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  79396. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  79397. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  79398. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  79399. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  79400. BABYLON.Tools.Error("texture missing KTX identifier");
  79401. return;
  79402. }
  79403. // load the reset of the header in native 32 bit int
  79404. var header = new Int32Array(this.arrayBuffer, 12, 13);
  79405. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  79406. var oppositeEndianess = header[0] === 0x01020304;
  79407. // read all the header elements in order they exist in the file, without modification (sans endainness)
  79408. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  79409. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  79410. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  79411. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  79412. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  79413. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  79414. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  79415. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  79416. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  79417. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  79418. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  79419. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  79420. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  79421. if (this.glType !== 0) {
  79422. BABYLON.Tools.Error("only compressed formats currently supported");
  79423. return;
  79424. }
  79425. else {
  79426. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  79427. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  79428. }
  79429. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  79430. BABYLON.Tools.Error("only 2D textures currently supported");
  79431. return;
  79432. }
  79433. if (this.numberOfArrayElements !== 0) {
  79434. BABYLON.Tools.Error("texture arrays not currently supported");
  79435. return;
  79436. }
  79437. if (this.numberOfFaces !== facesExpected) {
  79438. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  79439. return;
  79440. }
  79441. // we now have a completely validated file, so could use existence of loadType as success
  79442. // would need to make this more elaborate & adjust checks above to support more than one load type
  79443. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  79444. }
  79445. // not as fast hardware based, but will probably never need to use
  79446. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  79447. return ((val & 0xFF) << 24)
  79448. | ((val & 0xFF00) << 8)
  79449. | ((val >> 8) & 0xFF00)
  79450. | ((val >> 24) & 0xFF);
  79451. };
  79452. /**
  79453. * It is assumed that the texture has already been created & is currently bound
  79454. */
  79455. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  79456. switch (this.loadType) {
  79457. case KhronosTextureContainer.COMPRESSED_2D:
  79458. this._upload2DCompressedLevels(gl, loadMipmaps);
  79459. break;
  79460. case KhronosTextureContainer.TEX_2D:
  79461. case KhronosTextureContainer.COMPRESSED_3D:
  79462. case KhronosTextureContainer.TEX_3D:
  79463. }
  79464. };
  79465. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  79466. // initialize width & height for level 1
  79467. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  79468. var width = this.pixelWidth;
  79469. var height = this.pixelHeight;
  79470. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  79471. for (var level = 0; level < mipmapCount; level++) {
  79472. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  79473. for (var face = 0; face < this.numberOfFaces; face++) {
  79474. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  79475. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  79476. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  79477. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  79478. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  79479. }
  79480. width = Math.max(1.0, width * 0.5);
  79481. height = Math.max(1.0, height * 0.5);
  79482. }
  79483. };
  79484. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  79485. // load types
  79486. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  79487. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  79488. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  79489. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  79490. return KhronosTextureContainer;
  79491. }());
  79492. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  79493. })(BABYLON || (BABYLON = {}));
  79494. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  79495. var BABYLON;
  79496. (function (BABYLON) {
  79497. var Debug = /** @class */ (function () {
  79498. function Debug() {
  79499. }
  79500. Debug.AxesViewer = /** @class */ (function () {
  79501. function AxesViewer(scene, scaleLines) {
  79502. if (scaleLines === void 0) { scaleLines = 1; }
  79503. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79504. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79505. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79506. this.scaleLines = 1;
  79507. this.scaleLines = scaleLines;
  79508. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  79509. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  79510. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  79511. this._xmesh.renderingGroupId = 2;
  79512. this._ymesh.renderingGroupId = 2;
  79513. this._zmesh.renderingGroupId = 2;
  79514. this._xmesh.material.checkReadyOnlyOnce = true;
  79515. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  79516. this._ymesh.material.checkReadyOnlyOnce = true;
  79517. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  79518. this._zmesh.material.checkReadyOnlyOnce = true;
  79519. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  79520. this.scene = scene;
  79521. }
  79522. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  79523. var scaleLines = this.scaleLines;
  79524. if (this._xmesh) {
  79525. this._xmesh.position.copyFrom(position);
  79526. }
  79527. if (this._ymesh) {
  79528. this._ymesh.position.copyFrom(position);
  79529. }
  79530. if (this._zmesh) {
  79531. this._zmesh.position.copyFrom(position);
  79532. }
  79533. var point2 = this._xline[1];
  79534. point2.x = xaxis.x * scaleLines;
  79535. point2.y = xaxis.y * scaleLines;
  79536. point2.z = xaxis.z * scaleLines;
  79537. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  79538. point2 = this._yline[1];
  79539. point2.x = yaxis.x * scaleLines;
  79540. point2.y = yaxis.y * scaleLines;
  79541. point2.z = yaxis.z * scaleLines;
  79542. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  79543. point2 = this._zline[1];
  79544. point2.x = zaxis.x * scaleLines;
  79545. point2.y = zaxis.y * scaleLines;
  79546. point2.z = zaxis.z * scaleLines;
  79547. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  79548. };
  79549. AxesViewer.prototype.dispose = function () {
  79550. if (this._xmesh) {
  79551. this._xmesh.dispose();
  79552. }
  79553. if (this._ymesh) {
  79554. this._ymesh.dispose();
  79555. }
  79556. if (this._zmesh) {
  79557. this._zmesh.dispose();
  79558. }
  79559. this._xmesh = null;
  79560. this._ymesh = null;
  79561. this._zmesh = null;
  79562. this.scene = null;
  79563. };
  79564. return AxesViewer;
  79565. }());
  79566. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  79567. __extends(BoneAxesViewer, _super);
  79568. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  79569. if (scaleLines === void 0) { scaleLines = 1; }
  79570. var _this = _super.call(this, scene, scaleLines) || this;
  79571. _this.pos = BABYLON.Vector3.Zero();
  79572. _this.xaxis = BABYLON.Vector3.Zero();
  79573. _this.yaxis = BABYLON.Vector3.Zero();
  79574. _this.zaxis = BABYLON.Vector3.Zero();
  79575. _this.mesh = mesh;
  79576. _this.bone = bone;
  79577. return _this;
  79578. }
  79579. BoneAxesViewer.prototype.update = function () {
  79580. if (!this.mesh || !this.bone) {
  79581. return;
  79582. }
  79583. var bone = this.bone;
  79584. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  79585. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  79586. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  79587. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  79588. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  79589. };
  79590. BoneAxesViewer.prototype.dispose = function () {
  79591. if (this.mesh) {
  79592. this.mesh = null;
  79593. this.bone = null;
  79594. _super.prototype.dispose.call(this);
  79595. }
  79596. };
  79597. return BoneAxesViewer;
  79598. }(Debug.AxesViewer));
  79599. Debug.PhysicsViewer = /** @class */ (function () {
  79600. function PhysicsViewer(scene) {
  79601. this._impostors = [];
  79602. this._meshes = [];
  79603. this._numMeshes = 0;
  79604. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79605. var physicEngine = this._scene.getPhysicsEngine();
  79606. if (physicEngine) {
  79607. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  79608. }
  79609. }
  79610. PhysicsViewer.prototype._updateDebugMeshes = function () {
  79611. var plugin = this._physicsEnginePlugin;
  79612. for (var i = 0; i < this._numMeshes; i++) {
  79613. var impostor = this._impostors[i];
  79614. if (!impostor) {
  79615. continue;
  79616. }
  79617. if (impostor.isDisposed) {
  79618. this.hideImpostor(this._impostors[i--]);
  79619. }
  79620. else {
  79621. var mesh = this._meshes[i];
  79622. if (mesh && plugin) {
  79623. plugin.syncMeshWithImpostor(mesh, impostor);
  79624. }
  79625. }
  79626. }
  79627. };
  79628. PhysicsViewer.prototype.showImpostor = function (impostor) {
  79629. if (!this._scene) {
  79630. return;
  79631. }
  79632. for (var i = 0; i < this._numMeshes; i++) {
  79633. if (this._impostors[i] == impostor) {
  79634. return;
  79635. }
  79636. }
  79637. var debugMesh = this._getDebugMesh(impostor, this._scene);
  79638. if (debugMesh) {
  79639. this._impostors[this._numMeshes] = impostor;
  79640. this._meshes[this._numMeshes] = debugMesh;
  79641. if (this._numMeshes === 0) {
  79642. this._renderFunction = this._updateDebugMeshes.bind(this);
  79643. this._scene.registerBeforeRender(this._renderFunction);
  79644. }
  79645. this._numMeshes++;
  79646. }
  79647. };
  79648. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  79649. if (!impostor || !this._scene) {
  79650. return;
  79651. }
  79652. var removed = false;
  79653. for (var i = 0; i < this._numMeshes; i++) {
  79654. if (this._impostors[i] == impostor) {
  79655. var mesh = this._meshes[i];
  79656. if (!mesh) {
  79657. continue;
  79658. }
  79659. this._scene.removeMesh(mesh);
  79660. mesh.dispose();
  79661. this._numMeshes--;
  79662. if (this._numMeshes > 0) {
  79663. this._meshes[i] = this._meshes[this._numMeshes];
  79664. this._impostors[i] = this._impostors[this._numMeshes];
  79665. this._meshes[this._numMeshes] = null;
  79666. this._impostors[this._numMeshes] = null;
  79667. }
  79668. else {
  79669. this._meshes[0] = null;
  79670. this._impostors[0] = null;
  79671. }
  79672. removed = true;
  79673. break;
  79674. }
  79675. }
  79676. if (removed && this._numMeshes === 0) {
  79677. this._scene.unregisterBeforeRender(this._renderFunction);
  79678. }
  79679. };
  79680. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  79681. if (!this._debugMaterial) {
  79682. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  79683. this._debugMaterial.wireframe = true;
  79684. }
  79685. return this._debugMaterial;
  79686. };
  79687. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  79688. if (!this._debugBoxMesh) {
  79689. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  79690. this._debugBoxMesh.renderingGroupId = 1;
  79691. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  79692. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  79693. scene.removeMesh(this._debugBoxMesh);
  79694. }
  79695. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  79696. };
  79697. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  79698. if (!this._debugSphereMesh) {
  79699. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  79700. this._debugSphereMesh.renderingGroupId = 1;
  79701. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  79702. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  79703. scene.removeMesh(this._debugSphereMesh);
  79704. }
  79705. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  79706. };
  79707. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  79708. var mesh = null;
  79709. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  79710. mesh = this._getDebugBoxMesh(scene);
  79711. impostor.getBoxSizeToRef(mesh.scaling);
  79712. }
  79713. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  79714. mesh = this._getDebugSphereMesh(scene);
  79715. var radius = impostor.getRadius();
  79716. mesh.scaling.x = radius * 2;
  79717. mesh.scaling.y = radius * 2;
  79718. mesh.scaling.z = radius * 2;
  79719. }
  79720. return mesh;
  79721. };
  79722. PhysicsViewer.prototype.dispose = function () {
  79723. for (var i = 0; i < this._numMeshes; i++) {
  79724. this.hideImpostor(this._impostors[i]);
  79725. }
  79726. if (this._debugBoxMesh) {
  79727. this._debugBoxMesh.dispose();
  79728. }
  79729. if (this._debugSphereMesh) {
  79730. this._debugSphereMesh.dispose();
  79731. }
  79732. if (this._debugMaterial) {
  79733. this._debugMaterial.dispose();
  79734. }
  79735. this._impostors.length = 0;
  79736. this._scene = null;
  79737. this._physicsEnginePlugin = null;
  79738. };
  79739. return PhysicsViewer;
  79740. }());
  79741. Debug.SkeletonViewer = /** @class */ (function () {
  79742. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  79743. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  79744. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  79745. this.skeleton = skeleton;
  79746. this.mesh = mesh;
  79747. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  79748. this.renderingGroupId = renderingGroupId;
  79749. this.color = BABYLON.Color3.White();
  79750. this._debugLines = new Array();
  79751. this._isEnabled = false;
  79752. this._scene = scene;
  79753. this.update();
  79754. this._renderFunction = this.update.bind(this);
  79755. }
  79756. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  79757. get: function () {
  79758. return this._isEnabled;
  79759. },
  79760. set: function (value) {
  79761. if (this._isEnabled === value) {
  79762. return;
  79763. }
  79764. this._isEnabled = value;
  79765. if (value) {
  79766. this._scene.registerBeforeRender(this._renderFunction);
  79767. }
  79768. else {
  79769. this._scene.unregisterBeforeRender(this._renderFunction);
  79770. }
  79771. },
  79772. enumerable: true,
  79773. configurable: true
  79774. });
  79775. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  79776. if (x === void 0) { x = 0; }
  79777. if (y === void 0) { y = 0; }
  79778. if (z === void 0) { z = 0; }
  79779. var tmat = BABYLON.Tmp.Matrix[0];
  79780. var parentBone = bone.getParent();
  79781. tmat.copyFrom(bone.getLocalMatrix());
  79782. if (x !== 0 || y !== 0 || z !== 0) {
  79783. var tmat2 = BABYLON.Tmp.Matrix[1];
  79784. BABYLON.Matrix.IdentityToRef(tmat2);
  79785. tmat2.m[12] = x;
  79786. tmat2.m[13] = y;
  79787. tmat2.m[14] = z;
  79788. tmat2.multiplyToRef(tmat, tmat);
  79789. }
  79790. if (parentBone) {
  79791. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  79792. }
  79793. tmat.multiplyToRef(meshMat, tmat);
  79794. position.x = tmat.m[12];
  79795. position.y = tmat.m[13];
  79796. position.z = tmat.m[14];
  79797. };
  79798. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  79799. var len = bones.length;
  79800. var meshPos = this.mesh.position;
  79801. for (var i = 0; i < len; i++) {
  79802. var bone = bones[i];
  79803. var points = this._debugLines[i];
  79804. if (!points) {
  79805. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79806. this._debugLines[i] = points;
  79807. }
  79808. this._getBonePosition(points[0], bone, meshMat);
  79809. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  79810. points[0].subtractInPlace(meshPos);
  79811. points[1].subtractInPlace(meshPos);
  79812. }
  79813. };
  79814. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  79815. var len = bones.length;
  79816. var boneNum = 0;
  79817. var meshPos = this.mesh.position;
  79818. for (var i = len - 1; i >= 0; i--) {
  79819. var childBone = bones[i];
  79820. var parentBone = childBone.getParent();
  79821. if (!parentBone) {
  79822. continue;
  79823. }
  79824. var points = this._debugLines[boneNum];
  79825. if (!points) {
  79826. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79827. this._debugLines[boneNum] = points;
  79828. }
  79829. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  79830. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  79831. points[0].subtractInPlace(meshPos);
  79832. points[1].subtractInPlace(meshPos);
  79833. boneNum++;
  79834. }
  79835. };
  79836. SkeletonViewer.prototype.update = function () {
  79837. if (this.autoUpdateBonesMatrices) {
  79838. this.skeleton.computeAbsoluteTransforms();
  79839. }
  79840. if (this.skeleton.bones[0].length === undefined) {
  79841. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  79842. }
  79843. else {
  79844. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  79845. }
  79846. if (!this._debugMesh) {
  79847. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  79848. this._debugMesh.renderingGroupId = this.renderingGroupId;
  79849. }
  79850. else {
  79851. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  79852. }
  79853. this._debugMesh.position.copyFrom(this.mesh.position);
  79854. this._debugMesh.color = this.color;
  79855. };
  79856. SkeletonViewer.prototype.dispose = function () {
  79857. if (this._debugMesh) {
  79858. this.isEnabled = false;
  79859. this._debugMesh.dispose();
  79860. this._debugMesh = null;
  79861. }
  79862. };
  79863. return SkeletonViewer;
  79864. }());
  79865. return Debug;
  79866. }());
  79867. BABYLON.Debug = Debug;
  79868. })(BABYLON || (BABYLON = {}));
  79869. //# sourceMappingURL=babylon.debugModules.js.map
  79870. var BABYLON;
  79871. (function (BABYLON) {
  79872. var RayHelper = /** @class */ (function () {
  79873. function RayHelper(ray) {
  79874. this.ray = ray;
  79875. }
  79876. RayHelper.CreateAndShow = function (ray, scene, color) {
  79877. var helper = new RayHelper(ray);
  79878. helper.show(scene, color);
  79879. return helper;
  79880. };
  79881. RayHelper.prototype.show = function (scene, color) {
  79882. if (!this._renderFunction && this.ray) {
  79883. var ray = this.ray;
  79884. this._renderFunction = this._render.bind(this);
  79885. this._scene = scene;
  79886. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  79887. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  79888. if (this._renderFunction) {
  79889. this._scene.registerBeforeRender(this._renderFunction);
  79890. }
  79891. }
  79892. if (color && this._renderLine) {
  79893. this._renderLine.color.copyFrom(color);
  79894. }
  79895. };
  79896. RayHelper.prototype.hide = function () {
  79897. if (this._renderFunction && this._scene) {
  79898. this._scene.unregisterBeforeRender(this._renderFunction);
  79899. this._scene = null;
  79900. this._renderFunction = null;
  79901. if (this._renderLine) {
  79902. this._renderLine.dispose();
  79903. this._renderLine = null;
  79904. }
  79905. this._renderPoints = [];
  79906. }
  79907. };
  79908. RayHelper.prototype._render = function () {
  79909. var ray = this.ray;
  79910. if (!ray) {
  79911. return;
  79912. }
  79913. var point = this._renderPoints[1];
  79914. var len = Math.min(ray.length, 1000000);
  79915. point.copyFrom(ray.direction);
  79916. point.scaleInPlace(len);
  79917. point.addInPlace(ray.origin);
  79918. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  79919. };
  79920. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  79921. this._attachedToMesh = mesh;
  79922. var ray = this.ray;
  79923. if (!ray) {
  79924. return;
  79925. }
  79926. if (!ray.direction) {
  79927. ray.direction = BABYLON.Vector3.Zero();
  79928. }
  79929. if (!ray.origin) {
  79930. ray.origin = BABYLON.Vector3.Zero();
  79931. }
  79932. if (length) {
  79933. ray.length = length;
  79934. }
  79935. if (!meshSpaceOrigin) {
  79936. meshSpaceOrigin = BABYLON.Vector3.Zero();
  79937. }
  79938. if (!meshSpaceDirection) {
  79939. // -1 so that this will work with Mesh.lookAt
  79940. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  79941. }
  79942. if (!this._meshSpaceDirection) {
  79943. this._meshSpaceDirection = meshSpaceDirection.clone();
  79944. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  79945. }
  79946. else {
  79947. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  79948. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  79949. }
  79950. if (!this._updateToMeshFunction) {
  79951. this._updateToMeshFunction = this._updateToMesh.bind(this);
  79952. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  79953. }
  79954. this._updateToMesh();
  79955. };
  79956. RayHelper.prototype.detachFromMesh = function () {
  79957. if (this._attachedToMesh) {
  79958. if (this._updateToMeshFunction) {
  79959. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  79960. }
  79961. this._attachedToMesh = null;
  79962. this._updateToMeshFunction = null;
  79963. }
  79964. };
  79965. RayHelper.prototype._updateToMesh = function () {
  79966. var ray = this.ray;
  79967. if (!this._attachedToMesh || !ray) {
  79968. return;
  79969. }
  79970. if (this._attachedToMesh._isDisposed) {
  79971. this.detachFromMesh();
  79972. return;
  79973. }
  79974. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  79975. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  79976. };
  79977. RayHelper.prototype.dispose = function () {
  79978. this.hide();
  79979. this.detachFromMesh();
  79980. this.ray = null;
  79981. };
  79982. return RayHelper;
  79983. }());
  79984. BABYLON.RayHelper = RayHelper;
  79985. })(BABYLON || (BABYLON = {}));
  79986. //# sourceMappingURL=babylon.rayHelper.js.map
  79987. var BABYLON;
  79988. (function (BABYLON) {
  79989. // load the inspector using require, if not present in the global namespace.
  79990. var DebugLayer = /** @class */ (function () {
  79991. function DebugLayer(scene) {
  79992. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  79993. this._scene = scene;
  79994. // load inspector using require, if it doesn't exist on the global namespace.
  79995. }
  79996. /** Creates the inspector window. */
  79997. DebugLayer.prototype._createInspector = function (config) {
  79998. if (config === void 0) { config = {}; }
  79999. var popup = config.popup || false;
  80000. var initialTab = config.initialTab || 0;
  80001. var parentElement = config.parentElement || null;
  80002. if (!this._inspector) {
  80003. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80004. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  80005. } // else nothing to do,; instance is already existing
  80006. };
  80007. DebugLayer.prototype.isVisible = function () {
  80008. if (!this._inspector) {
  80009. return false;
  80010. }
  80011. return true;
  80012. };
  80013. DebugLayer.prototype.hide = function () {
  80014. if (this._inspector) {
  80015. try {
  80016. this._inspector.dispose();
  80017. }
  80018. catch (e) {
  80019. // If the inspector has been removed directly from the inspector tool
  80020. }
  80021. this._inspector = null;
  80022. }
  80023. };
  80024. DebugLayer.prototype.show = function (config) {
  80025. if (config === void 0) { config = {}; }
  80026. if (typeof this.BJSINSPECTOR == 'undefined') {
  80027. // Load inspector and add it to the DOM
  80028. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  80029. }
  80030. else {
  80031. // Otherwise creates the inspector
  80032. this._createInspector(config);
  80033. }
  80034. };
  80035. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  80036. return DebugLayer;
  80037. }());
  80038. BABYLON.DebugLayer = DebugLayer;
  80039. })(BABYLON || (BABYLON = {}));
  80040. //# sourceMappingURL=babylon.debugLayer.js.map
  80041. var BABYLON;
  80042. (function (BABYLON) {
  80043. var BoundingBoxRenderer = /** @class */ (function () {
  80044. function BoundingBoxRenderer(scene) {
  80045. this.frontColor = new BABYLON.Color3(1, 1, 1);
  80046. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  80047. this.showBackLines = true;
  80048. this.renderList = new BABYLON.SmartArray(32);
  80049. this._vertexBuffers = {};
  80050. this._scene = scene;
  80051. }
  80052. BoundingBoxRenderer.prototype._prepareRessources = function () {
  80053. if (this._colorShader) {
  80054. return;
  80055. }
  80056. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  80057. attributes: [BABYLON.VertexBuffer.PositionKind],
  80058. uniforms: ["world", "viewProjection", "color"]
  80059. });
  80060. var engine = this._scene.getEngine();
  80061. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  80062. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  80063. this._createIndexBuffer();
  80064. };
  80065. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  80066. var engine = this._scene.getEngine();
  80067. 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]);
  80068. };
  80069. BoundingBoxRenderer.prototype._rebuild = function () {
  80070. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80071. if (vb) {
  80072. vb._rebuild();
  80073. }
  80074. this._createIndexBuffer();
  80075. };
  80076. BoundingBoxRenderer.prototype.reset = function () {
  80077. this.renderList.reset();
  80078. };
  80079. BoundingBoxRenderer.prototype.render = function () {
  80080. if (this.renderList.length === 0) {
  80081. return;
  80082. }
  80083. this._prepareRessources();
  80084. if (!this._colorShader.isReady()) {
  80085. return;
  80086. }
  80087. var engine = this._scene.getEngine();
  80088. engine.setDepthWrite(false);
  80089. this._colorShader._preBind();
  80090. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  80091. var boundingBox = this.renderList.data[boundingBoxIndex];
  80092. var min = boundingBox.minimum;
  80093. var max = boundingBox.maximum;
  80094. var diff = max.subtract(min);
  80095. var median = min.add(diff.scale(0.5));
  80096. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  80097. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  80098. .multiply(boundingBox.getWorldMatrix());
  80099. // VBOs
  80100. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  80101. if (this.showBackLines) {
  80102. // Back
  80103. engine.setDepthFunctionToGreaterOrEqual();
  80104. this._scene.resetCachedMaterial();
  80105. this._colorShader.setColor4("color", this.backColor.toColor4());
  80106. this._colorShader.bind(worldMatrix);
  80107. // Draw order
  80108. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80109. }
  80110. // Front
  80111. engine.setDepthFunctionToLess();
  80112. this._scene.resetCachedMaterial();
  80113. this._colorShader.setColor4("color", this.frontColor.toColor4());
  80114. this._colorShader.bind(worldMatrix);
  80115. // Draw order
  80116. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80117. }
  80118. this._colorShader.unbind();
  80119. engine.setDepthFunctionToLessOrEqual();
  80120. engine.setDepthWrite(true);
  80121. };
  80122. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  80123. this._prepareRessources();
  80124. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  80125. return;
  80126. }
  80127. var engine = this._scene.getEngine();
  80128. engine.setDepthWrite(false);
  80129. engine.setColorWrite(false);
  80130. this._colorShader._preBind();
  80131. var boundingBox = mesh._boundingInfo.boundingBox;
  80132. var min = boundingBox.minimum;
  80133. var max = boundingBox.maximum;
  80134. var diff = max.subtract(min);
  80135. var median = min.add(diff.scale(0.5));
  80136. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  80137. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  80138. .multiply(boundingBox.getWorldMatrix());
  80139. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  80140. engine.setDepthFunctionToLess();
  80141. this._scene.resetCachedMaterial();
  80142. this._colorShader.bind(worldMatrix);
  80143. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80144. this._colorShader.unbind();
  80145. engine.setDepthFunctionToLessOrEqual();
  80146. engine.setDepthWrite(true);
  80147. engine.setColorWrite(true);
  80148. };
  80149. BoundingBoxRenderer.prototype.dispose = function () {
  80150. if (!this._colorShader) {
  80151. return;
  80152. }
  80153. this.renderList.dispose();
  80154. this._colorShader.dispose();
  80155. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80156. if (buffer) {
  80157. buffer.dispose();
  80158. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80159. }
  80160. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80161. };
  80162. return BoundingBoxRenderer;
  80163. }());
  80164. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  80165. })(BABYLON || (BABYLON = {}));
  80166. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  80167. var BABYLON;
  80168. (function (BABYLON) {
  80169. var MorphTarget = /** @class */ (function () {
  80170. function MorphTarget(name, influence) {
  80171. if (influence === void 0) { influence = 0; }
  80172. this.name = name;
  80173. this.animations = new Array();
  80174. this._positions = null;
  80175. this._normals = null;
  80176. this._tangents = null;
  80177. this.onInfluenceChanged = new BABYLON.Observable();
  80178. this.influence = influence;
  80179. }
  80180. Object.defineProperty(MorphTarget.prototype, "influence", {
  80181. get: function () {
  80182. return this._influence;
  80183. },
  80184. set: function (influence) {
  80185. if (this._influence === influence) {
  80186. return;
  80187. }
  80188. var previous = this._influence;
  80189. this._influence = influence;
  80190. if (this.onInfluenceChanged.hasObservers) {
  80191. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  80192. }
  80193. },
  80194. enumerable: true,
  80195. configurable: true
  80196. });
  80197. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  80198. get: function () {
  80199. return !!this._positions;
  80200. },
  80201. enumerable: true,
  80202. configurable: true
  80203. });
  80204. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  80205. get: function () {
  80206. return !!this._normals;
  80207. },
  80208. enumerable: true,
  80209. configurable: true
  80210. });
  80211. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  80212. get: function () {
  80213. return !!this._tangents;
  80214. },
  80215. enumerable: true,
  80216. configurable: true
  80217. });
  80218. MorphTarget.prototype.setPositions = function (data) {
  80219. this._positions = data;
  80220. };
  80221. MorphTarget.prototype.getPositions = function () {
  80222. return this._positions;
  80223. };
  80224. MorphTarget.prototype.setNormals = function (data) {
  80225. this._normals = data;
  80226. };
  80227. MorphTarget.prototype.getNormals = function () {
  80228. return this._normals;
  80229. };
  80230. MorphTarget.prototype.setTangents = function (data) {
  80231. this._tangents = data;
  80232. };
  80233. MorphTarget.prototype.getTangents = function () {
  80234. return this._tangents;
  80235. };
  80236. /**
  80237. * Serializes the current target into a Serialization object.
  80238. * Returns the serialized object.
  80239. */
  80240. MorphTarget.prototype.serialize = function () {
  80241. var serializationObject = {};
  80242. serializationObject.name = this.name;
  80243. serializationObject.influence = this.influence;
  80244. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  80245. if (this.hasNormals) {
  80246. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  80247. }
  80248. if (this.hasTangents) {
  80249. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  80250. }
  80251. // Animations
  80252. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  80253. return serializationObject;
  80254. };
  80255. // Statics
  80256. MorphTarget.Parse = function (serializationObject) {
  80257. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  80258. result.setPositions(serializationObject.positions);
  80259. if (serializationObject.normals) {
  80260. result.setNormals(serializationObject.normals);
  80261. }
  80262. if (serializationObject.tangents) {
  80263. result.setTangents(serializationObject.tangents);
  80264. }
  80265. // Animations
  80266. if (serializationObject.animations) {
  80267. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  80268. var parsedAnimation = serializationObject.animations[animationIndex];
  80269. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  80270. }
  80271. }
  80272. return result;
  80273. };
  80274. MorphTarget.FromMesh = function (mesh, name, influence) {
  80275. if (!name) {
  80276. name = mesh.name;
  80277. }
  80278. var result = new MorphTarget(name, influence);
  80279. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  80280. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  80281. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  80282. }
  80283. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  80284. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  80285. }
  80286. return result;
  80287. };
  80288. return MorphTarget;
  80289. }());
  80290. BABYLON.MorphTarget = MorphTarget;
  80291. })(BABYLON || (BABYLON = {}));
  80292. //# sourceMappingURL=babylon.morphTarget.js.map
  80293. var BABYLON;
  80294. (function (BABYLON) {
  80295. var MorphTargetManager = /** @class */ (function () {
  80296. function MorphTargetManager(scene) {
  80297. if (scene === void 0) { scene = null; }
  80298. this._targets = new Array();
  80299. this._targetObservable = new Array();
  80300. this._activeTargets = new BABYLON.SmartArray(16);
  80301. this._supportsNormals = false;
  80302. this._supportsTangents = false;
  80303. this._vertexCount = 0;
  80304. this._uniqueId = 0;
  80305. this._tempInfluences = new Array();
  80306. if (!scene) {
  80307. scene = BABYLON.Engine.LastCreatedScene;
  80308. }
  80309. this._scene = scene;
  80310. if (this._scene) {
  80311. this._scene.morphTargetManagers.push(this);
  80312. this._uniqueId = this._scene.getUniqueId();
  80313. }
  80314. }
  80315. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  80316. get: function () {
  80317. return this._uniqueId;
  80318. },
  80319. enumerable: true,
  80320. configurable: true
  80321. });
  80322. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  80323. get: function () {
  80324. return this._vertexCount;
  80325. },
  80326. enumerable: true,
  80327. configurable: true
  80328. });
  80329. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  80330. get: function () {
  80331. return this._supportsNormals;
  80332. },
  80333. enumerable: true,
  80334. configurable: true
  80335. });
  80336. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  80337. get: function () {
  80338. return this._supportsTangents;
  80339. },
  80340. enumerable: true,
  80341. configurable: true
  80342. });
  80343. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  80344. get: function () {
  80345. return this._targets.length;
  80346. },
  80347. enumerable: true,
  80348. configurable: true
  80349. });
  80350. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  80351. get: function () {
  80352. return this._activeTargets.length;
  80353. },
  80354. enumerable: true,
  80355. configurable: true
  80356. });
  80357. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  80358. get: function () {
  80359. return this._influences;
  80360. },
  80361. enumerable: true,
  80362. configurable: true
  80363. });
  80364. MorphTargetManager.prototype.getActiveTarget = function (index) {
  80365. return this._activeTargets.data[index];
  80366. };
  80367. MorphTargetManager.prototype.getTarget = function (index) {
  80368. return this._targets[index];
  80369. };
  80370. MorphTargetManager.prototype.addTarget = function (target) {
  80371. var _this = this;
  80372. this._targets.push(target);
  80373. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  80374. _this._syncActiveTargets(needUpdate);
  80375. }));
  80376. this._syncActiveTargets(true);
  80377. };
  80378. MorphTargetManager.prototype.removeTarget = function (target) {
  80379. var index = this._targets.indexOf(target);
  80380. if (index >= 0) {
  80381. this._targets.splice(index, 1);
  80382. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  80383. this._syncActiveTargets(true);
  80384. }
  80385. };
  80386. /**
  80387. * Serializes the current manager into a Serialization object.
  80388. * Returns the serialized object.
  80389. */
  80390. MorphTargetManager.prototype.serialize = function () {
  80391. var serializationObject = {};
  80392. serializationObject.id = this.uniqueId;
  80393. serializationObject.targets = [];
  80394. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  80395. var target = _a[_i];
  80396. serializationObject.targets.push(target.serialize());
  80397. }
  80398. return serializationObject;
  80399. };
  80400. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  80401. var influenceCount = 0;
  80402. this._activeTargets.reset();
  80403. this._supportsNormals = true;
  80404. this._supportsTangents = true;
  80405. this._vertexCount = 0;
  80406. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  80407. var target = _a[_i];
  80408. this._activeTargets.push(target);
  80409. this._tempInfluences[influenceCount++] = target.influence;
  80410. var positions = target.getPositions();
  80411. if (positions) {
  80412. this._supportsNormals = this._supportsNormals && target.hasNormals;
  80413. this._supportsTangents = this._supportsTangents && target.hasTangents;
  80414. var vertexCount = positions.length / 3;
  80415. if (this._vertexCount === 0) {
  80416. this._vertexCount = vertexCount;
  80417. }
  80418. else if (this._vertexCount !== vertexCount) {
  80419. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  80420. return;
  80421. }
  80422. }
  80423. }
  80424. if (!this._influences || this._influences.length !== influenceCount) {
  80425. this._influences = new Float32Array(influenceCount);
  80426. }
  80427. for (var index = 0; index < influenceCount; index++) {
  80428. this._influences[index] = this._tempInfluences[index];
  80429. }
  80430. if (needUpdate && this._scene) {
  80431. // Flag meshes as dirty to resync with the active targets
  80432. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  80433. var mesh = _c[_b];
  80434. if (mesh.morphTargetManager === this) {
  80435. mesh._syncGeometryWithMorphTargetManager();
  80436. }
  80437. }
  80438. }
  80439. };
  80440. // Statics
  80441. MorphTargetManager.Parse = function (serializationObject, scene) {
  80442. var result = new MorphTargetManager(scene);
  80443. result._uniqueId = serializationObject.id;
  80444. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  80445. var targetData = _a[_i];
  80446. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  80447. }
  80448. return result;
  80449. };
  80450. return MorphTargetManager;
  80451. }());
  80452. BABYLON.MorphTargetManager = MorphTargetManager;
  80453. })(BABYLON || (BABYLON = {}));
  80454. //# sourceMappingURL=babylon.morphTargetManager.js.map
  80455. var BABYLON;
  80456. (function (BABYLON) {
  80457. var Octree = /** @class */ (function () {
  80458. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  80459. if (maxDepth === void 0) { maxDepth = 2; }
  80460. this.maxDepth = maxDepth;
  80461. this.dynamicContent = new Array();
  80462. this._maxBlockCapacity = maxBlockCapacity || 64;
  80463. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  80464. this._creationFunc = creationFunc;
  80465. }
  80466. // Methods
  80467. Octree.prototype.update = function (worldMin, worldMax, entries) {
  80468. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  80469. };
  80470. Octree.prototype.addMesh = function (entry) {
  80471. for (var index = 0; index < this.blocks.length; index++) {
  80472. var block = this.blocks[index];
  80473. block.addEntry(entry);
  80474. }
  80475. };
  80476. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  80477. this._selectionContent.reset();
  80478. for (var index = 0; index < this.blocks.length; index++) {
  80479. var block = this.blocks[index];
  80480. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  80481. }
  80482. if (allowDuplicate) {
  80483. this._selectionContent.concat(this.dynamicContent);
  80484. }
  80485. else {
  80486. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80487. }
  80488. return this._selectionContent;
  80489. };
  80490. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  80491. this._selectionContent.reset();
  80492. for (var index = 0; index < this.blocks.length; index++) {
  80493. var block = this.blocks[index];
  80494. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  80495. }
  80496. if (allowDuplicate) {
  80497. this._selectionContent.concat(this.dynamicContent);
  80498. }
  80499. else {
  80500. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80501. }
  80502. return this._selectionContent;
  80503. };
  80504. Octree.prototype.intersectsRay = function (ray) {
  80505. this._selectionContent.reset();
  80506. for (var index = 0; index < this.blocks.length; index++) {
  80507. var block = this.blocks[index];
  80508. block.intersectsRay(ray, this._selectionContent);
  80509. }
  80510. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80511. return this._selectionContent;
  80512. };
  80513. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  80514. target.blocks = new Array();
  80515. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  80516. // Segmenting space
  80517. for (var x = 0; x < 2; x++) {
  80518. for (var y = 0; y < 2; y++) {
  80519. for (var z = 0; z < 2; z++) {
  80520. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  80521. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  80522. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  80523. block.addEntries(entries);
  80524. target.blocks.push(block);
  80525. }
  80526. }
  80527. }
  80528. };
  80529. Octree.CreationFuncForMeshes = function (entry, block) {
  80530. var boundingInfo = entry.getBoundingInfo();
  80531. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  80532. block.entries.push(entry);
  80533. }
  80534. };
  80535. Octree.CreationFuncForSubMeshes = function (entry, block) {
  80536. var boundingInfo = entry.getBoundingInfo();
  80537. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  80538. block.entries.push(entry);
  80539. }
  80540. };
  80541. return Octree;
  80542. }());
  80543. BABYLON.Octree = Octree;
  80544. })(BABYLON || (BABYLON = {}));
  80545. //# sourceMappingURL=babylon.octree.js.map
  80546. var BABYLON;
  80547. (function (BABYLON) {
  80548. var OctreeBlock = /** @class */ (function () {
  80549. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  80550. this.entries = new Array();
  80551. this._boundingVectors = new Array();
  80552. this._capacity = capacity;
  80553. this._depth = depth;
  80554. this._maxDepth = maxDepth;
  80555. this._creationFunc = creationFunc;
  80556. this._minPoint = minPoint;
  80557. this._maxPoint = maxPoint;
  80558. this._boundingVectors.push(minPoint.clone());
  80559. this._boundingVectors.push(maxPoint.clone());
  80560. this._boundingVectors.push(minPoint.clone());
  80561. this._boundingVectors[2].x = maxPoint.x;
  80562. this._boundingVectors.push(minPoint.clone());
  80563. this._boundingVectors[3].y = maxPoint.y;
  80564. this._boundingVectors.push(minPoint.clone());
  80565. this._boundingVectors[4].z = maxPoint.z;
  80566. this._boundingVectors.push(maxPoint.clone());
  80567. this._boundingVectors[5].z = minPoint.z;
  80568. this._boundingVectors.push(maxPoint.clone());
  80569. this._boundingVectors[6].x = minPoint.x;
  80570. this._boundingVectors.push(maxPoint.clone());
  80571. this._boundingVectors[7].y = minPoint.y;
  80572. }
  80573. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  80574. // Property
  80575. get: function () {
  80576. return this._capacity;
  80577. },
  80578. enumerable: true,
  80579. configurable: true
  80580. });
  80581. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  80582. get: function () {
  80583. return this._minPoint;
  80584. },
  80585. enumerable: true,
  80586. configurable: true
  80587. });
  80588. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  80589. get: function () {
  80590. return this._maxPoint;
  80591. },
  80592. enumerable: true,
  80593. configurable: true
  80594. });
  80595. // Methods
  80596. OctreeBlock.prototype.addEntry = function (entry) {
  80597. if (this.blocks) {
  80598. for (var index = 0; index < this.blocks.length; index++) {
  80599. var block = this.blocks[index];
  80600. block.addEntry(entry);
  80601. }
  80602. return;
  80603. }
  80604. this._creationFunc(entry, this);
  80605. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  80606. this.createInnerBlocks();
  80607. }
  80608. };
  80609. OctreeBlock.prototype.addEntries = function (entries) {
  80610. for (var index = 0; index < entries.length; index++) {
  80611. var mesh = entries[index];
  80612. this.addEntry(mesh);
  80613. }
  80614. };
  80615. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  80616. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  80617. if (this.blocks) {
  80618. for (var index = 0; index < this.blocks.length; index++) {
  80619. var block = this.blocks[index];
  80620. block.select(frustumPlanes, selection, allowDuplicate);
  80621. }
  80622. return;
  80623. }
  80624. if (allowDuplicate) {
  80625. selection.concat(this.entries);
  80626. }
  80627. else {
  80628. selection.concatWithNoDuplicate(this.entries);
  80629. }
  80630. }
  80631. };
  80632. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  80633. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  80634. if (this.blocks) {
  80635. for (var index = 0; index < this.blocks.length; index++) {
  80636. var block = this.blocks[index];
  80637. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  80638. }
  80639. return;
  80640. }
  80641. if (allowDuplicate) {
  80642. selection.concat(this.entries);
  80643. }
  80644. else {
  80645. selection.concatWithNoDuplicate(this.entries);
  80646. }
  80647. }
  80648. };
  80649. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  80650. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  80651. if (this.blocks) {
  80652. for (var index = 0; index < this.blocks.length; index++) {
  80653. var block = this.blocks[index];
  80654. block.intersectsRay(ray, selection);
  80655. }
  80656. return;
  80657. }
  80658. selection.concatWithNoDuplicate(this.entries);
  80659. }
  80660. };
  80661. OctreeBlock.prototype.createInnerBlocks = function () {
  80662. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  80663. };
  80664. return OctreeBlock;
  80665. }());
  80666. BABYLON.OctreeBlock = OctreeBlock;
  80667. })(BABYLON || (BABYLON = {}));
  80668. //# sourceMappingURL=babylon.octreeBlock.js.map
  80669. var BABYLON;
  80670. (function (BABYLON) {
  80671. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  80672. __extends(VRDistortionCorrectionPostProcess, _super);
  80673. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  80674. var _this = _super.call(this, name, "vrDistortionCorrection", [
  80675. 'LensCenter',
  80676. 'Scale',
  80677. 'ScaleIn',
  80678. 'HmdWarpParam'
  80679. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  80680. _this._isRightEye = isRightEye;
  80681. _this._distortionFactors = vrMetrics.distortionK;
  80682. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  80683. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  80684. _this.adaptScaleToCurrentViewport = true;
  80685. _this.onSizeChangedObservable.add(function () {
  80686. _this.aspectRatio = _this.width * .5 / _this.height;
  80687. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  80688. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  80689. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  80690. });
  80691. _this.onApplyObservable.add(function (effect) {
  80692. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  80693. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  80694. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  80695. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  80696. });
  80697. return _this;
  80698. }
  80699. return VRDistortionCorrectionPostProcess;
  80700. }(BABYLON.PostProcess));
  80701. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  80702. })(BABYLON || (BABYLON = {}));
  80703. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  80704. var BABYLON;
  80705. (function (BABYLON) {
  80706. var AnaglyphPostProcess = /** @class */ (function (_super) {
  80707. __extends(AnaglyphPostProcess, _super);
  80708. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  80709. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  80710. _this._passedProcess = rigCameras[0]._rigPostProcess;
  80711. _this.onApplyObservable.add(function (effect) {
  80712. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  80713. });
  80714. return _this;
  80715. }
  80716. return AnaglyphPostProcess;
  80717. }(BABYLON.PostProcess));
  80718. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  80719. })(BABYLON || (BABYLON = {}));
  80720. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  80721. var BABYLON;
  80722. (function (BABYLON) {
  80723. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  80724. __extends(StereoscopicInterlacePostProcess, _super);
  80725. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  80726. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  80727. _this._passedProcess = rigCameras[0]._rigPostProcess;
  80728. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  80729. _this.onSizeChangedObservable.add(function () {
  80730. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  80731. });
  80732. _this.onApplyObservable.add(function (effect) {
  80733. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  80734. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  80735. });
  80736. return _this;
  80737. }
  80738. return StereoscopicInterlacePostProcess;
  80739. }(BABYLON.PostProcess));
  80740. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  80741. })(BABYLON || (BABYLON = {}));
  80742. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  80743. var BABYLON;
  80744. (function (BABYLON) {
  80745. /**
  80746. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  80747. * Screen rotation is taken into account.
  80748. */
  80749. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  80750. function FreeCameraDeviceOrientationInput() {
  80751. var _this = this;
  80752. this._screenOrientationAngle = 0;
  80753. this._screenQuaternion = new BABYLON.Quaternion();
  80754. this._alpha = 0;
  80755. this._beta = 0;
  80756. this._gamma = 0;
  80757. this._orientationChanged = function () {
  80758. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  80759. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  80760. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  80761. };
  80762. this._deviceOrientation = function (evt) {
  80763. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  80764. _this._beta = evt.beta !== null ? evt.beta : 0;
  80765. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  80766. };
  80767. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  80768. this._orientationChanged();
  80769. }
  80770. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  80771. get: function () {
  80772. return this._camera;
  80773. },
  80774. set: function (camera) {
  80775. this._camera = camera;
  80776. if (this._camera != null && !this._camera.rotationQuaternion) {
  80777. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  80778. }
  80779. },
  80780. enumerable: true,
  80781. configurable: true
  80782. });
  80783. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  80784. window.addEventListener("orientationchange", this._orientationChanged);
  80785. window.addEventListener("deviceorientation", this._deviceOrientation);
  80786. //In certain cases, the attach control is called AFTER orientation was changed,
  80787. //So this is needed.
  80788. this._orientationChanged();
  80789. };
  80790. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  80791. window.removeEventListener("orientationchange", this._orientationChanged);
  80792. window.removeEventListener("deviceorientation", this._deviceOrientation);
  80793. };
  80794. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  80795. //if no device orientation provided, don't update the rotation.
  80796. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  80797. if (!this._alpha)
  80798. return;
  80799. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  80800. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  80801. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  80802. //Mirror on XY Plane
  80803. this._camera.rotationQuaternion.z *= -1;
  80804. this._camera.rotationQuaternion.w *= -1;
  80805. };
  80806. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  80807. return "FreeCameraDeviceOrientationInput";
  80808. };
  80809. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  80810. return "deviceOrientation";
  80811. };
  80812. return FreeCameraDeviceOrientationInput;
  80813. }());
  80814. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  80815. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  80816. })(BABYLON || (BABYLON = {}));
  80817. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  80818. var BABYLON;
  80819. (function (BABYLON) {
  80820. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  80821. function ArcRotateCameraVRDeviceOrientationInput() {
  80822. this.alphaCorrection = 1;
  80823. this.betaCorrection = 1;
  80824. this.gammaCorrection = 1;
  80825. this._alpha = 0;
  80826. this._gamma = 0;
  80827. this._dirty = false;
  80828. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  80829. }
  80830. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  80831. this.camera.attachControl(element, noPreventDefault);
  80832. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  80833. };
  80834. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  80835. if (evt.alpha !== null) {
  80836. this._alpha = +evt.alpha | 0;
  80837. }
  80838. if (evt.gamma !== null) {
  80839. this._gamma = +evt.gamma | 0;
  80840. }
  80841. this._dirty = true;
  80842. };
  80843. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  80844. if (this._dirty) {
  80845. this._dirty = false;
  80846. if (this._gamma < 0) {
  80847. this._gamma = 180 + this._gamma;
  80848. }
  80849. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  80850. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  80851. }
  80852. };
  80853. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  80854. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  80855. };
  80856. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  80857. return "ArcRotateCameraVRDeviceOrientationInput";
  80858. };
  80859. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  80860. return "VRDeviceOrientation";
  80861. };
  80862. return ArcRotateCameraVRDeviceOrientationInput;
  80863. }());
  80864. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  80865. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  80866. })(BABYLON || (BABYLON = {}));
  80867. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  80868. var BABYLON;
  80869. (function (BABYLON) {
  80870. var VRCameraMetrics = /** @class */ (function () {
  80871. function VRCameraMetrics() {
  80872. this.compensateDistortion = true;
  80873. }
  80874. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  80875. get: function () {
  80876. return this.hResolution / (2 * this.vResolution);
  80877. },
  80878. enumerable: true,
  80879. configurable: true
  80880. });
  80881. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  80882. get: function () {
  80883. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  80884. },
  80885. enumerable: true,
  80886. configurable: true
  80887. });
  80888. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  80889. get: function () {
  80890. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  80891. var h = (4 * meters) / this.hScreenSize;
  80892. return BABYLON.Matrix.Translation(h, 0, 0);
  80893. },
  80894. enumerable: true,
  80895. configurable: true
  80896. });
  80897. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  80898. get: function () {
  80899. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  80900. var h = (4 * meters) / this.hScreenSize;
  80901. return BABYLON.Matrix.Translation(-h, 0, 0);
  80902. },
  80903. enumerable: true,
  80904. configurable: true
  80905. });
  80906. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  80907. get: function () {
  80908. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  80909. },
  80910. enumerable: true,
  80911. configurable: true
  80912. });
  80913. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  80914. get: function () {
  80915. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  80916. },
  80917. enumerable: true,
  80918. configurable: true
  80919. });
  80920. VRCameraMetrics.GetDefault = function () {
  80921. var result = new VRCameraMetrics();
  80922. result.hResolution = 1280;
  80923. result.vResolution = 800;
  80924. result.hScreenSize = 0.149759993;
  80925. result.vScreenSize = 0.0935999975;
  80926. result.vScreenCenter = 0.0467999987;
  80927. result.eyeToScreenDistance = 0.0410000011;
  80928. result.lensSeparationDistance = 0.0635000020;
  80929. result.interpupillaryDistance = 0.0640000030;
  80930. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  80931. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  80932. result.postProcessScaleFactor = 1.714605507808412;
  80933. result.lensCenterOffset = 0.151976421;
  80934. return result;
  80935. };
  80936. return VRCameraMetrics;
  80937. }());
  80938. BABYLON.VRCameraMetrics = VRCameraMetrics;
  80939. })(BABYLON || (BABYLON = {}));
  80940. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  80941. var BABYLON;
  80942. (function (BABYLON) {
  80943. /**
  80944. * This represents a WebVR camera.
  80945. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  80946. * @example http://doc.babylonjs.com/how_to/webvr_camera
  80947. */
  80948. var WebVRFreeCamera = /** @class */ (function (_super) {
  80949. __extends(WebVRFreeCamera, _super);
  80950. /**
  80951. * Instantiates a WebVRFreeCamera.
  80952. * @param name The name of the WebVRFreeCamera
  80953. * @param position The starting anchor position for the camera
  80954. * @param scene The scene the camera belongs to
  80955. * @param webVROptions a set of customizable options for the webVRCamera
  80956. */
  80957. function WebVRFreeCamera(name, position, scene, webVROptions) {
  80958. if (webVROptions === void 0) { webVROptions = {}; }
  80959. var _this = _super.call(this, name, position, scene) || this;
  80960. _this.webVROptions = webVROptions;
  80961. /**
  80962. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  80963. */
  80964. _this._vrDevice = null;
  80965. /**
  80966. * The rawPose of the vrDevice.
  80967. */
  80968. _this.rawPose = null;
  80969. _this._specsVersion = "1.1";
  80970. _this._attached = false;
  80971. _this._descendants = [];
  80972. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  80973. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  80974. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  80975. _this._standingMatrix = null;
  80976. /**
  80977. * Represents device position in babylon space.
  80978. */
  80979. _this.devicePosition = BABYLON.Vector3.Zero();
  80980. /**
  80981. * Represents device rotation in babylon space.
  80982. */
  80983. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  80984. /**
  80985. * The scale of the device to be used when translating from device space to babylon space.
  80986. */
  80987. _this.deviceScaleFactor = 1;
  80988. _this._deviceToWorld = BABYLON.Matrix.Identity();
  80989. _this._worldToDevice = BABYLON.Matrix.Identity();
  80990. /**
  80991. * References to the webVR controllers for the vrDevice.
  80992. */
  80993. _this.controllers = [];
  80994. /**
  80995. * Emits an event when a controller is attached.
  80996. */
  80997. _this.onControllersAttachedObservable = new BABYLON.Observable();
  80998. /**
  80999. * Emits an event when a controller's mesh has been loaded;
  81000. */
  81001. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  81002. /**
  81003. * If the rig cameras be used as parent instead of this camera.
  81004. */
  81005. _this.rigParenting = true;
  81006. _this._defaultHeight = undefined;
  81007. _this._workingVector = BABYLON.Vector3.Zero();
  81008. _this._oneVector = BABYLON.Vector3.One();
  81009. _this._workingMatrix = BABYLON.Matrix.Identity();
  81010. _this._cache.position = BABYLON.Vector3.Zero();
  81011. if (webVROptions.defaultHeight) {
  81012. _this._defaultHeight = webVROptions.defaultHeight;
  81013. _this.position.y = _this._defaultHeight;
  81014. }
  81015. _this.minZ = 0.1;
  81016. //legacy support - the compensation boolean was removed.
  81017. if (arguments.length === 5) {
  81018. _this.webVROptions = arguments[4];
  81019. }
  81020. // default webVR options
  81021. if (_this.webVROptions.trackPosition == undefined) {
  81022. _this.webVROptions.trackPosition = true;
  81023. }
  81024. if (_this.webVROptions.controllerMeshes == undefined) {
  81025. _this.webVROptions.controllerMeshes = true;
  81026. }
  81027. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  81028. _this.webVROptions.defaultLightingOnControllers = true;
  81029. }
  81030. _this.rotationQuaternion = new BABYLON.Quaternion();
  81031. if (_this.webVROptions && _this.webVROptions.positionScale) {
  81032. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  81033. }
  81034. //enable VR
  81035. var engine = _this.getEngine();
  81036. _this._onVREnabled = function (success) { if (success) {
  81037. _this.initControllers();
  81038. } };
  81039. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  81040. engine.initWebVR().add(function (event) {
  81041. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  81042. return;
  81043. }
  81044. _this._vrDevice = event.vrDisplay;
  81045. //reset the rig parameters.
  81046. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  81047. if (_this._attached) {
  81048. _this.getEngine().enableVR();
  81049. }
  81050. });
  81051. if (typeof (VRFrameData) !== "undefined")
  81052. _this._frameData = new VRFrameData();
  81053. /**
  81054. * The idea behind the following lines:
  81055. * objects that have the camera as parent should actually have the rig cameras as a parent.
  81056. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  81057. * the second will not show it correctly.
  81058. *
  81059. * To solve this - each object that has the camera as parent will be added to a protected array.
  81060. * When the rig camera renders, it will take this array and set all of those to be its children.
  81061. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  81062. * Amazing!
  81063. */
  81064. scene.onBeforeCameraRenderObservable.add(function (camera) {
  81065. if (camera.parent === _this && _this.rigParenting) {
  81066. _this._descendants = _this.getDescendants(true, function (n) {
  81067. // don't take the cameras or the controllers!
  81068. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  81069. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  81070. return !isController && !isRigCamera;
  81071. });
  81072. _this._descendants.forEach(function (node) {
  81073. node.parent = camera;
  81074. });
  81075. }
  81076. });
  81077. scene.onAfterCameraRenderObservable.add(function (camera) {
  81078. if (camera.parent === _this && _this.rigParenting) {
  81079. _this._descendants.forEach(function (node) {
  81080. node.parent = _this;
  81081. });
  81082. }
  81083. });
  81084. return _this;
  81085. }
  81086. /**
  81087. * Gets the device distance from the ground in meters.
  81088. * @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.
  81089. */
  81090. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  81091. if (this._standingMatrix) {
  81092. // Add standing matrix offset to get real offset from ground in room
  81093. this._standingMatrix.getTranslationToRef(this._workingVector);
  81094. return this._deviceRoomPosition.y + this._workingVector.y;
  81095. }
  81096. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  81097. return this._defaultHeight || 0;
  81098. };
  81099. /**
  81100. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  81101. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  81102. */
  81103. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  81104. var _this = this;
  81105. if (callback === void 0) { callback = function (bool) { }; }
  81106. // Use standing matrix if available
  81107. this.getEngine().initWebVRAsync().then(function (result) {
  81108. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  81109. callback(false);
  81110. }
  81111. else {
  81112. _this._standingMatrix = new BABYLON.Matrix();
  81113. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  81114. if (!_this.getScene().useRightHandedSystem) {
  81115. [2, 6, 8, 9, 14].forEach(function (num) {
  81116. if (_this._standingMatrix) {
  81117. _this._standingMatrix.m[num] *= -1;
  81118. }
  81119. });
  81120. }
  81121. callback(true);
  81122. }
  81123. });
  81124. };
  81125. /**
  81126. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  81127. * @returns A promise with a boolean set to if the standing matrix is supported.
  81128. */
  81129. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  81130. var _this = this;
  81131. return new Promise(function (res, rej) {
  81132. _this.useStandingMatrix(function (supported) {
  81133. res(supported);
  81134. });
  81135. });
  81136. };
  81137. /**
  81138. * Disposes the camera
  81139. */
  81140. WebVRFreeCamera.prototype.dispose = function () {
  81141. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  81142. _super.prototype.dispose.call(this);
  81143. };
  81144. /**
  81145. * Gets a vrController by name.
  81146. * @param name The name of the controller to retreive
  81147. * @returns the controller matching the name specified or null if not found
  81148. */
  81149. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  81150. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  81151. var gp = _a[_i];
  81152. if (gp.hand === name) {
  81153. return gp;
  81154. }
  81155. }
  81156. return null;
  81157. };
  81158. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  81159. /**
  81160. * The controller corrisponding to the users left hand.
  81161. */
  81162. get: function () {
  81163. if (!this._leftController) {
  81164. this._leftController = this.getControllerByName("left");
  81165. }
  81166. return this._leftController;
  81167. },
  81168. enumerable: true,
  81169. configurable: true
  81170. });
  81171. ;
  81172. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  81173. /**
  81174. * The controller corrisponding to the users right hand.
  81175. */
  81176. get: function () {
  81177. if (!this._rightController) {
  81178. this._rightController = this.getControllerByName("right");
  81179. }
  81180. return this._rightController;
  81181. },
  81182. enumerable: true,
  81183. configurable: true
  81184. });
  81185. ;
  81186. /**
  81187. * Casts a ray forward from the vrCamera's gaze.
  81188. * @param length Length of the ray (default: 100)
  81189. * @returns the ray corrisponding to the gaze
  81190. */
  81191. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  81192. if (length === void 0) { length = 100; }
  81193. if (this.leftCamera) {
  81194. // Use left eye to avoid computation to compute center on every call
  81195. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  81196. }
  81197. else {
  81198. return _super.prototype.getForwardRay.call(this, length);
  81199. }
  81200. };
  81201. /**
  81202. * Updates the camera based on device's frame data
  81203. */
  81204. WebVRFreeCamera.prototype._checkInputs = function () {
  81205. if (this._vrDevice && this._vrDevice.isPresenting) {
  81206. this._vrDevice.getFrameData(this._frameData);
  81207. this.updateFromDevice(this._frameData.pose);
  81208. }
  81209. _super.prototype._checkInputs.call(this);
  81210. };
  81211. /**
  81212. * Updates the poseControlled values based on the input device pose.
  81213. * @param poseData Pose coming from the device
  81214. */
  81215. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  81216. if (poseData && poseData.orientation) {
  81217. this.rawPose = poseData;
  81218. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  81219. if (this.getScene().useRightHandedSystem) {
  81220. this._deviceRoomRotationQuaternion.z *= -1;
  81221. this._deviceRoomRotationQuaternion.w *= -1;
  81222. }
  81223. if (this.webVROptions.trackPosition && this.rawPose.position) {
  81224. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  81225. if (this.getScene().useRightHandedSystem) {
  81226. this._deviceRoomPosition.z *= -1;
  81227. }
  81228. }
  81229. }
  81230. };
  81231. /**
  81232. * WebVR's attach control will start broadcasting frames to the device.
  81233. * Note that in certain browsers (chrome for example) this function must be called
  81234. * within a user-interaction callback. Example:
  81235. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  81236. *
  81237. * @param element html element to attach the vrDevice to
  81238. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  81239. */
  81240. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  81241. _super.prototype.attachControl.call(this, element, noPreventDefault);
  81242. this._attached = true;
  81243. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  81244. if (this._vrDevice) {
  81245. this.getEngine().enableVR();
  81246. }
  81247. };
  81248. /**
  81249. * Detaches the camera from the html element and disables VR
  81250. *
  81251. * @param element html element to detach from
  81252. */
  81253. WebVRFreeCamera.prototype.detachControl = function (element) {
  81254. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  81255. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  81256. _super.prototype.detachControl.call(this, element);
  81257. this._attached = false;
  81258. this.getEngine().disableVR();
  81259. };
  81260. /**
  81261. * @returns the name of this class
  81262. */
  81263. WebVRFreeCamera.prototype.getClassName = function () {
  81264. return "WebVRFreeCamera";
  81265. };
  81266. /**
  81267. * Calls resetPose on the vrDisplay
  81268. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  81269. */
  81270. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  81271. //uses the vrDisplay's "resetPose()".
  81272. //pitch and roll won't be affected.
  81273. this._vrDevice.resetPose();
  81274. };
  81275. /**
  81276. * Updates the rig cameras (left and right eye)
  81277. */
  81278. WebVRFreeCamera.prototype._updateRigCameras = function () {
  81279. var camLeft = this._rigCameras[0];
  81280. var camRight = this._rigCameras[1];
  81281. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  81282. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  81283. camLeft.position.copyFrom(this._deviceRoomPosition);
  81284. camRight.position.copyFrom(this._deviceRoomPosition);
  81285. };
  81286. /**
  81287. * Updates the cached values of the camera
  81288. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  81289. */
  81290. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  81291. var _this = this;
  81292. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  81293. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  81294. if (!this.updateCacheCalled) {
  81295. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  81296. this.updateCacheCalled = true;
  81297. this.update();
  81298. }
  81299. // Set working vector to the device position in room space rotated by the new rotation
  81300. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  81301. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  81302. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  81303. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  81304. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  81305. // Add translation from anchor position
  81306. this._deviceToWorld.getTranslationToRef(this._workingVector);
  81307. this._workingVector.addInPlace(this.position);
  81308. this._workingVector.subtractInPlace(this._cache.position);
  81309. this._deviceToWorld.setTranslation(this._workingVector);
  81310. // Set an inverted matrix to be used when updating the camera
  81311. this._deviceToWorld.invertToRef(this._worldToDevice);
  81312. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  81313. this.controllers.forEach(function (controller) {
  81314. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  81315. controller.update();
  81316. });
  81317. }
  81318. if (!ignoreParentClass) {
  81319. _super.prototype._updateCache.call(this);
  81320. }
  81321. this.updateCacheCalled = false;
  81322. };
  81323. /**
  81324. * Updates the current device position and rotation in the babylon world
  81325. */
  81326. WebVRFreeCamera.prototype.update = function () {
  81327. // Get current device position in babylon world
  81328. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  81329. // Get current device rotation in babylon world
  81330. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  81331. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  81332. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  81333. _super.prototype.update.call(this);
  81334. };
  81335. /**
  81336. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  81337. * @returns an identity matrix
  81338. */
  81339. WebVRFreeCamera.prototype._getViewMatrix = function () {
  81340. return BABYLON.Matrix.Identity();
  81341. };
  81342. /**
  81343. * This function is called by the two RIG cameras.
  81344. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  81345. */
  81346. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  81347. var _this = this;
  81348. // Update the parent camera prior to using a child camera to avoid desynchronization
  81349. var parentCamera = this._cameraRigParams["parentCamera"];
  81350. parentCamera._updateCache();
  81351. //WebVR 1.1
  81352. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  81353. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  81354. if (!this.getScene().useRightHandedSystem) {
  81355. [2, 6, 8, 9, 14].forEach(function (num) {
  81356. _this._webvrViewMatrix.m[num] *= -1;
  81357. });
  81358. }
  81359. // update the camera rotation matrix
  81360. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  81361. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  81362. // Computing target and final matrix
  81363. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  81364. // should the view matrix be updated with scale and position offset?
  81365. if (parentCamera.deviceScaleFactor !== 1) {
  81366. this._webvrViewMatrix.invert();
  81367. // scale the position, if set
  81368. if (parentCamera.deviceScaleFactor) {
  81369. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  81370. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  81371. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  81372. }
  81373. this._webvrViewMatrix.invert();
  81374. }
  81375. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  81376. return this._webvrViewMatrix;
  81377. };
  81378. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  81379. var _this = this;
  81380. var parentCamera = this.parent;
  81381. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  81382. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  81383. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  81384. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  81385. //babylon compatible matrix
  81386. if (!this.getScene().useRightHandedSystem) {
  81387. [8, 9, 10, 11].forEach(function (num) {
  81388. _this._projectionMatrix.m[num] *= -1;
  81389. });
  81390. }
  81391. return this._projectionMatrix;
  81392. };
  81393. /**
  81394. * Initializes the controllers and their meshes
  81395. */
  81396. WebVRFreeCamera.prototype.initControllers = function () {
  81397. var _this = this;
  81398. this.controllers = [];
  81399. var manager = this.getScene().gamepadManager;
  81400. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  81401. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  81402. var webVrController = gamepad;
  81403. if (webVrController.defaultModel) {
  81404. webVrController.defaultModel.setEnabled(false);
  81405. }
  81406. if (webVrController.hand === "right") {
  81407. _this._rightController = null;
  81408. }
  81409. if (webVrController.hand === "left") {
  81410. _this._leftController = null;
  81411. }
  81412. var controllerIndex = _this.controllers.indexOf(webVrController);
  81413. if (controllerIndex !== -1) {
  81414. _this.controllers.splice(controllerIndex, 1);
  81415. }
  81416. }
  81417. });
  81418. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  81419. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  81420. var webVrController_1 = gamepad;
  81421. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  81422. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  81423. if (_this.webVROptions.controllerMeshes) {
  81424. if (webVrController_1.defaultModel) {
  81425. webVrController_1.defaultModel.setEnabled(true);
  81426. }
  81427. else {
  81428. // Load the meshes
  81429. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  81430. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  81431. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  81432. if (_this.webVROptions.defaultLightingOnControllers) {
  81433. if (!_this._lightOnControllers) {
  81434. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  81435. }
  81436. var activateLightOnSubMeshes_1 = function (mesh, light) {
  81437. var children = mesh.getChildren();
  81438. if (children.length !== 0) {
  81439. children.forEach(function (mesh) {
  81440. light.includedOnlyMeshes.push(mesh);
  81441. activateLightOnSubMeshes_1(mesh, light);
  81442. });
  81443. }
  81444. };
  81445. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  81446. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  81447. }
  81448. });
  81449. }
  81450. }
  81451. webVrController_1.attachToPoseControlledCamera(_this);
  81452. // since this is async - sanity check. Is the controller already stored?
  81453. if (_this.controllers.indexOf(webVrController_1) === -1) {
  81454. //add to the controllers array
  81455. _this.controllers.push(webVrController_1);
  81456. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  81457. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  81458. // So we're overriding setting left & right manually to be sure
  81459. var firstViveWandDetected = false;
  81460. for (var i = 0; i < _this.controllers.length; i++) {
  81461. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  81462. if (!firstViveWandDetected) {
  81463. firstViveWandDetected = true;
  81464. _this.controllers[i].hand = "left";
  81465. }
  81466. else {
  81467. _this.controllers[i].hand = "right";
  81468. }
  81469. }
  81470. }
  81471. //did we find enough controllers? Great! let the developer know.
  81472. if (_this.controllers.length >= 2) {
  81473. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  81474. }
  81475. }
  81476. }
  81477. });
  81478. };
  81479. return WebVRFreeCamera;
  81480. }(BABYLON.FreeCamera));
  81481. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  81482. })(BABYLON || (BABYLON = {}));
  81483. //# sourceMappingURL=babylon.webVRCamera.js.map
  81484. var BABYLON;
  81485. (function (BABYLON) {
  81486. // We're mainly based on the logic defined into the FreeCamera code
  81487. /**
  81488. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  81489. * being tilted forward or back and left or right.
  81490. */
  81491. var DeviceOrientationCamera = /** @class */ (function (_super) {
  81492. __extends(DeviceOrientationCamera, _super);
  81493. /**
  81494. * Creates a new device orientation camera. @see DeviceOrientationCamera
  81495. * @param name The name of the camera
  81496. * @param position The start position camera
  81497. * @param scene The scene the camera belongs to
  81498. */
  81499. function DeviceOrientationCamera(name, position, scene) {
  81500. var _this = _super.call(this, name, position, scene) || this;
  81501. _this._quaternionCache = new BABYLON.Quaternion();
  81502. _this.inputs.addDeviceOrientation();
  81503. return _this;
  81504. }
  81505. /**
  81506. * Gets the current instance class name ("DeviceOrientationCamera").
  81507. * This helps avoiding instanceof at run time.
  81508. * @returns the class name
  81509. */
  81510. DeviceOrientationCamera.prototype.getClassName = function () {
  81511. return "DeviceOrientationCamera";
  81512. };
  81513. /**
  81514. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  81515. */
  81516. DeviceOrientationCamera.prototype._checkInputs = function () {
  81517. _super.prototype._checkInputs.call(this);
  81518. this._quaternionCache.copyFrom(this.rotationQuaternion);
  81519. if (this._initialQuaternion) {
  81520. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  81521. }
  81522. };
  81523. /**
  81524. * Reset the camera to its default orientation on the specified axis only.
  81525. * @param axis The axis to reset
  81526. */
  81527. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  81528. var _this = this;
  81529. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  81530. //can only work if this camera has a rotation quaternion already.
  81531. if (!this.rotationQuaternion)
  81532. return;
  81533. if (!this._initialQuaternion) {
  81534. this._initialQuaternion = new BABYLON.Quaternion();
  81535. }
  81536. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  81537. ['x', 'y', 'z'].forEach(function (axisName) {
  81538. if (!axis[axisName]) {
  81539. _this._initialQuaternion[axisName] = 0;
  81540. }
  81541. else {
  81542. _this._initialQuaternion[axisName] *= -1;
  81543. }
  81544. });
  81545. this._initialQuaternion.normalize();
  81546. //force rotation update
  81547. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  81548. };
  81549. return DeviceOrientationCamera;
  81550. }(BABYLON.FreeCamera));
  81551. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  81552. })(BABYLON || (BABYLON = {}));
  81553. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  81554. var BABYLON;
  81555. (function (BABYLON) {
  81556. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  81557. __extends(VRDeviceOrientationFreeCamera, _super);
  81558. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  81559. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81560. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81561. var _this = _super.call(this, name, position, scene) || this;
  81562. vrCameraMetrics.compensateDistortion = compensateDistortion;
  81563. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  81564. return _this;
  81565. }
  81566. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  81567. return "VRDeviceOrientationFreeCamera";
  81568. };
  81569. return VRDeviceOrientationFreeCamera;
  81570. }(BABYLON.DeviceOrientationCamera));
  81571. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  81572. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  81573. __extends(VRDeviceOrientationGamepadCamera, _super);
  81574. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  81575. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81576. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81577. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  81578. _this.inputs.addGamepad();
  81579. return _this;
  81580. }
  81581. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  81582. return "VRDeviceOrientationGamepadCamera";
  81583. };
  81584. return VRDeviceOrientationGamepadCamera;
  81585. }(VRDeviceOrientationFreeCamera));
  81586. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  81587. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  81588. __extends(VRDeviceOrientationArcRotateCamera, _super);
  81589. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  81590. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81591. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81592. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81593. vrCameraMetrics.compensateDistortion = compensateDistortion;
  81594. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  81595. _this.inputs.addVRDeviceOrientation();
  81596. return _this;
  81597. }
  81598. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  81599. return "VRDeviceOrientationArcRotateCamera";
  81600. };
  81601. return VRDeviceOrientationArcRotateCamera;
  81602. }(BABYLON.ArcRotateCamera));
  81603. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  81604. })(BABYLON || (BABYLON = {}));
  81605. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  81606. var BABYLON;
  81607. (function (BABYLON) {
  81608. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  81609. __extends(AnaglyphFreeCamera, _super);
  81610. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  81611. var _this = _super.call(this, name, position, scene) || this;
  81612. _this.interaxialDistance = interaxialDistance;
  81613. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81614. return _this;
  81615. }
  81616. AnaglyphFreeCamera.prototype.getClassName = function () {
  81617. return "AnaglyphFreeCamera";
  81618. };
  81619. return AnaglyphFreeCamera;
  81620. }(BABYLON.FreeCamera));
  81621. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  81622. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  81623. __extends(AnaglyphArcRotateCamera, _super);
  81624. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  81625. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81626. _this.interaxialDistance = interaxialDistance;
  81627. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81628. return _this;
  81629. }
  81630. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  81631. return "AnaglyphArcRotateCamera";
  81632. };
  81633. return AnaglyphArcRotateCamera;
  81634. }(BABYLON.ArcRotateCamera));
  81635. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  81636. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  81637. __extends(AnaglyphGamepadCamera, _super);
  81638. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  81639. var _this = _super.call(this, name, position, scene) || this;
  81640. _this.interaxialDistance = interaxialDistance;
  81641. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81642. return _this;
  81643. }
  81644. AnaglyphGamepadCamera.prototype.getClassName = function () {
  81645. return "AnaglyphGamepadCamera";
  81646. };
  81647. return AnaglyphGamepadCamera;
  81648. }(BABYLON.GamepadCamera));
  81649. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  81650. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  81651. __extends(AnaglyphUniversalCamera, _super);
  81652. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  81653. var _this = _super.call(this, name, position, scene) || this;
  81654. _this.interaxialDistance = interaxialDistance;
  81655. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81656. return _this;
  81657. }
  81658. AnaglyphUniversalCamera.prototype.getClassName = function () {
  81659. return "AnaglyphUniversalCamera";
  81660. };
  81661. return AnaglyphUniversalCamera;
  81662. }(BABYLON.UniversalCamera));
  81663. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  81664. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  81665. __extends(StereoscopicFreeCamera, _super);
  81666. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81667. var _this = _super.call(this, name, position, scene) || this;
  81668. _this.interaxialDistance = interaxialDistance;
  81669. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81670. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81671. return _this;
  81672. }
  81673. StereoscopicFreeCamera.prototype.getClassName = function () {
  81674. return "StereoscopicFreeCamera";
  81675. };
  81676. return StereoscopicFreeCamera;
  81677. }(BABYLON.FreeCamera));
  81678. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  81679. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  81680. __extends(StereoscopicArcRotateCamera, _super);
  81681. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  81682. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81683. _this.interaxialDistance = interaxialDistance;
  81684. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81685. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81686. return _this;
  81687. }
  81688. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  81689. return "StereoscopicArcRotateCamera";
  81690. };
  81691. return StereoscopicArcRotateCamera;
  81692. }(BABYLON.ArcRotateCamera));
  81693. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  81694. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  81695. __extends(StereoscopicGamepadCamera, _super);
  81696. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81697. var _this = _super.call(this, name, position, scene) || this;
  81698. _this.interaxialDistance = interaxialDistance;
  81699. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81700. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81701. return _this;
  81702. }
  81703. StereoscopicGamepadCamera.prototype.getClassName = function () {
  81704. return "StereoscopicGamepadCamera";
  81705. };
  81706. return StereoscopicGamepadCamera;
  81707. }(BABYLON.GamepadCamera));
  81708. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  81709. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  81710. __extends(StereoscopicUniversalCamera, _super);
  81711. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81712. var _this = _super.call(this, name, position, scene) || this;
  81713. _this.interaxialDistance = interaxialDistance;
  81714. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81715. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81716. return _this;
  81717. }
  81718. StereoscopicUniversalCamera.prototype.getClassName = function () {
  81719. return "StereoscopicUniversalCamera";
  81720. };
  81721. return StereoscopicUniversalCamera;
  81722. }(BABYLON.UniversalCamera));
  81723. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  81724. })(BABYLON || (BABYLON = {}));
  81725. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  81726. var BABYLON;
  81727. (function (BABYLON) {
  81728. var VRExperienceHelperGazer = /** @class */ (function () {
  81729. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  81730. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  81731. this.scene = scene;
  81732. this._pointerDownOnMeshAsked = false;
  81733. this._isActionableMesh = false;
  81734. this._teleportationRequestInitiated = false;
  81735. this._teleportationBackRequestInitiated = false;
  81736. this._dpadPressed = true;
  81737. this._activePointer = false;
  81738. this._id = VRExperienceHelperGazer._idCounter++;
  81739. // Gaze tracker
  81740. if (!gazeTrackerToClone) {
  81741. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  81742. this._gazeTracker.bakeCurrentTransformIntoVertices();
  81743. this._gazeTracker.isPickable = false;
  81744. this._gazeTracker.isVisible = false;
  81745. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  81746. targetMat.specularColor = BABYLON.Color3.Black();
  81747. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  81748. targetMat.backFaceCulling = false;
  81749. this._gazeTracker.material = targetMat;
  81750. }
  81751. else {
  81752. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  81753. }
  81754. }
  81755. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  81756. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  81757. };
  81758. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  81759. this._pointerDownOnMeshAsked = true;
  81760. if (this._currentMeshSelected && this._currentHit) {
  81761. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  81762. }
  81763. };
  81764. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  81765. if (this._currentMeshSelected && this._currentHit) {
  81766. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  81767. }
  81768. this._pointerDownOnMeshAsked = false;
  81769. };
  81770. VRExperienceHelperGazer.prototype._activatePointer = function () {
  81771. this._activePointer = true;
  81772. };
  81773. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  81774. this._activePointer = false;
  81775. };
  81776. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  81777. };
  81778. VRExperienceHelperGazer.prototype.dispose = function () {
  81779. this._interactionsEnabled = false;
  81780. this._teleportationEnabled = false;
  81781. };
  81782. VRExperienceHelperGazer._idCounter = 0;
  81783. return VRExperienceHelperGazer;
  81784. }());
  81785. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  81786. __extends(VRExperienceHelperControllerGazer, _super);
  81787. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  81788. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  81789. _this.webVRController = webVRController;
  81790. // Laser pointer
  81791. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  81792. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  81793. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  81794. laserPointerMaterial.alpha = 0.6;
  81795. _this._laserPointer.material = laserPointerMaterial;
  81796. _this._laserPointer.rotation.x = Math.PI / 2;
  81797. _this._laserPointer.position.z = -0.5;
  81798. _this._laserPointer.isVisible = false;
  81799. if (!webVRController.mesh) {
  81800. // Create an empty mesh that is used prior to loading the high quality model
  81801. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  81802. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  81803. preloadPointerPose.rotation.x = -0.7;
  81804. preloadMesh.addChild(preloadPointerPose);
  81805. webVRController.attachToMesh(preloadMesh);
  81806. }
  81807. _this._setLaserPointerParent(webVRController.mesh);
  81808. return _this;
  81809. }
  81810. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  81811. return this.webVRController.getForwardRay(length);
  81812. };
  81813. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  81814. _super.prototype._activatePointer.call(this);
  81815. this._laserPointer.isVisible = true;
  81816. };
  81817. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  81818. _super.prototype._deactivatePointer.call(this);
  81819. this._laserPointer.isVisible = false;
  81820. };
  81821. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  81822. this._laserPointer.material.emissiveColor = color;
  81823. };
  81824. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  81825. var makeNotPick = function (root) {
  81826. root.name += " laserPointer";
  81827. root.getChildMeshes().forEach(function (c) {
  81828. makeNotPick(c);
  81829. });
  81830. };
  81831. makeNotPick(mesh);
  81832. var childMeshes = mesh.getChildMeshes();
  81833. this.webVRController._pointingPoseNode = null;
  81834. for (var i = 0; i < childMeshes.length; i++) {
  81835. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  81836. mesh = childMeshes[i];
  81837. this.webVRController._pointingPoseNode = mesh;
  81838. break;
  81839. }
  81840. }
  81841. this._laserPointer.parent = mesh;
  81842. };
  81843. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  81844. this._laserPointer.scaling.y = distance;
  81845. this._laserPointer.position.z = -distance / 2;
  81846. };
  81847. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  81848. _super.prototype.dispose.call(this);
  81849. this._laserPointer.dispose();
  81850. };
  81851. return VRExperienceHelperControllerGazer;
  81852. }(VRExperienceHelperGazer));
  81853. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  81854. __extends(VRExperienceHelperCameraGazer, _super);
  81855. function VRExperienceHelperCameraGazer(getCamera, scene) {
  81856. var _this = _super.call(this, scene) || this;
  81857. _this.getCamera = getCamera;
  81858. return _this;
  81859. }
  81860. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  81861. var camera = this.getCamera();
  81862. if (camera) {
  81863. return camera.getForwardRay(length);
  81864. }
  81865. else {
  81866. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  81867. }
  81868. };
  81869. return VRExperienceHelperCameraGazer;
  81870. }(VRExperienceHelperGazer));
  81871. /**
  81872. * Helps to quickly add VR support to an existing scene.
  81873. * See http://doc.babylonjs.com/how_to/webvr_helper
  81874. */
  81875. var VRExperienceHelper = /** @class */ (function () {
  81876. /**
  81877. * Instantiates a VRExperienceHelper.
  81878. * Helps to quickly add VR support to an existing scene.
  81879. * @param scene The scene the VRExperienceHelper belongs to.
  81880. * @param webVROptions Options to modify the vr experience helper's behavior.
  81881. */
  81882. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  81883. if (webVROptions === void 0) { webVROptions = {}; }
  81884. var _this = this;
  81885. this.webVROptions = webVROptions;
  81886. // Can the system support WebVR, even if a headset isn't plugged in?
  81887. this._webVRsupported = false;
  81888. // If WebVR is supported, is a headset plugged in and are we ready to present?
  81889. this._webVRready = false;
  81890. // Are we waiting for the requestPresent callback to complete?
  81891. this._webVRrequesting = false;
  81892. // Are we presenting to the headset right now?
  81893. this._webVRpresenting = false;
  81894. // Are we presenting in the fullscreen fallback?
  81895. this._fullscreenVRpresenting = false;
  81896. /**
  81897. * Observable raised when entering VR.
  81898. */
  81899. this.onEnteringVRObservable = new BABYLON.Observable();
  81900. /**
  81901. * Observable raised when exiting VR.
  81902. */
  81903. this.onExitingVRObservable = new BABYLON.Observable();
  81904. /**
  81905. * Observable raised when controller mesh is loaded.
  81906. */
  81907. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  81908. this._useCustomVRButton = false;
  81909. this._teleportationRequested = false;
  81910. this._teleportActive = false;
  81911. this._floorMeshesCollection = [];
  81912. this._rotationAllowed = true;
  81913. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  81914. this._rotationRightAsked = false;
  81915. this._rotationLeftAsked = false;
  81916. this._isDefaultTeleportationTarget = true;
  81917. this._teleportationFillColor = "#444444";
  81918. this._teleportationBorderColor = "#FFFFFF";
  81919. this._rotationAngle = 0;
  81920. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  81921. this._padSensibilityUp = 0.65;
  81922. this._padSensibilityDown = 0.35;
  81923. this.leftController = null;
  81924. this.rightController = null;
  81925. /**
  81926. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  81927. */
  81928. this.onNewMeshSelected = new BABYLON.Observable();
  81929. /**
  81930. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  81931. */
  81932. this.onNewMeshPicked = new BABYLON.Observable();
  81933. /**
  81934. * Observable raised before camera teleportation
  81935. */
  81936. this.onBeforeCameraTeleport = new BABYLON.Observable();
  81937. /**
  81938. * Observable raised after camera teleportation
  81939. */
  81940. this.onAfterCameraTeleport = new BABYLON.Observable();
  81941. /**
  81942. * Observable raised when current selected mesh gets unselected
  81943. */
  81944. this.onSelectedMeshUnselected = new BABYLON.Observable();
  81945. /**
  81946. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  81947. */
  81948. this.teleportationEnabled = true;
  81949. this._teleportationInitialized = false;
  81950. this._interactionsEnabled = false;
  81951. this._interactionsRequested = false;
  81952. this._displayGaze = true;
  81953. this._displayLaserPointer = true;
  81954. this._onResize = function () {
  81955. _this.moveButtonToBottomRight();
  81956. if (_this._fullscreenVRpresenting && _this._webVRready) {
  81957. _this.exitVR();
  81958. }
  81959. };
  81960. this._onFullscreenChange = function () {
  81961. if (document.fullscreen !== undefined) {
  81962. _this._fullscreenVRpresenting = document.fullscreen;
  81963. }
  81964. else if (document.mozFullScreen !== undefined) {
  81965. _this._fullscreenVRpresenting = document.mozFullScreen;
  81966. }
  81967. else if (document.webkitIsFullScreen !== undefined) {
  81968. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  81969. }
  81970. else if (document.msIsFullScreen !== undefined) {
  81971. _this._fullscreenVRpresenting = document.msIsFullScreen;
  81972. }
  81973. if (!_this._fullscreenVRpresenting && _this._canvas) {
  81974. _this.exitVR();
  81975. if (!_this._useCustomVRButton) {
  81976. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  81977. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  81978. }
  81979. }
  81980. };
  81981. this.beforeRender = function () {
  81982. if (_this.leftController && _this.leftController._activePointer) {
  81983. _this._castRayAndSelectObject(_this.leftController);
  81984. }
  81985. if (_this.rightController && _this.rightController._activePointer) {
  81986. _this._castRayAndSelectObject(_this.rightController);
  81987. }
  81988. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  81989. _this._castRayAndSelectObject(_this._cameraGazer);
  81990. }
  81991. else {
  81992. _this._cameraGazer._gazeTracker.isVisible = false;
  81993. }
  81994. };
  81995. this._onNewGamepadConnected = function (gamepad) {
  81996. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  81997. if (gamepad.leftStick) {
  81998. gamepad.onleftstickchanged(function (stickValues) {
  81999. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  82000. // Listening to classic/xbox gamepad only if no VR controller is active
  82001. if ((!_this.leftController && !_this.rightController) ||
  82002. ((_this.leftController && !_this.leftController._activePointer) &&
  82003. (_this.rightController && !_this.rightController._activePointer))) {
  82004. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  82005. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  82006. }
  82007. }
  82008. });
  82009. }
  82010. if (gamepad.rightStick) {
  82011. gamepad.onrightstickchanged(function (stickValues) {
  82012. if (_this._teleportationInitialized) {
  82013. _this._checkRotate(stickValues, _this._cameraGazer);
  82014. }
  82015. });
  82016. }
  82017. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  82018. gamepad.onbuttondown(function (buttonPressed) {
  82019. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  82020. _this._cameraGazer._selectionPointerDown();
  82021. }
  82022. });
  82023. gamepad.onbuttonup(function (buttonPressed) {
  82024. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  82025. _this._cameraGazer._selectionPointerUp();
  82026. }
  82027. });
  82028. }
  82029. }
  82030. else {
  82031. var webVRController = gamepad;
  82032. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  82033. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  82034. _this.rightController = controller;
  82035. }
  82036. else {
  82037. _this.leftController = controller;
  82038. }
  82039. _this._tryEnableInteractionOnController(controller);
  82040. }
  82041. };
  82042. // 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
  82043. this._tryEnableInteractionOnController = function (controller) {
  82044. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  82045. _this._enableInteractionOnController(controller);
  82046. }
  82047. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  82048. _this._enableTeleportationOnController(controller);
  82049. }
  82050. };
  82051. this._onNewGamepadDisconnected = function (gamepad) {
  82052. if (gamepad instanceof BABYLON.WebVRController) {
  82053. if (gamepad.hand === "left" && _this.leftController != null) {
  82054. _this.leftController.dispose();
  82055. _this.leftController = null;
  82056. }
  82057. if (gamepad.hand === "right" && _this.rightController != null) {
  82058. _this.rightController.dispose();
  82059. _this.rightController = null;
  82060. }
  82061. }
  82062. };
  82063. this._workingVector = BABYLON.Vector3.Zero();
  82064. this._workingQuaternion = BABYLON.Quaternion.Identity();
  82065. this._workingMatrix = BABYLON.Matrix.Identity();
  82066. this._scene = scene;
  82067. this._canvas = scene.getEngine().getRenderingCanvas();
  82068. // Parse options
  82069. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  82070. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  82071. }
  82072. if (webVROptions.createDeviceOrientationCamera === undefined) {
  82073. webVROptions.createDeviceOrientationCamera = true;
  82074. }
  82075. if (webVROptions.defaultHeight === undefined) {
  82076. webVROptions.defaultHeight = 1.7;
  82077. }
  82078. if (webVROptions.useCustomVRButton) {
  82079. this._useCustomVRButton = true;
  82080. if (webVROptions.customVRButton) {
  82081. this._btnVR = webVROptions.customVRButton;
  82082. }
  82083. }
  82084. if (webVROptions.rayLength) {
  82085. this._rayLength = webVROptions.rayLength;
  82086. }
  82087. this._defaultHeight = webVROptions.defaultHeight;
  82088. if (webVROptions.positionScale) {
  82089. this._rayLength *= webVROptions.positionScale;
  82090. this._defaultHeight *= webVROptions.positionScale;
  82091. }
  82092. // Set position
  82093. if (this._scene.activeCamera) {
  82094. this._position = this._scene.activeCamera.position.clone();
  82095. }
  82096. else {
  82097. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  82098. }
  82099. // Set non-vr camera
  82100. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  82101. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  82102. // Copy data from existing camera
  82103. if (this._scene.activeCamera) {
  82104. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  82105. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  82106. // Set rotation from previous camera
  82107. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  82108. var targetCamera = this._scene.activeCamera;
  82109. if (targetCamera.rotationQuaternion) {
  82110. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  82111. }
  82112. else {
  82113. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  82114. }
  82115. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  82116. }
  82117. }
  82118. this._scene.activeCamera = this._deviceOrientationCamera;
  82119. if (this._canvas) {
  82120. this._scene.activeCamera.attachControl(this._canvas);
  82121. }
  82122. }
  82123. else {
  82124. this._existingCamera = this._scene.activeCamera;
  82125. }
  82126. // Create VR cameras
  82127. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82128. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  82129. }
  82130. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  82131. this._webVRCamera.useStandingMatrix();
  82132. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  82133. // Create default button
  82134. if (!this._useCustomVRButton) {
  82135. this._btnVR = document.createElement("BUTTON");
  82136. this._btnVR.className = "babylonVRicon";
  82137. this._btnVR.id = "babylonVRiconbtn";
  82138. this._btnVR.title = "Click to switch to VR";
  82139. 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) }";
  82140. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  82141. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  82142. // css += ".babylonVRicon.vrdisplaysupported { }";
  82143. // css += ".babylonVRicon.vrdisplayready { }";
  82144. // css += ".babylonVRicon.vrdisplayrequesting { }";
  82145. var style = document.createElement('style');
  82146. style.appendChild(document.createTextNode(css));
  82147. document.getElementsByTagName('head')[0].appendChild(style);
  82148. this.moveButtonToBottomRight();
  82149. }
  82150. // VR button click event
  82151. if (this._btnVR) {
  82152. this._btnVR.addEventListener("click", function () {
  82153. if (!_this.isInVRMode) {
  82154. _this.enterVR();
  82155. }
  82156. else {
  82157. _this.exitVR();
  82158. }
  82159. });
  82160. }
  82161. // Window events
  82162. window.addEventListener("resize", this._onResize);
  82163. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  82164. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  82165. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  82166. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  82167. // Display vr button when headset is connected
  82168. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82169. this.displayVRButton();
  82170. }
  82171. else {
  82172. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  82173. if (e.vrDisplay) {
  82174. _this.displayVRButton();
  82175. }
  82176. });
  82177. }
  82178. // Exiting VR mode using 'ESC' key on desktop
  82179. this._onKeyDown = function (event) {
  82180. if (event.keyCode === 27 && _this.isInVRMode) {
  82181. _this.exitVR();
  82182. }
  82183. };
  82184. document.addEventListener("keydown", this._onKeyDown);
  82185. // Exiting VR mode double tapping the touch screen
  82186. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  82187. if (_this.isInVRMode) {
  82188. _this.exitVR();
  82189. if (_this._fullscreenVRpresenting) {
  82190. _this._scene.getEngine().switchFullscreen(true);
  82191. }
  82192. }
  82193. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  82194. // Listen for WebVR display changes
  82195. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  82196. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  82197. this._onVRRequestPresentStart = function () {
  82198. _this._webVRrequesting = true;
  82199. _this.updateButtonVisibility();
  82200. };
  82201. this._onVRRequestPresentComplete = function (success) {
  82202. _this._webVRrequesting = false;
  82203. _this.updateButtonVisibility();
  82204. };
  82205. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  82206. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  82207. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  82208. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82209. scene.onDisposeObservable.add(function () {
  82210. _this.dispose();
  82211. });
  82212. // Gamepad connection events
  82213. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  82214. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  82215. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  82216. this.updateButtonVisibility();
  82217. //create easing functions
  82218. this._circleEase = new BABYLON.CircleEase();
  82219. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  82220. }
  82221. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  82222. /** Return this.onEnteringVRObservable
  82223. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  82224. */
  82225. get: function () {
  82226. return this.onEnteringVRObservable;
  82227. },
  82228. enumerable: true,
  82229. configurable: true
  82230. });
  82231. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  82232. /** Return this.onExitingVRObservable
  82233. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  82234. */
  82235. get: function () {
  82236. return this.onExitingVRObservable;
  82237. },
  82238. enumerable: true,
  82239. configurable: true
  82240. });
  82241. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  82242. /** Return this.onControllerMeshLoadedObservable
  82243. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  82244. */
  82245. get: function () {
  82246. return this.onControllerMeshLoadedObservable;
  82247. },
  82248. enumerable: true,
  82249. configurable: true
  82250. });
  82251. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  82252. /**
  82253. * The mesh used to display where the user is going to teleport.
  82254. */
  82255. get: function () {
  82256. return this._teleportationTarget;
  82257. },
  82258. /**
  82259. * Sets the mesh to be used to display where the user is going to teleport.
  82260. */
  82261. set: function (value) {
  82262. if (value) {
  82263. value.name = "teleportationTarget";
  82264. this._isDefaultTeleportationTarget = false;
  82265. this._teleportationTarget = value;
  82266. }
  82267. },
  82268. enumerable: true,
  82269. configurable: true
  82270. });
  82271. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  82272. /**
  82273. * The mesh used to display where the user is selecting,
  82274. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  82275. * See http://doc.babylonjs.com/resources/baking_transformations
  82276. */
  82277. get: function () {
  82278. return this._cameraGazer._gazeTracker;
  82279. },
  82280. set: function (value) {
  82281. if (value) {
  82282. this._cameraGazer._gazeTracker = value;
  82283. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  82284. this._cameraGazer._gazeTracker.isPickable = false;
  82285. this._cameraGazer._gazeTracker.isVisible = false;
  82286. this._cameraGazer._gazeTracker.name = "gazeTracker";
  82287. if (this.leftController) {
  82288. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82289. }
  82290. if (this.rightController) {
  82291. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82292. }
  82293. }
  82294. },
  82295. enumerable: true,
  82296. configurable: true
  82297. });
  82298. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  82299. /**
  82300. * If the ray of the gaze should be displayed.
  82301. */
  82302. get: function () {
  82303. return this._displayGaze;
  82304. },
  82305. /**
  82306. * Sets if the ray of the gaze should be displayed.
  82307. */
  82308. set: function (value) {
  82309. this._displayGaze = value;
  82310. if (!value) {
  82311. this._cameraGazer._gazeTracker.isVisible = false;
  82312. if (this.leftController) {
  82313. this.leftController._gazeTracker.isVisible = false;
  82314. }
  82315. if (this.rightController) {
  82316. this.rightController._gazeTracker.isVisible = false;
  82317. }
  82318. }
  82319. },
  82320. enumerable: true,
  82321. configurable: true
  82322. });
  82323. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  82324. /**
  82325. * If the ray of the LaserPointer should be displayed.
  82326. */
  82327. get: function () {
  82328. return this._displayLaserPointer;
  82329. },
  82330. /**
  82331. * Sets if the ray of the LaserPointer should be displayed.
  82332. */
  82333. set: function (value) {
  82334. this._displayLaserPointer = value;
  82335. if (!value) {
  82336. if (this.rightController) {
  82337. this.rightController._deactivatePointer();
  82338. this.rightController._gazeTracker.isVisible = false;
  82339. }
  82340. if (this.leftController) {
  82341. this.leftController._deactivatePointer();
  82342. this.leftController._gazeTracker.isVisible = false;
  82343. }
  82344. }
  82345. else {
  82346. if (this.rightController) {
  82347. this.rightController._activatePointer();
  82348. }
  82349. else if (this.leftController) {
  82350. this.leftController._activatePointer();
  82351. }
  82352. }
  82353. },
  82354. enumerable: true,
  82355. configurable: true
  82356. });
  82357. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  82358. /**
  82359. * The deviceOrientationCamera used as the camera when not in VR.
  82360. */
  82361. get: function () {
  82362. return this._deviceOrientationCamera;
  82363. },
  82364. enumerable: true,
  82365. configurable: true
  82366. });
  82367. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  82368. /**
  82369. * Based on the current WebVR support, returns the current VR camera used.
  82370. */
  82371. get: function () {
  82372. if (this._webVRready) {
  82373. return this._webVRCamera;
  82374. }
  82375. else {
  82376. return this._scene.activeCamera;
  82377. }
  82378. },
  82379. enumerable: true,
  82380. configurable: true
  82381. });
  82382. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  82383. /**
  82384. * The webVRCamera which is used when in VR.
  82385. */
  82386. get: function () {
  82387. return this._webVRCamera;
  82388. },
  82389. enumerable: true,
  82390. configurable: true
  82391. });
  82392. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  82393. /**
  82394. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  82395. */
  82396. get: function () {
  82397. return this._vrDeviceOrientationCamera;
  82398. },
  82399. enumerable: true,
  82400. configurable: true
  82401. });
  82402. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  82403. get: function () {
  82404. var result = this._cameraGazer._teleportationRequestInitiated
  82405. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  82406. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  82407. return result;
  82408. },
  82409. enumerable: true,
  82410. configurable: true
  82411. });
  82412. // Raised when one of the controller has loaded successfully its associated default mesh
  82413. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  82414. if (this.leftController && this.leftController.webVRController == webVRController) {
  82415. if (webVRController.mesh) {
  82416. this.leftController._setLaserPointerParent(webVRController.mesh);
  82417. }
  82418. }
  82419. if (this.rightController && this.rightController.webVRController == webVRController) {
  82420. if (webVRController.mesh) {
  82421. this.rightController._setLaserPointerParent(webVRController.mesh);
  82422. }
  82423. }
  82424. try {
  82425. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  82426. }
  82427. catch (err) {
  82428. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  82429. }
  82430. };
  82431. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  82432. /**
  82433. * Gets a value indicating if we are currently in VR mode.
  82434. */
  82435. get: function () {
  82436. return this._webVRpresenting || this._fullscreenVRpresenting;
  82437. },
  82438. enumerable: true,
  82439. configurable: true
  82440. });
  82441. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  82442. var vrDisplay = this._scene.getEngine().getVRDevice();
  82443. if (vrDisplay) {
  82444. var wasPresenting = this._webVRpresenting;
  82445. // A VR display is connected
  82446. this._webVRpresenting = vrDisplay.isPresenting;
  82447. if (wasPresenting && !this._webVRpresenting)
  82448. this.exitVR();
  82449. }
  82450. else {
  82451. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  82452. }
  82453. this.updateButtonVisibility();
  82454. };
  82455. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  82456. this._webVRsupported = eventArgs.vrSupported;
  82457. this._webVRready = !!eventArgs.vrDisplay;
  82458. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  82459. this.updateButtonVisibility();
  82460. };
  82461. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  82462. if (this._canvas && !this._useCustomVRButton) {
  82463. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  82464. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  82465. }
  82466. };
  82467. VRExperienceHelper.prototype.displayVRButton = function () {
  82468. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  82469. document.body.appendChild(this._btnVR);
  82470. this._btnVRDisplayed = true;
  82471. }
  82472. };
  82473. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  82474. if (!this._btnVR || this._useCustomVRButton) {
  82475. return;
  82476. }
  82477. this._btnVR.className = "babylonVRicon";
  82478. if (this.isInVRMode) {
  82479. this._btnVR.className += " vrdisplaypresenting";
  82480. }
  82481. else {
  82482. if (this._webVRready)
  82483. this._btnVR.className += " vrdisplayready";
  82484. if (this._webVRsupported)
  82485. this._btnVR.className += " vrdisplaysupported";
  82486. if (this._webVRrequesting)
  82487. this._btnVR.className += " vrdisplayrequesting";
  82488. }
  82489. };
  82490. /**
  82491. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  82492. * Otherwise, will use the fullscreen API.
  82493. */
  82494. VRExperienceHelper.prototype.enterVR = function () {
  82495. if (this.onEnteringVRObservable) {
  82496. try {
  82497. this.onEnteringVRObservable.notifyObservers(this);
  82498. }
  82499. catch (err) {
  82500. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  82501. }
  82502. }
  82503. if (this._scene.activeCamera) {
  82504. this._position = this._scene.activeCamera.position.clone();
  82505. // make sure that we return to the last active camera
  82506. this._existingCamera = this._scene.activeCamera;
  82507. }
  82508. if (this._webVRrequesting)
  82509. return;
  82510. // If WebVR is supported and a headset is connected
  82511. if (this._webVRready) {
  82512. if (!this._webVRpresenting) {
  82513. this._webVRCamera.position = this._position;
  82514. this._scene.activeCamera = this._webVRCamera;
  82515. }
  82516. }
  82517. else if (this._vrDeviceOrientationCamera) {
  82518. this._vrDeviceOrientationCamera.position = this._position;
  82519. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  82520. this._scene.getEngine().switchFullscreen(true);
  82521. this.updateButtonVisibility();
  82522. }
  82523. if (this._scene.activeCamera && this._canvas) {
  82524. this._scene.activeCamera.attachControl(this._canvas);
  82525. }
  82526. if (this._interactionsEnabled) {
  82527. this._scene.registerBeforeRender(this.beforeRender);
  82528. }
  82529. };
  82530. /**
  82531. * Attempt to exit VR, or fullscreen.
  82532. */
  82533. VRExperienceHelper.prototype.exitVR = function () {
  82534. if (this.onExitingVRObservable) {
  82535. try {
  82536. this.onExitingVRObservable.notifyObservers(this);
  82537. }
  82538. catch (err) {
  82539. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  82540. }
  82541. }
  82542. if (this._webVRpresenting) {
  82543. this._scene.getEngine().disableVR();
  82544. }
  82545. if (this._scene.activeCamera) {
  82546. this._position = this._scene.activeCamera.position.clone();
  82547. }
  82548. if (this._deviceOrientationCamera) {
  82549. this._deviceOrientationCamera.position = this._position;
  82550. this._scene.activeCamera = this._deviceOrientationCamera;
  82551. if (this._canvas) {
  82552. this._scene.activeCamera.attachControl(this._canvas);
  82553. }
  82554. }
  82555. else if (this._existingCamera) {
  82556. this._existingCamera.position = this._position;
  82557. this._scene.activeCamera = this._existingCamera;
  82558. }
  82559. this.updateButtonVisibility();
  82560. if (this._interactionsEnabled) {
  82561. this._scene.unregisterBeforeRender(this.beforeRender);
  82562. }
  82563. };
  82564. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  82565. /**
  82566. * The position of the vr experience helper.
  82567. */
  82568. get: function () {
  82569. return this._position;
  82570. },
  82571. /**
  82572. * Sets the position of the vr experience helper.
  82573. */
  82574. set: function (value) {
  82575. this._position = value;
  82576. if (this._scene.activeCamera) {
  82577. this._scene.activeCamera.position = value;
  82578. }
  82579. },
  82580. enumerable: true,
  82581. configurable: true
  82582. });
  82583. /**
  82584. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  82585. */
  82586. VRExperienceHelper.prototype.enableInteractions = function () {
  82587. var _this = this;
  82588. if (!this._interactionsEnabled) {
  82589. this._interactionsRequested = true;
  82590. if (this.leftController) {
  82591. this._enableInteractionOnController(this.leftController);
  82592. }
  82593. if (this.rightController) {
  82594. this._enableInteractionOnController(this.rightController);
  82595. }
  82596. this.raySelectionPredicate = function (mesh) {
  82597. return mesh.isVisible;
  82598. };
  82599. this.meshSelectionPredicate = function (mesh) {
  82600. return true;
  82601. };
  82602. this._raySelectionPredicate = function (mesh) {
  82603. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  82604. && mesh.name.indexOf("teleportationTarget") === -1
  82605. && mesh.name.indexOf("torusTeleportation") === -1
  82606. && mesh.name.indexOf("laserPointer") === -1)) {
  82607. return _this.raySelectionPredicate(mesh);
  82608. }
  82609. return false;
  82610. };
  82611. this._interactionsEnabled = true;
  82612. }
  82613. };
  82614. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  82615. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  82616. if (this._floorMeshesCollection[i].id === mesh.id) {
  82617. return true;
  82618. }
  82619. }
  82620. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  82621. return true;
  82622. }
  82623. return false;
  82624. };
  82625. /**
  82626. * Adds a floor mesh to be used for teleportation.
  82627. * @param floorMesh the mesh to be used for teleportation.
  82628. */
  82629. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  82630. if (!this._floorMeshesCollection) {
  82631. return;
  82632. }
  82633. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  82634. return;
  82635. }
  82636. this._floorMeshesCollection.push(floorMesh);
  82637. };
  82638. /**
  82639. * Removes a floor mesh from being used for teleportation.
  82640. * @param floorMesh the mesh to be removed.
  82641. */
  82642. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  82643. if (!this._floorMeshesCollection) {
  82644. return;
  82645. }
  82646. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  82647. if (meshIndex !== -1) {
  82648. this._floorMeshesCollection.splice(meshIndex, 1);
  82649. }
  82650. };
  82651. /**
  82652. * Enables interactions and teleportation using the VR controllers and gaze.
  82653. * @param vrTeleportationOptions options to modify teleportation behavior.
  82654. */
  82655. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  82656. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  82657. if (!this._teleportationInitialized) {
  82658. this._teleportationRequested = true;
  82659. this.enableInteractions();
  82660. if (vrTeleportationOptions.floorMeshName) {
  82661. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  82662. }
  82663. if (vrTeleportationOptions.floorMeshes) {
  82664. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  82665. }
  82666. if (this.leftController != null) {
  82667. this._enableTeleportationOnController(this.leftController);
  82668. }
  82669. if (this.rightController != null) {
  82670. this._enableTeleportationOnController(this.rightController);
  82671. }
  82672. // Creates an image processing post process for the vignette not relying
  82673. // on the main scene configuration for image processing to reduce setup and spaces
  82674. // (gamma/linear) conflicts.
  82675. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  82676. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  82677. imageProcessingConfiguration.vignetteEnabled = true;
  82678. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  82679. this._webVRCamera.detachPostProcess(this._postProcessMove);
  82680. this._teleportationInitialized = true;
  82681. if (this._isDefaultTeleportationTarget) {
  82682. this._createTeleportationCircles();
  82683. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  82684. }
  82685. }
  82686. };
  82687. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  82688. var _this = this;
  82689. var controllerMesh = controller.webVRController.mesh;
  82690. if (controllerMesh) {
  82691. controller._interactionsEnabled = true;
  82692. controller._activatePointer();
  82693. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  82694. // Enabling / disabling laserPointer
  82695. if (_this._displayLaserPointer && stateObject.value === 1) {
  82696. if (controller._activePointer) {
  82697. controller._deactivatePointer();
  82698. }
  82699. else {
  82700. controller._activatePointer();
  82701. }
  82702. if (_this.displayGaze) {
  82703. controller._gazeTracker.isVisible = controller._activePointer;
  82704. }
  82705. }
  82706. });
  82707. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  82708. if (!controller._pointerDownOnMeshAsked) {
  82709. if (stateObject.value > _this._padSensibilityUp) {
  82710. controller._selectionPointerDown();
  82711. }
  82712. }
  82713. else if (stateObject.value < _this._padSensibilityDown) {
  82714. controller._selectionPointerUp();
  82715. }
  82716. });
  82717. }
  82718. };
  82719. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  82720. // Dont teleport if another gaze already requested teleportation
  82721. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  82722. return;
  82723. }
  82724. if (!gazer._teleportationRequestInitiated) {
  82725. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  82726. gazer._activatePointer();
  82727. gazer._teleportationRequestInitiated = true;
  82728. }
  82729. }
  82730. else {
  82731. // Listening to the proper controller values changes to confirm teleportation
  82732. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  82733. if (this._teleportActive) {
  82734. this._teleportCamera(this._haloCenter);
  82735. }
  82736. gazer._teleportationRequestInitiated = false;
  82737. }
  82738. }
  82739. };
  82740. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  82741. // Only rotate when user is not currently selecting a teleportation location
  82742. if (gazer._teleportationRequestInitiated) {
  82743. return;
  82744. }
  82745. if (!this._rotationLeftAsked) {
  82746. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  82747. this._rotationLeftAsked = true;
  82748. if (this._rotationAllowed) {
  82749. this._rotateCamera(false);
  82750. }
  82751. }
  82752. }
  82753. else {
  82754. if (stateObject.x > -this._padSensibilityDown) {
  82755. this._rotationLeftAsked = false;
  82756. }
  82757. }
  82758. if (!this._rotationRightAsked) {
  82759. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  82760. this._rotationRightAsked = true;
  82761. if (this._rotationAllowed) {
  82762. this._rotateCamera(true);
  82763. }
  82764. }
  82765. }
  82766. else {
  82767. if (stateObject.x < this._padSensibilityDown) {
  82768. this._rotationRightAsked = false;
  82769. }
  82770. }
  82771. };
  82772. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  82773. // Only teleport backwards when user is not currently selecting a teleportation location
  82774. if (gazer._teleportationRequestInitiated) {
  82775. return;
  82776. }
  82777. // Teleport backwards
  82778. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  82779. if (!gazer._teleportationBackRequestInitiated) {
  82780. if (!this.currentVRCamera) {
  82781. return;
  82782. }
  82783. // Get rotation and position of the current camera
  82784. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  82785. var position = this.currentVRCamera.position;
  82786. // If the camera has device position, use that instead
  82787. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  82788. rotation = this.currentVRCamera.deviceRotationQuaternion;
  82789. position = this.currentVRCamera.devicePosition;
  82790. }
  82791. // Get matrix with only the y rotation of the device rotation
  82792. rotation.toEulerAnglesToRef(this._workingVector);
  82793. this._workingVector.z = 0;
  82794. this._workingVector.x = 0;
  82795. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  82796. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  82797. // Rotate backwards ray by device rotation to cast at the ground behind the user
  82798. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  82799. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  82800. var ray = new BABYLON.Ray(position, this._workingVector);
  82801. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  82802. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  82803. this._teleportCamera(hit.pickedPoint);
  82804. }
  82805. gazer._teleportationBackRequestInitiated = true;
  82806. }
  82807. }
  82808. else {
  82809. gazer._teleportationBackRequestInitiated = false;
  82810. }
  82811. };
  82812. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  82813. var _this = this;
  82814. var controllerMesh = controller.webVRController.mesh;
  82815. if (controllerMesh) {
  82816. if (!controller._interactionsEnabled) {
  82817. this._enableInteractionOnController(controller);
  82818. }
  82819. controller._interactionsEnabled = true;
  82820. controller._teleportationEnabled = true;
  82821. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82822. controller._dpadPressed = false;
  82823. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  82824. controller._dpadPressed = stateObject.pressed;
  82825. if (!controller._dpadPressed) {
  82826. _this._rotationLeftAsked = false;
  82827. _this._rotationRightAsked = false;
  82828. controller._teleportationBackRequestInitiated = false;
  82829. }
  82830. });
  82831. }
  82832. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  82833. if (_this.teleportationEnabled) {
  82834. _this._checkTeleportBackwards(stateObject, controller);
  82835. _this._checkTeleportWithRay(stateObject, controller);
  82836. }
  82837. _this._checkRotate(stateObject, controller);
  82838. });
  82839. }
  82840. };
  82841. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  82842. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  82843. this._teleportationTarget.isPickable = false;
  82844. var length = 512;
  82845. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  82846. dynamicTexture.hasAlpha = true;
  82847. var context = dynamicTexture.getContext();
  82848. var centerX = length / 2;
  82849. var centerY = length / 2;
  82850. var radius = 200;
  82851. context.beginPath();
  82852. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  82853. context.fillStyle = this._teleportationFillColor;
  82854. context.fill();
  82855. context.lineWidth = 10;
  82856. context.strokeStyle = this._teleportationBorderColor;
  82857. context.stroke();
  82858. context.closePath();
  82859. dynamicTexture.update();
  82860. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  82861. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  82862. this._teleportationTarget.material = teleportationCircleMaterial;
  82863. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  82864. torus.isPickable = false;
  82865. torus.parent = this._teleportationTarget;
  82866. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  82867. var keys = [];
  82868. keys.push({
  82869. frame: 0,
  82870. value: 0
  82871. });
  82872. keys.push({
  82873. frame: 30,
  82874. value: 0.4
  82875. });
  82876. keys.push({
  82877. frame: 60,
  82878. value: 0
  82879. });
  82880. animationInnerCircle.setKeys(keys);
  82881. var easingFunction = new BABYLON.SineEase();
  82882. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  82883. animationInnerCircle.setEasingFunction(easingFunction);
  82884. torus.animations = [];
  82885. torus.animations.push(animationInnerCircle);
  82886. this._scene.beginAnimation(torus, 0, 60, true);
  82887. this._hideTeleportationTarget();
  82888. };
  82889. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  82890. this._teleportActive = true;
  82891. if (this._teleportationInitialized) {
  82892. this._teleportationTarget.isVisible = true;
  82893. if (this._isDefaultTeleportationTarget) {
  82894. this._teleportationTarget.getChildren()[0].isVisible = true;
  82895. }
  82896. }
  82897. };
  82898. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  82899. this._teleportActive = false;
  82900. if (this._teleportationInitialized) {
  82901. this._teleportationTarget.isVisible = false;
  82902. if (this._isDefaultTeleportationTarget) {
  82903. this._teleportationTarget.getChildren()[0].isVisible = false;
  82904. }
  82905. }
  82906. };
  82907. VRExperienceHelper.prototype._rotateCamera = function (right) {
  82908. var _this = this;
  82909. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82910. return;
  82911. }
  82912. if (right) {
  82913. this._rotationAngle++;
  82914. }
  82915. else {
  82916. this._rotationAngle--;
  82917. }
  82918. this.currentVRCamera.animations = [];
  82919. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  82920. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82921. var animationRotationKeys = [];
  82922. animationRotationKeys.push({
  82923. frame: 0,
  82924. value: this.currentVRCamera.rotationQuaternion
  82925. });
  82926. animationRotationKeys.push({
  82927. frame: 6,
  82928. value: target
  82929. });
  82930. animationRotation.setKeys(animationRotationKeys);
  82931. animationRotation.setEasingFunction(this._circleEase);
  82932. this.currentVRCamera.animations.push(animationRotation);
  82933. this._postProcessMove.animations = [];
  82934. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82935. var vignetteWeightKeys = [];
  82936. vignetteWeightKeys.push({
  82937. frame: 0,
  82938. value: 0
  82939. });
  82940. vignetteWeightKeys.push({
  82941. frame: 3,
  82942. value: 4
  82943. });
  82944. vignetteWeightKeys.push({
  82945. frame: 6,
  82946. value: 0
  82947. });
  82948. animationPP.setKeys(vignetteWeightKeys);
  82949. animationPP.setEasingFunction(this._circleEase);
  82950. this._postProcessMove.animations.push(animationPP);
  82951. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82952. var vignetteStretchKeys = [];
  82953. vignetteStretchKeys.push({
  82954. frame: 0,
  82955. value: 0
  82956. });
  82957. vignetteStretchKeys.push({
  82958. frame: 3,
  82959. value: 10
  82960. });
  82961. vignetteStretchKeys.push({
  82962. frame: 6,
  82963. value: 0
  82964. });
  82965. animationPP2.setKeys(vignetteStretchKeys);
  82966. animationPP2.setEasingFunction(this._circleEase);
  82967. this._postProcessMove.animations.push(animationPP2);
  82968. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  82969. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  82970. this._postProcessMove.samples = 4;
  82971. this._webVRCamera.attachPostProcess(this._postProcessMove);
  82972. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  82973. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  82974. });
  82975. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  82976. };
  82977. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  82978. if (hit.pickedPoint) {
  82979. if (gazer._teleportationRequestInitiated) {
  82980. this._displayTeleportationTarget();
  82981. this._haloCenter.copyFrom(hit.pickedPoint);
  82982. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  82983. }
  82984. var pickNormal = hit.getNormal(true, false);
  82985. if (pickNormal) {
  82986. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  82987. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  82988. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  82989. }
  82990. this._teleportationTarget.position.y += 0.1;
  82991. }
  82992. };
  82993. VRExperienceHelper.prototype._teleportCamera = function (location) {
  82994. var _this = this;
  82995. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82996. return;
  82997. }
  82998. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  82999. // offset of the headset from the anchor.
  83000. if (this.webVRCamera.leftCamera) {
  83001. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  83002. this._workingVector.subtractInPlace(this.webVRCamera.position);
  83003. location.subtractToRef(this._workingVector, this._workingVector);
  83004. }
  83005. else {
  83006. this._workingVector.copyFrom(location);
  83007. }
  83008. // Add height to account for user's height offset
  83009. if (this.isInVRMode) {
  83010. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  83011. }
  83012. else {
  83013. this._workingVector.y += this._defaultHeight;
  83014. }
  83015. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  83016. // Create animation from the camera's position to the new location
  83017. this.currentVRCamera.animations = [];
  83018. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83019. var animationCameraTeleportationKeys = [{
  83020. frame: 0,
  83021. value: this.currentVRCamera.position
  83022. },
  83023. {
  83024. frame: 11,
  83025. value: this._workingVector
  83026. }
  83027. ];
  83028. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  83029. animationCameraTeleportation.setEasingFunction(this._circleEase);
  83030. this.currentVRCamera.animations.push(animationCameraTeleportation);
  83031. this._postProcessMove.animations = [];
  83032. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83033. var vignetteWeightKeys = [];
  83034. vignetteWeightKeys.push({
  83035. frame: 0,
  83036. value: 0
  83037. });
  83038. vignetteWeightKeys.push({
  83039. frame: 5,
  83040. value: 8
  83041. });
  83042. vignetteWeightKeys.push({
  83043. frame: 11,
  83044. value: 0
  83045. });
  83046. animationPP.setKeys(vignetteWeightKeys);
  83047. this._postProcessMove.animations.push(animationPP);
  83048. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83049. var vignetteStretchKeys = [];
  83050. vignetteStretchKeys.push({
  83051. frame: 0,
  83052. value: 0
  83053. });
  83054. vignetteStretchKeys.push({
  83055. frame: 5,
  83056. value: 10
  83057. });
  83058. vignetteStretchKeys.push({
  83059. frame: 11,
  83060. value: 0
  83061. });
  83062. animationPP2.setKeys(vignetteStretchKeys);
  83063. this._postProcessMove.animations.push(animationPP2);
  83064. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  83065. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  83066. this._webVRCamera.attachPostProcess(this._postProcessMove);
  83067. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  83068. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  83069. });
  83070. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  83071. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  83072. });
  83073. this._hideTeleportationTarget();
  83074. };
  83075. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  83076. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83077. return;
  83078. }
  83079. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  83080. // Moving the gazeTracker on the mesh face targetted
  83081. if (hit && hit.pickedPoint) {
  83082. if (this._displayGaze) {
  83083. var multiplier = 1;
  83084. gazer._gazeTracker.isVisible = true;
  83085. if (gazer._isActionableMesh) {
  83086. multiplier = 3;
  83087. }
  83088. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  83089. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  83090. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  83091. var pickNormal = hit.getNormal();
  83092. // To avoid z-fighting
  83093. var deltaFighting = 0.002;
  83094. if (pickNormal) {
  83095. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  83096. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  83097. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  83098. }
  83099. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  83100. if (gazer._gazeTracker.position.x < 0) {
  83101. gazer._gazeTracker.position.x += deltaFighting;
  83102. }
  83103. else {
  83104. gazer._gazeTracker.position.x -= deltaFighting;
  83105. }
  83106. if (gazer._gazeTracker.position.y < 0) {
  83107. gazer._gazeTracker.position.y += deltaFighting;
  83108. }
  83109. else {
  83110. gazer._gazeTracker.position.y -= deltaFighting;
  83111. }
  83112. if (gazer._gazeTracker.position.z < 0) {
  83113. gazer._gazeTracker.position.z += deltaFighting;
  83114. }
  83115. else {
  83116. gazer._gazeTracker.position.z -= deltaFighting;
  83117. }
  83118. }
  83119. // Changing the size of the laser pointer based on the distance from the targetted point
  83120. gazer._updatePointerDistance(hit.distance);
  83121. }
  83122. else {
  83123. gazer._gazeTracker.isVisible = false;
  83124. }
  83125. if (hit && hit.pickedMesh) {
  83126. gazer._currentHit = hit;
  83127. if (gazer._pointerDownOnMeshAsked) {
  83128. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  83129. }
  83130. // The object selected is the floor, we're in a teleportation scenario
  83131. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  83132. // Moving the teleportation area to this targetted point
  83133. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  83134. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  83135. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83136. }
  83137. gazer._currentMeshSelected = null;
  83138. if (gazer._teleportationRequestInitiated) {
  83139. this._moveTeleportationSelectorTo(hit, gazer);
  83140. }
  83141. return;
  83142. }
  83143. // If not, we're in a selection scenario
  83144. //this._teleportationAllowed = false;
  83145. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  83146. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  83147. this.onNewMeshPicked.notifyObservers(hit);
  83148. gazer._currentMeshSelected = hit.pickedMesh;
  83149. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  83150. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  83151. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  83152. gazer._isActionableMesh = true;
  83153. }
  83154. else {
  83155. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83156. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83157. gazer._isActionableMesh = false;
  83158. }
  83159. try {
  83160. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  83161. }
  83162. catch (err) {
  83163. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  83164. }
  83165. }
  83166. else {
  83167. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83168. gazer._currentMeshSelected = null;
  83169. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83170. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83171. }
  83172. }
  83173. }
  83174. else {
  83175. gazer._currentHit = null;
  83176. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83177. gazer._currentMeshSelected = null;
  83178. //this._teleportationAllowed = false;
  83179. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83180. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83181. }
  83182. };
  83183. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  83184. if (mesh) {
  83185. this.onSelectedMeshUnselected.notifyObservers(mesh);
  83186. }
  83187. };
  83188. /**
  83189. * Sets the color of the laser ray from the vr controllers.
  83190. * @param color new color for the ray.
  83191. */
  83192. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  83193. if (this.leftController) {
  83194. this.leftController._setLaserPointerColor(color);
  83195. }
  83196. if (this.rightController) {
  83197. this.rightController._setLaserPointerColor(color);
  83198. }
  83199. };
  83200. /**
  83201. * Sets the color of the ray from the vr headsets gaze.
  83202. * @param color new color for the ray.
  83203. */
  83204. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  83205. if (!this._cameraGazer._gazeTracker.material) {
  83206. return;
  83207. }
  83208. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  83209. if (this.leftController) {
  83210. this.leftController._gazeTracker.material.emissiveColor = color;
  83211. }
  83212. if (this.rightController) {
  83213. this.rightController._gazeTracker.material.emissiveColor = color;
  83214. }
  83215. };
  83216. /**
  83217. * Exits VR and disposes of the vr experience helper
  83218. */
  83219. VRExperienceHelper.prototype.dispose = function () {
  83220. if (this.isInVRMode) {
  83221. this.exitVR();
  83222. }
  83223. if (this._postProcessMove) {
  83224. this._postProcessMove.dispose();
  83225. }
  83226. if (this._webVRCamera) {
  83227. this._webVRCamera.dispose();
  83228. }
  83229. if (this._vrDeviceOrientationCamera) {
  83230. this._vrDeviceOrientationCamera.dispose();
  83231. }
  83232. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  83233. document.body.removeChild(this._btnVR);
  83234. }
  83235. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  83236. this._deviceOrientationCamera.dispose();
  83237. }
  83238. if (this._cameraGazer) {
  83239. this._cameraGazer.dispose();
  83240. }
  83241. if (this.leftController) {
  83242. this.leftController.dispose();
  83243. }
  83244. if (this.rightController) {
  83245. this.rightController.dispose();
  83246. }
  83247. if (this._teleportationTarget) {
  83248. this._teleportationTarget.dispose();
  83249. }
  83250. this._floorMeshesCollection = [];
  83251. document.removeEventListener("keydown", this._onKeyDown);
  83252. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83253. window.removeEventListener("resize", this._onResize);
  83254. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  83255. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  83256. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  83257. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  83258. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  83259. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  83260. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  83261. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83262. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  83263. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  83264. this._scene.unregisterBeforeRender(this.beforeRender);
  83265. };
  83266. /**
  83267. * Gets the name of the VRExperienceHelper class
  83268. * @returns "VRExperienceHelper"
  83269. */
  83270. VRExperienceHelper.prototype.getClassName = function () {
  83271. return "VRExperienceHelper";
  83272. };
  83273. return VRExperienceHelper;
  83274. }());
  83275. BABYLON.VRExperienceHelper = VRExperienceHelper;
  83276. })(BABYLON || (BABYLON = {}));
  83277. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  83278. // Mainly based on these 2 articles :
  83279. // 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
  83280. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  83281. var BABYLON;
  83282. (function (BABYLON) {
  83283. var JoystickAxis;
  83284. (function (JoystickAxis) {
  83285. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  83286. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  83287. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  83288. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  83289. var VirtualJoystick = /** @class */ (function () {
  83290. function VirtualJoystick(leftJoystick) {
  83291. var _this = this;
  83292. if (leftJoystick) {
  83293. this._leftJoystick = true;
  83294. }
  83295. else {
  83296. this._leftJoystick = false;
  83297. }
  83298. VirtualJoystick._globalJoystickIndex++;
  83299. // By default left & right arrow keys are moving the X
  83300. // and up & down keys are moving the Y
  83301. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  83302. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  83303. this.reverseLeftRight = false;
  83304. this.reverseUpDown = false;
  83305. // collections of pointers
  83306. this._touches = new BABYLON.StringDictionary();
  83307. this.deltaPosition = BABYLON.Vector3.Zero();
  83308. this._joystickSensibility = 25;
  83309. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  83310. this._onResize = function (evt) {
  83311. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83312. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83313. if (VirtualJoystick.vjCanvas) {
  83314. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  83315. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  83316. }
  83317. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  83318. };
  83319. // injecting a canvas element on top of the canvas 3D game
  83320. if (!VirtualJoystick.vjCanvas) {
  83321. window.addEventListener("resize", this._onResize, false);
  83322. VirtualJoystick.vjCanvas = document.createElement("canvas");
  83323. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83324. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83325. VirtualJoystick.vjCanvas.width = window.innerWidth;
  83326. VirtualJoystick.vjCanvas.height = window.innerHeight;
  83327. VirtualJoystick.vjCanvas.style.width = "100%";
  83328. VirtualJoystick.vjCanvas.style.height = "100%";
  83329. VirtualJoystick.vjCanvas.style.position = "absolute";
  83330. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  83331. VirtualJoystick.vjCanvas.style.top = "0px";
  83332. VirtualJoystick.vjCanvas.style.left = "0px";
  83333. VirtualJoystick.vjCanvas.style.zIndex = "5";
  83334. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  83335. // Support for jQuery PEP polyfill
  83336. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  83337. var context = VirtualJoystick.vjCanvas.getContext('2d');
  83338. if (!context) {
  83339. throw new Error("Unable to create canvas for virtual joystick");
  83340. }
  83341. VirtualJoystick.vjCanvasContext = context;
  83342. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  83343. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  83344. document.body.appendChild(VirtualJoystick.vjCanvas);
  83345. }
  83346. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  83347. this.pressed = false;
  83348. // default joystick color
  83349. this._joystickColor = "cyan";
  83350. this._joystickPointerID = -1;
  83351. // current joystick position
  83352. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  83353. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  83354. // origin joystick position
  83355. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  83356. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  83357. this._onPointerDownHandlerRef = function (evt) {
  83358. _this._onPointerDown(evt);
  83359. };
  83360. this._onPointerMoveHandlerRef = function (evt) {
  83361. _this._onPointerMove(evt);
  83362. };
  83363. this._onPointerUpHandlerRef = function (evt) {
  83364. _this._onPointerUp(evt);
  83365. };
  83366. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  83367. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  83368. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  83369. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  83370. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  83371. evt.preventDefault(); // Disables system menu
  83372. }, false);
  83373. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  83374. }
  83375. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  83376. this._joystickSensibility = newJoystickSensibility;
  83377. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  83378. };
  83379. VirtualJoystick.prototype._onPointerDown = function (e) {
  83380. var positionOnScreenCondition;
  83381. e.preventDefault();
  83382. if (this._leftJoystick === true) {
  83383. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  83384. }
  83385. else {
  83386. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  83387. }
  83388. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  83389. // First contact will be dedicated to the virtual joystick
  83390. this._joystickPointerID = e.pointerId;
  83391. this._joystickPointerStartPos.x = e.clientX;
  83392. this._joystickPointerStartPos.y = e.clientY;
  83393. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  83394. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  83395. this._deltaJoystickVector.x = 0;
  83396. this._deltaJoystickVector.y = 0;
  83397. this.pressed = true;
  83398. this._touches.add(e.pointerId.toString(), e);
  83399. }
  83400. else {
  83401. // You can only trigger the action buttons with a joystick declared
  83402. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  83403. this._action();
  83404. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  83405. }
  83406. }
  83407. };
  83408. VirtualJoystick.prototype._onPointerMove = function (e) {
  83409. // If the current pointer is the one associated to the joystick (first touch contact)
  83410. if (this._joystickPointerID == e.pointerId) {
  83411. this._joystickPointerPos.x = e.clientX;
  83412. this._joystickPointerPos.y = e.clientY;
  83413. this._deltaJoystickVector = this._joystickPointerPos.clone();
  83414. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  83415. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  83416. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  83417. switch (this._axisTargetedByLeftAndRight) {
  83418. case JoystickAxis.X:
  83419. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  83420. break;
  83421. case JoystickAxis.Y:
  83422. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  83423. break;
  83424. case JoystickAxis.Z:
  83425. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  83426. break;
  83427. }
  83428. var directionUpDown = this.reverseUpDown ? 1 : -1;
  83429. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  83430. switch (this._axisTargetedByUpAndDown) {
  83431. case JoystickAxis.X:
  83432. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  83433. break;
  83434. case JoystickAxis.Y:
  83435. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  83436. break;
  83437. case JoystickAxis.Z:
  83438. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  83439. break;
  83440. }
  83441. }
  83442. else {
  83443. var data = this._touches.get(e.pointerId.toString());
  83444. if (data) {
  83445. data.x = e.clientX;
  83446. data.y = e.clientY;
  83447. }
  83448. }
  83449. };
  83450. VirtualJoystick.prototype._onPointerUp = function (e) {
  83451. if (this._joystickPointerID == e.pointerId) {
  83452. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  83453. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  83454. this._joystickPointerID = -1;
  83455. this.pressed = false;
  83456. }
  83457. else {
  83458. var touch = this._touches.get(e.pointerId.toString());
  83459. if (touch) {
  83460. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  83461. }
  83462. }
  83463. this._deltaJoystickVector.x = 0;
  83464. this._deltaJoystickVector.y = 0;
  83465. this._touches.remove(e.pointerId.toString());
  83466. };
  83467. /**
  83468. * Change the color of the virtual joystick
  83469. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  83470. */
  83471. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  83472. this._joystickColor = newColor;
  83473. };
  83474. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  83475. this._action = action;
  83476. };
  83477. // Define which axis you'd like to control for left & right
  83478. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  83479. switch (axis) {
  83480. case JoystickAxis.X:
  83481. case JoystickAxis.Y:
  83482. case JoystickAxis.Z:
  83483. this._axisTargetedByLeftAndRight = axis;
  83484. break;
  83485. default:
  83486. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  83487. break;
  83488. }
  83489. };
  83490. // Define which axis you'd like to control for up & down
  83491. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  83492. switch (axis) {
  83493. case JoystickAxis.X:
  83494. case JoystickAxis.Y:
  83495. case JoystickAxis.Z:
  83496. this._axisTargetedByUpAndDown = axis;
  83497. break;
  83498. default:
  83499. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  83500. break;
  83501. }
  83502. };
  83503. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  83504. var _this = this;
  83505. if (this.pressed) {
  83506. this._touches.forEach(function (key, touch) {
  83507. if (touch.pointerId === _this._joystickPointerID) {
  83508. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  83509. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  83510. VirtualJoystick.vjCanvasContext.beginPath();
  83511. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  83512. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83513. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  83514. VirtualJoystick.vjCanvasContext.stroke();
  83515. VirtualJoystick.vjCanvasContext.closePath();
  83516. VirtualJoystick.vjCanvasContext.beginPath();
  83517. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83518. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  83519. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  83520. VirtualJoystick.vjCanvasContext.stroke();
  83521. VirtualJoystick.vjCanvasContext.closePath();
  83522. VirtualJoystick.vjCanvasContext.beginPath();
  83523. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83524. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  83525. VirtualJoystick.vjCanvasContext.stroke();
  83526. VirtualJoystick.vjCanvasContext.closePath();
  83527. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  83528. }
  83529. else {
  83530. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  83531. VirtualJoystick.vjCanvasContext.beginPath();
  83532. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  83533. VirtualJoystick.vjCanvasContext.beginPath();
  83534. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  83535. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  83536. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  83537. VirtualJoystick.vjCanvasContext.stroke();
  83538. VirtualJoystick.vjCanvasContext.closePath();
  83539. touch.prevX = touch.x;
  83540. touch.prevY = touch.y;
  83541. }
  83542. ;
  83543. });
  83544. }
  83545. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  83546. };
  83547. VirtualJoystick.prototype.releaseCanvas = function () {
  83548. if (VirtualJoystick.vjCanvas) {
  83549. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  83550. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  83551. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  83552. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  83553. window.removeEventListener("resize", this._onResize);
  83554. document.body.removeChild(VirtualJoystick.vjCanvas);
  83555. VirtualJoystick.vjCanvas = null;
  83556. }
  83557. };
  83558. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  83559. VirtualJoystick._globalJoystickIndex = 0;
  83560. return VirtualJoystick;
  83561. }());
  83562. BABYLON.VirtualJoystick = VirtualJoystick;
  83563. })(BABYLON || (BABYLON = {}));
  83564. //# sourceMappingURL=babylon.virtualJoystick.js.map
  83565. var BABYLON;
  83566. (function (BABYLON) {
  83567. // We're mainly based on the logic defined into the FreeCamera code
  83568. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  83569. __extends(VirtualJoysticksCamera, _super);
  83570. function VirtualJoysticksCamera(name, position, scene) {
  83571. var _this = _super.call(this, name, position, scene) || this;
  83572. _this.inputs.addVirtualJoystick();
  83573. return _this;
  83574. }
  83575. VirtualJoysticksCamera.prototype.getClassName = function () {
  83576. return "VirtualJoysticksCamera";
  83577. };
  83578. return VirtualJoysticksCamera;
  83579. }(BABYLON.FreeCamera));
  83580. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  83581. })(BABYLON || (BABYLON = {}));
  83582. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  83583. var BABYLON;
  83584. (function (BABYLON) {
  83585. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  83586. function FreeCameraVirtualJoystickInput() {
  83587. }
  83588. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  83589. return this._leftjoystick;
  83590. };
  83591. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  83592. return this._rightjoystick;
  83593. };
  83594. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  83595. if (this._leftjoystick) {
  83596. var camera = this.camera;
  83597. var speed = camera._computeLocalCameraSpeed() * 50;
  83598. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  83599. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  83600. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  83601. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  83602. if (!this._leftjoystick.pressed) {
  83603. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  83604. }
  83605. if (!this._rightjoystick.pressed) {
  83606. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  83607. }
  83608. }
  83609. };
  83610. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  83611. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  83612. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  83613. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  83614. this._leftjoystick.setJoystickSensibility(0.15);
  83615. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  83616. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  83617. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  83618. this._rightjoystick.reverseUpDown = true;
  83619. this._rightjoystick.setJoystickSensibility(0.05);
  83620. this._rightjoystick.setJoystickColor("yellow");
  83621. };
  83622. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  83623. this._leftjoystick.releaseCanvas();
  83624. this._rightjoystick.releaseCanvas();
  83625. };
  83626. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  83627. return "FreeCameraVirtualJoystickInput";
  83628. };
  83629. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  83630. return "virtualJoystick";
  83631. };
  83632. return FreeCameraVirtualJoystickInput;
  83633. }());
  83634. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  83635. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  83636. })(BABYLON || (BABYLON = {}));
  83637. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  83638. var BABYLON;
  83639. (function (BABYLON) {
  83640. var SimplificationSettings = /** @class */ (function () {
  83641. function SimplificationSettings(quality, distance, optimizeMesh) {
  83642. this.quality = quality;
  83643. this.distance = distance;
  83644. this.optimizeMesh = optimizeMesh;
  83645. }
  83646. return SimplificationSettings;
  83647. }());
  83648. BABYLON.SimplificationSettings = SimplificationSettings;
  83649. var SimplificationQueue = /** @class */ (function () {
  83650. function SimplificationQueue() {
  83651. this.running = false;
  83652. this._simplificationArray = [];
  83653. }
  83654. SimplificationQueue.prototype.addTask = function (task) {
  83655. this._simplificationArray.push(task);
  83656. };
  83657. SimplificationQueue.prototype.executeNext = function () {
  83658. var task = this._simplificationArray.pop();
  83659. if (task) {
  83660. this.running = true;
  83661. this.runSimplification(task);
  83662. }
  83663. else {
  83664. this.running = false;
  83665. }
  83666. };
  83667. SimplificationQueue.prototype.runSimplification = function (task) {
  83668. var _this = this;
  83669. if (task.parallelProcessing) {
  83670. //parallel simplifier
  83671. task.settings.forEach(function (setting) {
  83672. var simplifier = _this.getSimplifier(task);
  83673. simplifier.simplify(setting, function (newMesh) {
  83674. task.mesh.addLODLevel(setting.distance, newMesh);
  83675. newMesh.isVisible = true;
  83676. //check if it is the last
  83677. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  83678. //all done, run the success callback.
  83679. task.successCallback();
  83680. }
  83681. _this.executeNext();
  83682. });
  83683. });
  83684. }
  83685. else {
  83686. //single simplifier.
  83687. var simplifier = this.getSimplifier(task);
  83688. var runDecimation = function (setting, callback) {
  83689. simplifier.simplify(setting, function (newMesh) {
  83690. task.mesh.addLODLevel(setting.distance, newMesh);
  83691. newMesh.isVisible = true;
  83692. //run the next quality level
  83693. callback();
  83694. });
  83695. };
  83696. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  83697. runDecimation(task.settings[loop.index], function () {
  83698. loop.executeNext();
  83699. });
  83700. }, function () {
  83701. //execution ended, run the success callback.
  83702. if (task.successCallback) {
  83703. task.successCallback();
  83704. }
  83705. _this.executeNext();
  83706. });
  83707. }
  83708. };
  83709. SimplificationQueue.prototype.getSimplifier = function (task) {
  83710. switch (task.simplificationType) {
  83711. case SimplificationType.QUADRATIC:
  83712. default:
  83713. return new QuadraticErrorSimplification(task.mesh);
  83714. }
  83715. };
  83716. return SimplificationQueue;
  83717. }());
  83718. BABYLON.SimplificationQueue = SimplificationQueue;
  83719. /**
  83720. * The implemented types of simplification.
  83721. * At the moment only Quadratic Error Decimation is implemented.
  83722. */
  83723. var SimplificationType;
  83724. (function (SimplificationType) {
  83725. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  83726. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  83727. var DecimationTriangle = /** @class */ (function () {
  83728. function DecimationTriangle(vertices) {
  83729. this.vertices = vertices;
  83730. this.error = new Array(4);
  83731. this.deleted = false;
  83732. this.isDirty = false;
  83733. this.deletePending = false;
  83734. this.borderFactor = 0;
  83735. }
  83736. return DecimationTriangle;
  83737. }());
  83738. BABYLON.DecimationTriangle = DecimationTriangle;
  83739. var DecimationVertex = /** @class */ (function () {
  83740. function DecimationVertex(position, id) {
  83741. this.position = position;
  83742. this.id = id;
  83743. this.isBorder = true;
  83744. this.q = new QuadraticMatrix();
  83745. this.triangleCount = 0;
  83746. this.triangleStart = 0;
  83747. this.originalOffsets = [];
  83748. }
  83749. DecimationVertex.prototype.updatePosition = function (newPosition) {
  83750. this.position.copyFrom(newPosition);
  83751. };
  83752. return DecimationVertex;
  83753. }());
  83754. BABYLON.DecimationVertex = DecimationVertex;
  83755. var QuadraticMatrix = /** @class */ (function () {
  83756. function QuadraticMatrix(data) {
  83757. this.data = new Array(10);
  83758. for (var i = 0; i < 10; ++i) {
  83759. if (data && data[i]) {
  83760. this.data[i] = data[i];
  83761. }
  83762. else {
  83763. this.data[i] = 0;
  83764. }
  83765. }
  83766. }
  83767. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  83768. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  83769. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  83770. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  83771. return det;
  83772. };
  83773. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  83774. for (var i = 0; i < 10; ++i) {
  83775. this.data[i] += matrix.data[i];
  83776. }
  83777. };
  83778. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  83779. for (var i = 0; i < 10; ++i) {
  83780. this.data[i] += data[i];
  83781. }
  83782. };
  83783. QuadraticMatrix.prototype.add = function (matrix) {
  83784. var m = new QuadraticMatrix();
  83785. for (var i = 0; i < 10; ++i) {
  83786. m.data[i] = this.data[i] + matrix.data[i];
  83787. }
  83788. return m;
  83789. };
  83790. QuadraticMatrix.FromData = function (a, b, c, d) {
  83791. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  83792. };
  83793. //returning an array to avoid garbage collection
  83794. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  83795. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  83796. };
  83797. return QuadraticMatrix;
  83798. }());
  83799. BABYLON.QuadraticMatrix = QuadraticMatrix;
  83800. var Reference = /** @class */ (function () {
  83801. function Reference(vertexId, triangleId) {
  83802. this.vertexId = vertexId;
  83803. this.triangleId = triangleId;
  83804. }
  83805. return Reference;
  83806. }());
  83807. BABYLON.Reference = Reference;
  83808. /**
  83809. * An implementation of the Quadratic Error simplification algorithm.
  83810. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  83811. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  83812. * @author RaananW
  83813. */
  83814. var QuadraticErrorSimplification = /** @class */ (function () {
  83815. function QuadraticErrorSimplification(_mesh) {
  83816. this._mesh = _mesh;
  83817. this.syncIterations = 5000;
  83818. this.aggressiveness = 7;
  83819. this.decimationIterations = 100;
  83820. this.boundingBoxEpsilon = BABYLON.Epsilon;
  83821. }
  83822. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  83823. var _this = this;
  83824. this.initDecimatedMesh();
  83825. //iterating through the submeshes array, one after the other.
  83826. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  83827. _this.initWithMesh(loop.index, function () {
  83828. _this.runDecimation(settings, loop.index, function () {
  83829. loop.executeNext();
  83830. });
  83831. }, settings.optimizeMesh);
  83832. }, function () {
  83833. setTimeout(function () {
  83834. successCallback(_this._reconstructedMesh);
  83835. }, 0);
  83836. });
  83837. };
  83838. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  83839. var _this = this;
  83840. var targetCount = ~~(this.triangles.length * settings.quality);
  83841. var deletedTriangles = 0;
  83842. var triangleCount = this.triangles.length;
  83843. var iterationFunction = function (iteration, callback) {
  83844. setTimeout(function () {
  83845. if (iteration % 5 === 0) {
  83846. _this.updateMesh(iteration === 0);
  83847. }
  83848. for (var i = 0; i < _this.triangles.length; ++i) {
  83849. _this.triangles[i].isDirty = false;
  83850. }
  83851. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  83852. var trianglesIterator = function (i) {
  83853. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  83854. var t = _this.triangles[tIdx];
  83855. if (!t)
  83856. return;
  83857. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  83858. return;
  83859. }
  83860. for (var j = 0; j < 3; ++j) {
  83861. if (t.error[j] < threshold) {
  83862. var deleted0 = [];
  83863. var deleted1 = [];
  83864. var v0 = t.vertices[j];
  83865. var v1 = t.vertices[(j + 1) % 3];
  83866. if (v0.isBorder || v1.isBorder)
  83867. continue;
  83868. var p = BABYLON.Vector3.Zero();
  83869. var n = BABYLON.Vector3.Zero();
  83870. var uv = BABYLON.Vector2.Zero();
  83871. var color = new BABYLON.Color4(0, 0, 0, 1);
  83872. _this.calculateError(v0, v1, p, n, uv, color);
  83873. var delTr = new Array();
  83874. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  83875. continue;
  83876. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  83877. continue;
  83878. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  83879. continue;
  83880. var uniqueArray = new Array();
  83881. delTr.forEach(function (deletedT) {
  83882. if (uniqueArray.indexOf(deletedT) === -1) {
  83883. deletedT.deletePending = true;
  83884. uniqueArray.push(deletedT);
  83885. }
  83886. });
  83887. if (uniqueArray.length % 2 !== 0) {
  83888. continue;
  83889. }
  83890. v0.q = v1.q.add(v0.q);
  83891. v0.updatePosition(p);
  83892. var tStart = _this.references.length;
  83893. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  83894. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  83895. var tCount = _this.references.length - tStart;
  83896. if (tCount <= v0.triangleCount) {
  83897. if (tCount) {
  83898. for (var c = 0; c < tCount; c++) {
  83899. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  83900. }
  83901. }
  83902. }
  83903. else {
  83904. v0.triangleStart = tStart;
  83905. }
  83906. v0.triangleCount = tCount;
  83907. break;
  83908. }
  83909. }
  83910. };
  83911. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  83912. }, 0);
  83913. };
  83914. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  83915. if (triangleCount - deletedTriangles <= targetCount)
  83916. loop.breakLoop();
  83917. else {
  83918. iterationFunction(loop.index, function () {
  83919. loop.executeNext();
  83920. });
  83921. }
  83922. }, function () {
  83923. setTimeout(function () {
  83924. //reconstruct this part of the mesh
  83925. _this.reconstructMesh(submeshIndex);
  83926. successCallback();
  83927. }, 0);
  83928. });
  83929. };
  83930. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  83931. var _this = this;
  83932. this.vertices = [];
  83933. this.triangles = [];
  83934. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  83935. var indices = this._mesh.getIndices();
  83936. var submesh = this._mesh.subMeshes[submeshIndex];
  83937. var findInVertices = function (positionToSearch) {
  83938. if (optimizeMesh) {
  83939. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  83940. if (_this.vertices[ii].position.equals(positionToSearch)) {
  83941. return _this.vertices[ii];
  83942. }
  83943. }
  83944. }
  83945. return null;
  83946. };
  83947. var vertexReferences = [];
  83948. var vertexInit = function (i) {
  83949. if (!positionData) {
  83950. return;
  83951. }
  83952. var offset = i + submesh.verticesStart;
  83953. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  83954. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  83955. vertex.originalOffsets.push(offset);
  83956. if (vertex.id === _this.vertices.length) {
  83957. _this.vertices.push(vertex);
  83958. }
  83959. vertexReferences.push(vertex.id);
  83960. };
  83961. //var totalVertices = mesh.getTotalVertices();
  83962. var totalVertices = submesh.verticesCount;
  83963. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  83964. var indicesInit = function (i) {
  83965. if (!indices) {
  83966. return;
  83967. }
  83968. var offset = (submesh.indexStart / 3) + i;
  83969. var pos = (offset * 3);
  83970. var i0 = indices[pos + 0];
  83971. var i1 = indices[pos + 1];
  83972. var i2 = indices[pos + 2];
  83973. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  83974. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  83975. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  83976. var triangle = new DecimationTriangle([v0, v1, v2]);
  83977. triangle.originalOffset = pos;
  83978. _this.triangles.push(triangle);
  83979. };
  83980. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  83981. _this.init(callback);
  83982. });
  83983. });
  83984. };
  83985. QuadraticErrorSimplification.prototype.init = function (callback) {
  83986. var _this = this;
  83987. var triangleInit1 = function (i) {
  83988. var t = _this.triangles[i];
  83989. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  83990. for (var j = 0; j < 3; j++) {
  83991. 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))));
  83992. }
  83993. };
  83994. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  83995. var triangleInit2 = function (i) {
  83996. var t = _this.triangles[i];
  83997. for (var j = 0; j < 3; ++j) {
  83998. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  83999. }
  84000. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84001. };
  84002. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  84003. callback();
  84004. });
  84005. });
  84006. };
  84007. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  84008. var newTriangles = [];
  84009. var i;
  84010. for (i = 0; i < this.vertices.length; ++i) {
  84011. this.vertices[i].triangleCount = 0;
  84012. }
  84013. var t;
  84014. var j;
  84015. for (i = 0; i < this.triangles.length; ++i) {
  84016. if (!this.triangles[i].deleted) {
  84017. t = this.triangles[i];
  84018. for (j = 0; j < 3; ++j) {
  84019. t.vertices[j].triangleCount = 1;
  84020. }
  84021. newTriangles.push(t);
  84022. }
  84023. }
  84024. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  84025. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  84026. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  84027. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  84028. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  84029. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  84030. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  84031. var vertexCount = 0;
  84032. for (i = 0; i < this.vertices.length; ++i) {
  84033. var vertex = this.vertices[i];
  84034. vertex.id = vertexCount;
  84035. if (vertex.triangleCount) {
  84036. vertex.originalOffsets.forEach(function (originalOffset) {
  84037. if (!normalData) {
  84038. return;
  84039. }
  84040. newPositionData.push(vertex.position.x);
  84041. newPositionData.push(vertex.position.y);
  84042. newPositionData.push(vertex.position.z);
  84043. newNormalData.push(normalData[originalOffset * 3]);
  84044. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  84045. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  84046. if (uvs && uvs.length) {
  84047. newUVsData.push(uvs[(originalOffset * 2)]);
  84048. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  84049. }
  84050. else if (colorsData && colorsData.length) {
  84051. newColorsData.push(colorsData[(originalOffset * 4)]);
  84052. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  84053. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  84054. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  84055. }
  84056. ++vertexCount;
  84057. });
  84058. }
  84059. }
  84060. var startingIndex = this._reconstructedMesh.getTotalIndices();
  84061. var startingVertex = this._reconstructedMesh.getTotalVertices();
  84062. var submeshesArray = this._reconstructedMesh.subMeshes;
  84063. this._reconstructedMesh.subMeshes = [];
  84064. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  84065. var originalIndices = this._mesh.getIndices();
  84066. for (i = 0; i < newTriangles.length; ++i) {
  84067. t = newTriangles[i]; //now get the new referencing point for each vertex
  84068. [0, 1, 2].forEach(function (idx) {
  84069. var id = originalIndices[t.originalOffset + idx];
  84070. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  84071. if (offset < 0)
  84072. offset = 0;
  84073. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  84074. });
  84075. }
  84076. //overwriting the old vertex buffers and indices.
  84077. this._reconstructedMesh.setIndices(newIndicesArray);
  84078. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  84079. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  84080. if (newUVsData.length > 0)
  84081. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  84082. if (newColorsData.length > 0)
  84083. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  84084. //create submesh
  84085. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  84086. if (submeshIndex > 0) {
  84087. this._reconstructedMesh.subMeshes = [];
  84088. submeshesArray.forEach(function (submesh) {
  84089. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  84090. });
  84091. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  84092. }
  84093. };
  84094. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  84095. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  84096. this._reconstructedMesh.material = this._mesh.material;
  84097. this._reconstructedMesh.parent = this._mesh.parent;
  84098. this._reconstructedMesh.isVisible = false;
  84099. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  84100. };
  84101. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  84102. for (var i = 0; i < vertex1.triangleCount; ++i) {
  84103. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  84104. if (t.deleted)
  84105. continue;
  84106. var s = this.references[vertex1.triangleStart + i].vertexId;
  84107. var v1 = t.vertices[(s + 1) % 3];
  84108. var v2 = t.vertices[(s + 2) % 3];
  84109. if ((v1 === vertex2 || v2 === vertex2)) {
  84110. deletedArray[i] = true;
  84111. delTr.push(t);
  84112. continue;
  84113. }
  84114. var d1 = v1.position.subtract(point);
  84115. d1 = d1.normalize();
  84116. var d2 = v2.position.subtract(point);
  84117. d2 = d2.normalize();
  84118. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  84119. return true;
  84120. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  84121. deletedArray[i] = false;
  84122. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  84123. return true;
  84124. }
  84125. return false;
  84126. };
  84127. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  84128. var newDeleted = deletedTriangles;
  84129. for (var i = 0; i < vertex.triangleCount; ++i) {
  84130. var ref = this.references[vertex.triangleStart + i];
  84131. var t = this.triangles[ref.triangleId];
  84132. if (t.deleted)
  84133. continue;
  84134. if (deletedArray[i] && t.deletePending) {
  84135. t.deleted = true;
  84136. newDeleted++;
  84137. continue;
  84138. }
  84139. t.vertices[ref.vertexId] = origVertex;
  84140. t.isDirty = true;
  84141. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  84142. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  84143. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  84144. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84145. this.references.push(ref);
  84146. }
  84147. return newDeleted;
  84148. };
  84149. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  84150. for (var i = 0; i < this.vertices.length; ++i) {
  84151. var vCount = [];
  84152. var vId = [];
  84153. var v = this.vertices[i];
  84154. var j;
  84155. for (j = 0; j < v.triangleCount; ++j) {
  84156. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  84157. for (var ii = 0; ii < 3; ii++) {
  84158. var ofs = 0;
  84159. var vv = triangle.vertices[ii];
  84160. while (ofs < vCount.length) {
  84161. if (vId[ofs] === vv.id)
  84162. break;
  84163. ++ofs;
  84164. }
  84165. if (ofs === vCount.length) {
  84166. vCount.push(1);
  84167. vId.push(vv.id);
  84168. }
  84169. else {
  84170. vCount[ofs]++;
  84171. }
  84172. }
  84173. }
  84174. for (j = 0; j < vCount.length; ++j) {
  84175. if (vCount[j] === 1) {
  84176. this.vertices[vId[j]].isBorder = true;
  84177. }
  84178. else {
  84179. this.vertices[vId[j]].isBorder = false;
  84180. }
  84181. }
  84182. }
  84183. };
  84184. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  84185. if (identifyBorders === void 0) { identifyBorders = false; }
  84186. var i;
  84187. if (!identifyBorders) {
  84188. var newTrianglesVector = [];
  84189. for (i = 0; i < this.triangles.length; ++i) {
  84190. if (!this.triangles[i].deleted) {
  84191. newTrianglesVector.push(this.triangles[i]);
  84192. }
  84193. }
  84194. this.triangles = newTrianglesVector;
  84195. }
  84196. for (i = 0; i < this.vertices.length; ++i) {
  84197. this.vertices[i].triangleCount = 0;
  84198. this.vertices[i].triangleStart = 0;
  84199. }
  84200. var t;
  84201. var j;
  84202. var v;
  84203. for (i = 0; i < this.triangles.length; ++i) {
  84204. t = this.triangles[i];
  84205. for (j = 0; j < 3; ++j) {
  84206. v = t.vertices[j];
  84207. v.triangleCount++;
  84208. }
  84209. }
  84210. var tStart = 0;
  84211. for (i = 0; i < this.vertices.length; ++i) {
  84212. this.vertices[i].triangleStart = tStart;
  84213. tStart += this.vertices[i].triangleCount;
  84214. this.vertices[i].triangleCount = 0;
  84215. }
  84216. var newReferences = new Array(this.triangles.length * 3);
  84217. for (i = 0; i < this.triangles.length; ++i) {
  84218. t = this.triangles[i];
  84219. for (j = 0; j < 3; ++j) {
  84220. v = t.vertices[j];
  84221. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  84222. v.triangleCount++;
  84223. }
  84224. }
  84225. this.references = newReferences;
  84226. if (identifyBorders) {
  84227. this.identifyBorder();
  84228. }
  84229. };
  84230. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  84231. var x = point.x;
  84232. var y = point.y;
  84233. var z = point.z;
  84234. 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
  84235. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  84236. };
  84237. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  84238. var q = vertex1.q.add(vertex2.q);
  84239. var border = vertex1.isBorder && vertex2.isBorder;
  84240. var error = 0;
  84241. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  84242. if (qDet !== 0 && !border) {
  84243. if (!pointResult) {
  84244. pointResult = BABYLON.Vector3.Zero();
  84245. }
  84246. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  84247. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  84248. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  84249. error = this.vertexError(q, pointResult);
  84250. }
  84251. else {
  84252. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  84253. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  84254. var error1 = this.vertexError(q, vertex1.position);
  84255. var error2 = this.vertexError(q, vertex2.position);
  84256. var error3 = this.vertexError(q, p3);
  84257. error = Math.min(error1, error2, error3);
  84258. if (error === error1) {
  84259. if (pointResult) {
  84260. pointResult.copyFrom(vertex1.position);
  84261. }
  84262. }
  84263. else if (error === error2) {
  84264. if (pointResult) {
  84265. pointResult.copyFrom(vertex2.position);
  84266. }
  84267. }
  84268. else {
  84269. if (pointResult) {
  84270. pointResult.copyFrom(p3);
  84271. }
  84272. }
  84273. }
  84274. return error;
  84275. };
  84276. return QuadraticErrorSimplification;
  84277. }());
  84278. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  84279. })(BABYLON || (BABYLON = {}));
  84280. //# sourceMappingURL=babylon.meshSimplification.js.map
  84281. var BABYLON;
  84282. (function (BABYLON) {
  84283. var MeshLODLevel = /** @class */ (function () {
  84284. function MeshLODLevel(distance, mesh) {
  84285. this.distance = distance;
  84286. this.mesh = mesh;
  84287. }
  84288. return MeshLODLevel;
  84289. }());
  84290. BABYLON.MeshLODLevel = MeshLODLevel;
  84291. })(BABYLON || (BABYLON = {}));
  84292. //# sourceMappingURL=babylon.meshLODLevel.js.map
  84293. var BABYLON;
  84294. (function (BABYLON) {
  84295. /**
  84296. * Defines the root class used to create scene optimization to use with SceneOptimizer
  84297. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84298. */
  84299. var SceneOptimization = /** @class */ (function () {
  84300. /**
  84301. * Creates the SceneOptimization object
  84302. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84303. * @param desc defines the description associated with the optimization
  84304. */
  84305. function SceneOptimization(
  84306. /**
  84307. * Defines the priority of this optimization (0 by default which means first in the list)
  84308. */
  84309. priority) {
  84310. if (priority === void 0) { priority = 0; }
  84311. this.priority = priority;
  84312. }
  84313. /**
  84314. * Gets a string describing the action executed by the current optimization
  84315. * @returns description string
  84316. */
  84317. SceneOptimization.prototype.getDescription = function () {
  84318. return "";
  84319. };
  84320. /**
  84321. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84322. * @param scene defines the current scene where to apply this optimization
  84323. * @param optimizer defines the current optimizer
  84324. * @returns true if everything that can be done was applied
  84325. */
  84326. SceneOptimization.prototype.apply = function (scene, optimizer) {
  84327. return true;
  84328. };
  84329. ;
  84330. return SceneOptimization;
  84331. }());
  84332. BABYLON.SceneOptimization = SceneOptimization;
  84333. /**
  84334. * Defines an optimization used to reduce the size of render target textures
  84335. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84336. */
  84337. var TextureOptimization = /** @class */ (function (_super) {
  84338. __extends(TextureOptimization, _super);
  84339. /**
  84340. * Creates the TextureOptimization object
  84341. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84342. * @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
  84343. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  84344. */
  84345. function TextureOptimization(
  84346. /**
  84347. * Defines the priority of this optimization (0 by default which means first in the list)
  84348. */
  84349. priority,
  84350. /**
  84351. * 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
  84352. */
  84353. maximumSize,
  84354. /**
  84355. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  84356. */
  84357. step) {
  84358. if (priority === void 0) { priority = 0; }
  84359. if (maximumSize === void 0) { maximumSize = 1024; }
  84360. if (step === void 0) { step = 0.5; }
  84361. var _this = _super.call(this, priority) || this;
  84362. _this.priority = priority;
  84363. _this.maximumSize = maximumSize;
  84364. _this.step = step;
  84365. return _this;
  84366. }
  84367. /**
  84368. * Gets a string describing the action executed by the current optimization
  84369. * @returns description string
  84370. */
  84371. TextureOptimization.prototype.getDescription = function () {
  84372. return "Reducing render target texture size to " + this.maximumSize;
  84373. };
  84374. /**
  84375. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84376. * @param scene defines the current scene where to apply this optimization
  84377. * @param optimizer defines the current optimizer
  84378. * @returns true if everything that can be done was applied
  84379. */
  84380. TextureOptimization.prototype.apply = function (scene, optimizer) {
  84381. var allDone = true;
  84382. for (var index = 0; index < scene.textures.length; index++) {
  84383. var texture = scene.textures[index];
  84384. if (!texture.canRescale || texture.getContext) {
  84385. continue;
  84386. }
  84387. var currentSize = texture.getSize();
  84388. var maxDimension = Math.max(currentSize.width, currentSize.height);
  84389. if (maxDimension > this.maximumSize) {
  84390. texture.scale(this.step);
  84391. allDone = false;
  84392. }
  84393. }
  84394. return allDone;
  84395. };
  84396. return TextureOptimization;
  84397. }(SceneOptimization));
  84398. BABYLON.TextureOptimization = TextureOptimization;
  84399. /**
  84400. * Defines an optimization used to increase or decrease the rendering resolution
  84401. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84402. */
  84403. var HardwareScalingOptimization = /** @class */ (function (_super) {
  84404. __extends(HardwareScalingOptimization, _super);
  84405. /**
  84406. * Creates the HardwareScalingOptimization object
  84407. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84408. * @param maximumScale defines the maximum scale to use (2 by default)
  84409. * @param step defines the step to use between two passes (0.5 by default)
  84410. */
  84411. function HardwareScalingOptimization(
  84412. /**
  84413. * Defines the priority of this optimization (0 by default which means first in the list)
  84414. */
  84415. priority,
  84416. /**
  84417. * Defines the maximum scale to use (2 by default)
  84418. */
  84419. maximumScale,
  84420. /**
  84421. * Defines the step to use between two passes (0.5 by default)
  84422. */
  84423. step) {
  84424. if (priority === void 0) { priority = 0; }
  84425. if (maximumScale === void 0) { maximumScale = 2; }
  84426. if (step === void 0) { step = 0.25; }
  84427. var _this = _super.call(this, priority) || this;
  84428. _this.priority = priority;
  84429. _this.maximumScale = maximumScale;
  84430. _this.step = step;
  84431. _this._currentScale = -1;
  84432. _this._directionOffset = 1;
  84433. return _this;
  84434. }
  84435. /**
  84436. * Gets a string describing the action executed by the current optimization
  84437. * @return description string
  84438. */
  84439. HardwareScalingOptimization.prototype.getDescription = function () {
  84440. return "Setting hardware scaling level to " + this._currentScale;
  84441. };
  84442. /**
  84443. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84444. * @param scene defines the current scene where to apply this optimization
  84445. * @param optimizer defines the current optimizer
  84446. * @returns true if everything that can be done was applied
  84447. */
  84448. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  84449. if (this._currentScale === -1) {
  84450. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  84451. if (this._currentScale > this.maximumScale) {
  84452. this._directionOffset = -1;
  84453. }
  84454. }
  84455. this._currentScale += this._directionOffset * this.step;
  84456. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  84457. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  84458. };
  84459. ;
  84460. return HardwareScalingOptimization;
  84461. }(SceneOptimization));
  84462. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  84463. /**
  84464. * Defines an optimization used to remove shadows
  84465. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84466. */
  84467. var ShadowsOptimization = /** @class */ (function (_super) {
  84468. __extends(ShadowsOptimization, _super);
  84469. function ShadowsOptimization() {
  84470. return _super !== null && _super.apply(this, arguments) || this;
  84471. }
  84472. /**
  84473. * Gets a string describing the action executed by the current optimization
  84474. * @return description string
  84475. */
  84476. ShadowsOptimization.prototype.getDescription = function () {
  84477. return "Turning shadows on/off";
  84478. };
  84479. /**
  84480. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84481. * @param scene defines the current scene where to apply this optimization
  84482. * @param optimizer defines the current optimizer
  84483. * @returns true if everything that can be done was applied
  84484. */
  84485. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  84486. scene.shadowsEnabled = optimizer.isInImprovementMode;
  84487. return true;
  84488. };
  84489. ;
  84490. return ShadowsOptimization;
  84491. }(SceneOptimization));
  84492. BABYLON.ShadowsOptimization = ShadowsOptimization;
  84493. /**
  84494. * Defines an optimization used to turn post-processes off
  84495. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84496. */
  84497. var PostProcessesOptimization = /** @class */ (function (_super) {
  84498. __extends(PostProcessesOptimization, _super);
  84499. function PostProcessesOptimization() {
  84500. return _super !== null && _super.apply(this, arguments) || this;
  84501. }
  84502. /**
  84503. * Gets a string describing the action executed by the current optimization
  84504. * @return description string
  84505. */
  84506. PostProcessesOptimization.prototype.getDescription = function () {
  84507. return "Turning post-processes on/off";
  84508. };
  84509. /**
  84510. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84511. * @param scene defines the current scene where to apply this optimization
  84512. * @param optimizer defines the current optimizer
  84513. * @returns true if everything that can be done was applied
  84514. */
  84515. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  84516. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  84517. return true;
  84518. };
  84519. ;
  84520. return PostProcessesOptimization;
  84521. }(SceneOptimization));
  84522. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  84523. /**
  84524. * Defines an optimization used to turn lens flares off
  84525. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84526. */
  84527. var LensFlaresOptimization = /** @class */ (function (_super) {
  84528. __extends(LensFlaresOptimization, _super);
  84529. function LensFlaresOptimization() {
  84530. return _super !== null && _super.apply(this, arguments) || this;
  84531. }
  84532. /**
  84533. * Gets a string describing the action executed by the current optimization
  84534. * @return description string
  84535. */
  84536. LensFlaresOptimization.prototype.getDescription = function () {
  84537. return "Turning lens flares on/off";
  84538. };
  84539. /**
  84540. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84541. * @param scene defines the current scene where to apply this optimization
  84542. * @param optimizer defines the current optimizer
  84543. * @returns true if everything that can be done was applied
  84544. */
  84545. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  84546. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  84547. return true;
  84548. };
  84549. ;
  84550. return LensFlaresOptimization;
  84551. }(SceneOptimization));
  84552. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  84553. /**
  84554. * Defines an optimization based on user defined callback.
  84555. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84556. */
  84557. var CustomOptimization = /** @class */ (function (_super) {
  84558. __extends(CustomOptimization, _super);
  84559. function CustomOptimization() {
  84560. return _super !== null && _super.apply(this, arguments) || this;
  84561. }
  84562. /**
  84563. * Gets a string describing the action executed by the current optimization
  84564. * @returns description string
  84565. */
  84566. CustomOptimization.prototype.getDescription = function () {
  84567. if (this.onGetDescription) {
  84568. return this.onGetDescription();
  84569. }
  84570. return "Running user defined callback";
  84571. };
  84572. /**
  84573. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84574. * @param scene defines the current scene where to apply this optimization
  84575. * @param optimizer defines the current optimizer
  84576. * @returns true if everything that can be done was applied
  84577. */
  84578. CustomOptimization.prototype.apply = function (scene, optimizer) {
  84579. if (this.onApply) {
  84580. return this.onApply(scene, optimizer);
  84581. }
  84582. return true;
  84583. };
  84584. ;
  84585. return CustomOptimization;
  84586. }(SceneOptimization));
  84587. BABYLON.CustomOptimization = CustomOptimization;
  84588. /**
  84589. * Defines an optimization used to turn particles off
  84590. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84591. */
  84592. var ParticlesOptimization = /** @class */ (function (_super) {
  84593. __extends(ParticlesOptimization, _super);
  84594. function ParticlesOptimization() {
  84595. return _super !== null && _super.apply(this, arguments) || this;
  84596. }
  84597. /**
  84598. * Gets a string describing the action executed by the current optimization
  84599. * @return description string
  84600. */
  84601. ParticlesOptimization.prototype.getDescription = function () {
  84602. return "Turning particles on/off";
  84603. };
  84604. /**
  84605. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84606. * @param scene defines the current scene where to apply this optimization
  84607. * @param optimizer defines the current optimizer
  84608. * @returns true if everything that can be done was applied
  84609. */
  84610. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  84611. scene.particlesEnabled = optimizer.isInImprovementMode;
  84612. return true;
  84613. };
  84614. ;
  84615. return ParticlesOptimization;
  84616. }(SceneOptimization));
  84617. BABYLON.ParticlesOptimization = ParticlesOptimization;
  84618. /**
  84619. * Defines an optimization used to turn render targets off
  84620. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84621. */
  84622. var RenderTargetsOptimization = /** @class */ (function (_super) {
  84623. __extends(RenderTargetsOptimization, _super);
  84624. function RenderTargetsOptimization() {
  84625. return _super !== null && _super.apply(this, arguments) || this;
  84626. }
  84627. /**
  84628. * Gets a string describing the action executed by the current optimization
  84629. * @return description string
  84630. */
  84631. RenderTargetsOptimization.prototype.getDescription = function () {
  84632. return "Turning render targets off";
  84633. };
  84634. /**
  84635. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84636. * @param scene defines the current scene where to apply this optimization
  84637. * @param optimizer defines the current optimizer
  84638. * @returns true if everything that can be done was applied
  84639. */
  84640. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  84641. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  84642. return true;
  84643. };
  84644. ;
  84645. return RenderTargetsOptimization;
  84646. }(SceneOptimization));
  84647. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  84648. /**
  84649. * Defines an optimization used to merge meshes with compatible materials
  84650. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84651. */
  84652. var MergeMeshesOptimization = /** @class */ (function (_super) {
  84653. __extends(MergeMeshesOptimization, _super);
  84654. function MergeMeshesOptimization() {
  84655. var _this = _super !== null && _super.apply(this, arguments) || this;
  84656. _this._canBeMerged = function (abstractMesh) {
  84657. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  84658. return false;
  84659. }
  84660. var mesh = abstractMesh;
  84661. if (!mesh.isVisible || !mesh.isEnabled()) {
  84662. return false;
  84663. }
  84664. if (mesh.instances.length > 0) {
  84665. return false;
  84666. }
  84667. if (mesh.skeleton || mesh.hasLODLevels) {
  84668. return false;
  84669. }
  84670. if (mesh.parent) {
  84671. return false;
  84672. }
  84673. return true;
  84674. };
  84675. return _this;
  84676. }
  84677. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  84678. /**
  84679. * Gets or sets a boolean which defines if optimization octree has to be updated
  84680. */
  84681. get: function () {
  84682. return MergeMeshesOptimization._UpdateSelectionTree;
  84683. },
  84684. /**
  84685. * Gets or sets a boolean which defines if optimization octree has to be updated
  84686. */
  84687. set: function (value) {
  84688. MergeMeshesOptimization._UpdateSelectionTree = value;
  84689. },
  84690. enumerable: true,
  84691. configurable: true
  84692. });
  84693. /**
  84694. * Gets a string describing the action executed by the current optimization
  84695. * @return description string
  84696. */
  84697. MergeMeshesOptimization.prototype.getDescription = function () {
  84698. return "Merging similar meshes together";
  84699. };
  84700. /**
  84701. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84702. * @param scene defines the current scene where to apply this optimization
  84703. * @param optimizer defines the current optimizer
  84704. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  84705. * @returns true if everything that can be done was applied
  84706. */
  84707. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  84708. var globalPool = scene.meshes.slice(0);
  84709. var globalLength = globalPool.length;
  84710. for (var index = 0; index < globalLength; index++) {
  84711. var currentPool = new Array();
  84712. var current = globalPool[index];
  84713. // Checks
  84714. if (!this._canBeMerged(current)) {
  84715. continue;
  84716. }
  84717. currentPool.push(current);
  84718. // Find compatible meshes
  84719. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  84720. var otherMesh = globalPool[subIndex];
  84721. if (!this._canBeMerged(otherMesh)) {
  84722. continue;
  84723. }
  84724. if (otherMesh.material !== current.material) {
  84725. continue;
  84726. }
  84727. if (otherMesh.checkCollisions !== current.checkCollisions) {
  84728. continue;
  84729. }
  84730. currentPool.push(otherMesh);
  84731. globalLength--;
  84732. globalPool.splice(subIndex, 1);
  84733. subIndex--;
  84734. }
  84735. if (currentPool.length < 2) {
  84736. continue;
  84737. }
  84738. // Merge meshes
  84739. BABYLON.Mesh.MergeMeshes(currentPool);
  84740. }
  84741. if (updateSelectionTree != undefined) {
  84742. if (updateSelectionTree) {
  84743. scene.createOrUpdateSelectionOctree();
  84744. }
  84745. }
  84746. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  84747. scene.createOrUpdateSelectionOctree();
  84748. }
  84749. return true;
  84750. };
  84751. ;
  84752. MergeMeshesOptimization._UpdateSelectionTree = false;
  84753. return MergeMeshesOptimization;
  84754. }(SceneOptimization));
  84755. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  84756. /**
  84757. * Defines a list of options used by SceneOptimizer
  84758. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84759. */
  84760. var SceneOptimizerOptions = /** @class */ (function () {
  84761. /**
  84762. * Creates a new list of options used by SceneOptimizer
  84763. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  84764. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  84765. */
  84766. function SceneOptimizerOptions(
  84767. /**
  84768. * Defines the target frame rate to reach (60 by default)
  84769. */
  84770. targetFrameRate,
  84771. /**
  84772. * Defines the interval between two checkes (2000ms by default)
  84773. */
  84774. trackerDuration) {
  84775. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  84776. if (trackerDuration === void 0) { trackerDuration = 2000; }
  84777. this.targetFrameRate = targetFrameRate;
  84778. this.trackerDuration = trackerDuration;
  84779. /**
  84780. * Gets the list of optimizations to apply
  84781. */
  84782. this.optimizations = new Array();
  84783. }
  84784. /**
  84785. * Add a new optimization
  84786. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  84787. * @returns the current SceneOptimizerOptions
  84788. */
  84789. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  84790. this.optimizations.push(optimization);
  84791. return this;
  84792. };
  84793. /**
  84794. * Add a new custom optimization
  84795. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  84796. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  84797. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84798. * @returns the current SceneOptimizerOptions
  84799. */
  84800. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  84801. if (priority === void 0) { priority = 0; }
  84802. var optimization = new CustomOptimization(priority);
  84803. optimization.onApply = onApply;
  84804. optimization.onGetDescription = onGetDescription;
  84805. this.optimizations.push(optimization);
  84806. return this;
  84807. };
  84808. /**
  84809. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  84810. * @param targetFrameRate defines the target frame rate (60 by default)
  84811. * @returns a SceneOptimizerOptions object
  84812. */
  84813. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  84814. var result = new SceneOptimizerOptions(targetFrameRate);
  84815. var priority = 0;
  84816. result.addOptimization(new MergeMeshesOptimization(priority));
  84817. result.addOptimization(new ShadowsOptimization(priority));
  84818. result.addOptimization(new LensFlaresOptimization(priority));
  84819. // Next priority
  84820. priority++;
  84821. result.addOptimization(new PostProcessesOptimization(priority));
  84822. result.addOptimization(new ParticlesOptimization(priority));
  84823. // Next priority
  84824. priority++;
  84825. result.addOptimization(new TextureOptimization(priority, 1024));
  84826. return result;
  84827. };
  84828. /**
  84829. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  84830. * @param targetFrameRate defines the target frame rate (60 by default)
  84831. * @returns a SceneOptimizerOptions object
  84832. */
  84833. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  84834. var result = new SceneOptimizerOptions(targetFrameRate);
  84835. var priority = 0;
  84836. result.addOptimization(new MergeMeshesOptimization(priority));
  84837. result.addOptimization(new ShadowsOptimization(priority));
  84838. result.addOptimization(new LensFlaresOptimization(priority));
  84839. // Next priority
  84840. priority++;
  84841. result.addOptimization(new PostProcessesOptimization(priority));
  84842. result.addOptimization(new ParticlesOptimization(priority));
  84843. // Next priority
  84844. priority++;
  84845. result.addOptimization(new TextureOptimization(priority, 512));
  84846. // Next priority
  84847. priority++;
  84848. result.addOptimization(new RenderTargetsOptimization(priority));
  84849. // Next priority
  84850. priority++;
  84851. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  84852. return result;
  84853. };
  84854. /**
  84855. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  84856. * @param targetFrameRate defines the target frame rate (60 by default)
  84857. * @returns a SceneOptimizerOptions object
  84858. */
  84859. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  84860. var result = new SceneOptimizerOptions(targetFrameRate);
  84861. var priority = 0;
  84862. result.addOptimization(new MergeMeshesOptimization(priority));
  84863. result.addOptimization(new ShadowsOptimization(priority));
  84864. result.addOptimization(new LensFlaresOptimization(priority));
  84865. // Next priority
  84866. priority++;
  84867. result.addOptimization(new PostProcessesOptimization(priority));
  84868. result.addOptimization(new ParticlesOptimization(priority));
  84869. // Next priority
  84870. priority++;
  84871. result.addOptimization(new TextureOptimization(priority, 256));
  84872. // Next priority
  84873. priority++;
  84874. result.addOptimization(new RenderTargetsOptimization(priority));
  84875. // Next priority
  84876. priority++;
  84877. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  84878. return result;
  84879. };
  84880. return SceneOptimizerOptions;
  84881. }());
  84882. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  84883. /**
  84884. * Class used to run optimizations in order to reach a target frame rate
  84885. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84886. */
  84887. var SceneOptimizer = /** @class */ (function () {
  84888. /**
  84889. * Creates a new SceneOptimizer
  84890. * @param scene defines the scene to work on
  84891. * @param options defines the options to use with the SceneOptimizer
  84892. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  84893. * @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)
  84894. */
  84895. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  84896. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  84897. if (improvementMode === void 0) { improvementMode = false; }
  84898. var _this = this;
  84899. this._isRunning = false;
  84900. this._currentPriorityLevel = 0;
  84901. this._targetFrameRate = 60;
  84902. this._trackerDuration = 2000;
  84903. this._currentFrameRate = 0;
  84904. this._improvementMode = false;
  84905. /**
  84906. * Defines an observable called when the optimizer reaches the target frame rate
  84907. */
  84908. this.onSuccessObservable = new BABYLON.Observable();
  84909. /**
  84910. * Defines an observable called when the optimizer enables an optimization
  84911. */
  84912. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  84913. /**
  84914. * Defines an observable called when the optimizer is not able to reach the target frame rate
  84915. */
  84916. this.onFailureObservable = new BABYLON.Observable();
  84917. if (!options) {
  84918. this._options = new SceneOptimizerOptions();
  84919. }
  84920. else {
  84921. this._options = options;
  84922. }
  84923. if (this._options.targetFrameRate) {
  84924. this._targetFrameRate = this._options.targetFrameRate;
  84925. }
  84926. if (this._options.trackerDuration) {
  84927. this._trackerDuration = this._options.trackerDuration;
  84928. }
  84929. if (autoGeneratePriorities) {
  84930. var priority = 0;
  84931. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  84932. var optim = _a[_i];
  84933. optim.priority = priority++;
  84934. }
  84935. }
  84936. this._improvementMode = improvementMode;
  84937. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84938. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  84939. _this._sceneDisposeObserver = null;
  84940. _this.dispose();
  84941. });
  84942. }
  84943. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  84944. /**
  84945. * Gets a boolean indicating if the optimizer is in improvement mode
  84946. */
  84947. get: function () {
  84948. return this._improvementMode;
  84949. },
  84950. enumerable: true,
  84951. configurable: true
  84952. });
  84953. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  84954. /**
  84955. * Gets the current priority level (0 at start)
  84956. */
  84957. get: function () {
  84958. return this._currentPriorityLevel;
  84959. },
  84960. enumerable: true,
  84961. configurable: true
  84962. });
  84963. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  84964. /**
  84965. * Gets the current frame rate checked by the SceneOptimizer
  84966. */
  84967. get: function () {
  84968. return this._currentFrameRate;
  84969. },
  84970. enumerable: true,
  84971. configurable: true
  84972. });
  84973. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  84974. /**
  84975. * Gets or sets the current target frame rate (60 by default)
  84976. */
  84977. get: function () {
  84978. return this._targetFrameRate;
  84979. },
  84980. /**
  84981. * Gets or sets the current target frame rate (60 by default)
  84982. */
  84983. set: function (value) {
  84984. this._targetFrameRate = value;
  84985. },
  84986. enumerable: true,
  84987. configurable: true
  84988. });
  84989. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  84990. /**
  84991. * Gets or sets the current interval between two checks (every 2000ms by default)
  84992. */
  84993. get: function () {
  84994. return this._trackerDuration;
  84995. },
  84996. /**
  84997. * Gets or sets the current interval between two checks (every 2000ms by default)
  84998. */
  84999. set: function (value) {
  85000. this._trackerDuration = value;
  85001. },
  85002. enumerable: true,
  85003. configurable: true
  85004. });
  85005. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  85006. /**
  85007. * Gets the list of active optimizations
  85008. */
  85009. get: function () {
  85010. return this._options.optimizations;
  85011. },
  85012. enumerable: true,
  85013. configurable: true
  85014. });
  85015. /**
  85016. * Stops the current optimizer
  85017. */
  85018. SceneOptimizer.prototype.stop = function () {
  85019. this._isRunning = false;
  85020. };
  85021. /**
  85022. * Reset the optimizer to initial step (current priority level = 0)
  85023. */
  85024. SceneOptimizer.prototype.reset = function () {
  85025. this._currentPriorityLevel = 0;
  85026. };
  85027. /**
  85028. * Start the optimizer. By default it will try to reach a specific framerate
  85029. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  85030. */
  85031. SceneOptimizer.prototype.start = function () {
  85032. var _this = this;
  85033. if (this._isRunning) {
  85034. return;
  85035. }
  85036. this._isRunning = true;
  85037. // Let's wait for the scene to be ready before running our check
  85038. this._scene.executeWhenReady(function () {
  85039. setTimeout(function () {
  85040. _this._checkCurrentState();
  85041. }, _this._trackerDuration);
  85042. });
  85043. };
  85044. SceneOptimizer.prototype._checkCurrentState = function () {
  85045. var _this = this;
  85046. if (!this._isRunning) {
  85047. return;
  85048. }
  85049. var scene = this._scene;
  85050. var options = this._options;
  85051. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  85052. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  85053. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  85054. this._isRunning = false;
  85055. this.onSuccessObservable.notifyObservers(this);
  85056. return;
  85057. }
  85058. // Apply current level of optimizations
  85059. var allDone = true;
  85060. var noOptimizationApplied = true;
  85061. for (var index = 0; index < options.optimizations.length; index++) {
  85062. var optimization = options.optimizations[index];
  85063. if (optimization.priority === this._currentPriorityLevel) {
  85064. noOptimizationApplied = false;
  85065. allDone = allDone && optimization.apply(scene, this);
  85066. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  85067. }
  85068. }
  85069. // If no optimization was applied, this is a failure :(
  85070. if (noOptimizationApplied) {
  85071. this._isRunning = false;
  85072. this.onFailureObservable.notifyObservers(this);
  85073. return;
  85074. }
  85075. // If all optimizations were done, move to next level
  85076. if (allDone) {
  85077. this._currentPriorityLevel++;
  85078. }
  85079. // Let's the system running for a specific amount of time before checking FPS
  85080. scene.executeWhenReady(function () {
  85081. setTimeout(function () {
  85082. _this._checkCurrentState();
  85083. }, _this._trackerDuration);
  85084. });
  85085. };
  85086. /**
  85087. * Release all resources
  85088. */
  85089. SceneOptimizer.prototype.dispose = function () {
  85090. this.stop();
  85091. this.onSuccessObservable.clear();
  85092. this.onFailureObservable.clear();
  85093. this.onNewOptimizationAppliedObservable.clear();
  85094. if (this._sceneDisposeObserver) {
  85095. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  85096. }
  85097. };
  85098. /**
  85099. * Helper function to create a SceneOptimizer with one single line of code
  85100. * @param scene defines the scene to work on
  85101. * @param options defines the options to use with the SceneOptimizer
  85102. * @param onSuccess defines a callback to call on success
  85103. * @param onFailure defines a callback to call on failure
  85104. * @returns the new SceneOptimizer object
  85105. */
  85106. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  85107. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  85108. if (onSuccess) {
  85109. optimizer.onSuccessObservable.add(function () {
  85110. onSuccess();
  85111. });
  85112. }
  85113. if (onFailure) {
  85114. optimizer.onFailureObservable.add(function () {
  85115. onFailure();
  85116. });
  85117. }
  85118. optimizer.start();
  85119. return optimizer;
  85120. };
  85121. return SceneOptimizer;
  85122. }());
  85123. BABYLON.SceneOptimizer = SceneOptimizer;
  85124. })(BABYLON || (BABYLON = {}));
  85125. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  85126. var BABYLON;
  85127. (function (BABYLON) {
  85128. var OutlineRenderer = /** @class */ (function () {
  85129. function OutlineRenderer(scene) {
  85130. this.zOffset = 1;
  85131. this._scene = scene;
  85132. }
  85133. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  85134. var _this = this;
  85135. if (useOverlay === void 0) { useOverlay = false; }
  85136. var scene = this._scene;
  85137. var engine = this._scene.getEngine();
  85138. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  85139. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  85140. return;
  85141. }
  85142. var mesh = subMesh.getRenderingMesh();
  85143. var material = subMesh.getMaterial();
  85144. if (!material || !scene.activeCamera) {
  85145. return;
  85146. }
  85147. engine.enableEffect(this._effect);
  85148. // Logarithmic depth
  85149. if (material.useLogarithmicDepth) {
  85150. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  85151. }
  85152. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  85153. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  85154. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  85155. // Bones
  85156. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85157. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85158. }
  85159. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  85160. // Alpha test
  85161. if (material && material.needAlphaTesting()) {
  85162. var alphaTexture = material.getAlphaTestTexture();
  85163. if (alphaTexture) {
  85164. this._effect.setTexture("diffuseSampler", alphaTexture);
  85165. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  85166. }
  85167. }
  85168. engine.setZOffset(-this.zOffset);
  85169. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  85170. engine.setZOffset(0);
  85171. };
  85172. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  85173. var defines = [];
  85174. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  85175. var mesh = subMesh.getMesh();
  85176. var material = subMesh.getMaterial();
  85177. if (material) {
  85178. // Alpha test
  85179. if (material.needAlphaTesting()) {
  85180. defines.push("#define ALPHATEST");
  85181. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85182. attribs.push(BABYLON.VertexBuffer.UVKind);
  85183. defines.push("#define UV1");
  85184. }
  85185. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  85186. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85187. defines.push("#define UV2");
  85188. }
  85189. }
  85190. //Logarithmic depth
  85191. if (material.useLogarithmicDepth) {
  85192. defines.push("#define LOGARITHMICDEPTH");
  85193. }
  85194. }
  85195. // Bones
  85196. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85197. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85198. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85199. if (mesh.numBoneInfluencers > 4) {
  85200. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85201. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85202. }
  85203. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85204. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  85205. }
  85206. else {
  85207. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85208. }
  85209. // Instances
  85210. if (useInstances) {
  85211. defines.push("#define INSTANCES");
  85212. attribs.push("world0");
  85213. attribs.push("world1");
  85214. attribs.push("world2");
  85215. attribs.push("world3");
  85216. }
  85217. // Get correct effect
  85218. var join = defines.join("\n");
  85219. if (this._cachedDefines !== join) {
  85220. this._cachedDefines = join;
  85221. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  85222. }
  85223. return this._effect.isReady();
  85224. };
  85225. return OutlineRenderer;
  85226. }());
  85227. BABYLON.OutlineRenderer = OutlineRenderer;
  85228. })(BABYLON || (BABYLON = {}));
  85229. //# sourceMappingURL=babylon.outlineRenderer.js.map
  85230. var BABYLON;
  85231. (function (BABYLON) {
  85232. var FaceAdjacencies = /** @class */ (function () {
  85233. function FaceAdjacencies() {
  85234. this.edges = new Array();
  85235. this.edgesConnectedCount = 0;
  85236. }
  85237. return FaceAdjacencies;
  85238. }());
  85239. var EdgesRenderer = /** @class */ (function () {
  85240. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  85241. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  85242. if (epsilon === void 0) { epsilon = 0.95; }
  85243. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  85244. this.edgesWidthScalerForOrthographic = 1000.0;
  85245. this.edgesWidthScalerForPerspective = 50.0;
  85246. this._linesPositions = new Array();
  85247. this._linesNormals = new Array();
  85248. this._linesIndices = new Array();
  85249. this._buffers = {};
  85250. this._checkVerticesInsteadOfIndices = false;
  85251. this._source = source;
  85252. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  85253. this._epsilon = epsilon;
  85254. this._prepareRessources();
  85255. this._generateEdgesLines();
  85256. }
  85257. EdgesRenderer.prototype._prepareRessources = function () {
  85258. if (this._lineShader) {
  85259. return;
  85260. }
  85261. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  85262. attributes: ["position", "normal"],
  85263. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  85264. });
  85265. this._lineShader.disableDepthWrite = true;
  85266. this._lineShader.backFaceCulling = false;
  85267. };
  85268. EdgesRenderer.prototype._rebuild = function () {
  85269. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  85270. if (buffer) {
  85271. buffer._rebuild();
  85272. }
  85273. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  85274. if (buffer) {
  85275. buffer._rebuild();
  85276. }
  85277. var scene = this._source.getScene();
  85278. var engine = scene.getEngine();
  85279. this._ib = engine.createIndexBuffer(this._linesIndices);
  85280. };
  85281. EdgesRenderer.prototype.dispose = function () {
  85282. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  85283. if (buffer) {
  85284. buffer.dispose();
  85285. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  85286. }
  85287. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  85288. if (buffer) {
  85289. buffer.dispose();
  85290. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  85291. }
  85292. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  85293. this._lineShader.dispose();
  85294. };
  85295. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  85296. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  85297. return 0;
  85298. }
  85299. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  85300. return 1;
  85301. }
  85302. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  85303. return 2;
  85304. }
  85305. return -1;
  85306. };
  85307. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  85308. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  85309. return 0;
  85310. }
  85311. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  85312. return 1;
  85313. }
  85314. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  85315. return 2;
  85316. }
  85317. return -1;
  85318. };
  85319. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  85320. var needToCreateLine;
  85321. if (edge === undefined) {
  85322. needToCreateLine = true;
  85323. }
  85324. else {
  85325. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  85326. needToCreateLine = dotProduct < this._epsilon;
  85327. }
  85328. if (needToCreateLine) {
  85329. var offset = this._linesPositions.length / 3;
  85330. var normal = p0.subtract(p1);
  85331. normal.normalize();
  85332. // Positions
  85333. this._linesPositions.push(p0.x);
  85334. this._linesPositions.push(p0.y);
  85335. this._linesPositions.push(p0.z);
  85336. this._linesPositions.push(p0.x);
  85337. this._linesPositions.push(p0.y);
  85338. this._linesPositions.push(p0.z);
  85339. this._linesPositions.push(p1.x);
  85340. this._linesPositions.push(p1.y);
  85341. this._linesPositions.push(p1.z);
  85342. this._linesPositions.push(p1.x);
  85343. this._linesPositions.push(p1.y);
  85344. this._linesPositions.push(p1.z);
  85345. // Normals
  85346. this._linesNormals.push(p1.x);
  85347. this._linesNormals.push(p1.y);
  85348. this._linesNormals.push(p1.z);
  85349. this._linesNormals.push(-1);
  85350. this._linesNormals.push(p1.x);
  85351. this._linesNormals.push(p1.y);
  85352. this._linesNormals.push(p1.z);
  85353. this._linesNormals.push(1);
  85354. this._linesNormals.push(p0.x);
  85355. this._linesNormals.push(p0.y);
  85356. this._linesNormals.push(p0.z);
  85357. this._linesNormals.push(-1);
  85358. this._linesNormals.push(p0.x);
  85359. this._linesNormals.push(p0.y);
  85360. this._linesNormals.push(p0.z);
  85361. this._linesNormals.push(1);
  85362. // Indices
  85363. this._linesIndices.push(offset);
  85364. this._linesIndices.push(offset + 1);
  85365. this._linesIndices.push(offset + 2);
  85366. this._linesIndices.push(offset);
  85367. this._linesIndices.push(offset + 2);
  85368. this._linesIndices.push(offset + 3);
  85369. }
  85370. };
  85371. EdgesRenderer.prototype._generateEdgesLines = function () {
  85372. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  85373. var indices = this._source.getIndices();
  85374. if (!indices || !positions) {
  85375. return;
  85376. }
  85377. // First let's find adjacencies
  85378. var adjacencies = new Array();
  85379. var faceNormals = new Array();
  85380. var index;
  85381. var faceAdjacencies;
  85382. // Prepare faces
  85383. for (index = 0; index < indices.length; index += 3) {
  85384. faceAdjacencies = new FaceAdjacencies();
  85385. var p0Index = indices[index];
  85386. var p1Index = indices[index + 1];
  85387. var p2Index = indices[index + 2];
  85388. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  85389. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  85390. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  85391. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  85392. faceNormal.normalize();
  85393. faceNormals.push(faceNormal);
  85394. adjacencies.push(faceAdjacencies);
  85395. }
  85396. // Scan
  85397. for (index = 0; index < adjacencies.length; index++) {
  85398. faceAdjacencies = adjacencies[index];
  85399. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  85400. var otherFaceAdjacencies = adjacencies[otherIndex];
  85401. if (faceAdjacencies.edgesConnectedCount === 3) {
  85402. break;
  85403. }
  85404. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  85405. continue;
  85406. }
  85407. var otherP0 = indices[otherIndex * 3];
  85408. var otherP1 = indices[otherIndex * 3 + 1];
  85409. var otherP2 = indices[otherIndex * 3 + 2];
  85410. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  85411. var otherEdgeIndex = 0;
  85412. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  85413. continue;
  85414. }
  85415. switch (edgeIndex) {
  85416. case 0:
  85417. if (this._checkVerticesInsteadOfIndices) {
  85418. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85419. }
  85420. else {
  85421. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  85422. }
  85423. break;
  85424. case 1:
  85425. if (this._checkVerticesInsteadOfIndices) {
  85426. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85427. }
  85428. else {
  85429. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  85430. }
  85431. break;
  85432. case 2:
  85433. if (this._checkVerticesInsteadOfIndices) {
  85434. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85435. }
  85436. else {
  85437. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  85438. }
  85439. break;
  85440. }
  85441. if (otherEdgeIndex === -1) {
  85442. continue;
  85443. }
  85444. faceAdjacencies.edges[edgeIndex] = otherIndex;
  85445. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  85446. faceAdjacencies.edgesConnectedCount++;
  85447. otherFaceAdjacencies.edgesConnectedCount++;
  85448. if (faceAdjacencies.edgesConnectedCount === 3) {
  85449. break;
  85450. }
  85451. }
  85452. }
  85453. }
  85454. // Create lines
  85455. for (index = 0; index < adjacencies.length; index++) {
  85456. // 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
  85457. var current = adjacencies[index];
  85458. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  85459. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  85460. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  85461. }
  85462. // Merge into a single mesh
  85463. var engine = this._source.getScene().getEngine();
  85464. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  85465. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  85466. this._ib = engine.createIndexBuffer(this._linesIndices);
  85467. this._indicesCount = this._linesIndices.length;
  85468. };
  85469. EdgesRenderer.prototype.render = function () {
  85470. var scene = this._source.getScene();
  85471. if (!this._lineShader.isReady() || !scene.activeCamera) {
  85472. return;
  85473. }
  85474. var engine = scene.getEngine();
  85475. this._lineShader._preBind();
  85476. // VBOs
  85477. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  85478. scene.resetCachedMaterial();
  85479. this._lineShader.setColor4("color", this._source.edgesColor);
  85480. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  85481. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  85482. }
  85483. else {
  85484. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  85485. }
  85486. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  85487. this._lineShader.bind(this._source.getWorldMatrix());
  85488. // Draw order
  85489. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  85490. this._lineShader.unbind();
  85491. engine.setDepthWrite(true);
  85492. };
  85493. return EdgesRenderer;
  85494. }());
  85495. BABYLON.EdgesRenderer = EdgesRenderer;
  85496. })(BABYLON || (BABYLON = {}));
  85497. //# sourceMappingURL=babylon.edgesRenderer.js.map
  85498. var __assign = (this && this.__assign) || Object.assign || function(t) {
  85499. for (var s, i = 1, n = arguments.length; i < n; i++) {
  85500. s = arguments[i];
  85501. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  85502. t[p] = s[p];
  85503. }
  85504. return t;
  85505. };
  85506. var BABYLON;
  85507. (function (BABYLON) {
  85508. /**
  85509. * The effect layer Helps adding post process effect blended with the main pass.
  85510. *
  85511. * This can be for instance use to generate glow or higlight effects on the scene.
  85512. *
  85513. * The effect layer class can not be used directly and is intented to inherited from to be
  85514. * customized per effects.
  85515. */
  85516. var EffectLayer = /** @class */ (function () {
  85517. /**
  85518. * Instantiates a new effect Layer and references it in the scene.
  85519. * @param name The name of the layer
  85520. * @param scene The scene to use the layer in
  85521. */
  85522. function EffectLayer(
  85523. /** The Friendly of the effect in the scene */
  85524. name, scene) {
  85525. this.name = name;
  85526. this._vertexBuffers = {};
  85527. this._maxSize = 0;
  85528. this._mainTextureDesiredSize = { width: 0, height: 0 };
  85529. this._shouldRender = true;
  85530. this._postProcesses = [];
  85531. this._textures = [];
  85532. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  85533. /**
  85534. * The clear color of the texture used to generate the glow map.
  85535. */
  85536. this.neutralColor = new BABYLON.Color4();
  85537. /**
  85538. * Specifies wether the highlight layer is enabled or not.
  85539. */
  85540. this.isEnabled = true;
  85541. /**
  85542. * An event triggered when the effect layer has been disposed.
  85543. */
  85544. this.onDisposeObservable = new BABYLON.Observable();
  85545. /**
  85546. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  85547. */
  85548. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  85549. /**
  85550. * An event triggered when the generated texture is being merged in the scene.
  85551. */
  85552. this.onBeforeComposeObservable = new BABYLON.Observable();
  85553. /**
  85554. * An event triggered when the generated texture has been merged in the scene.
  85555. */
  85556. this.onAfterComposeObservable = new BABYLON.Observable();
  85557. /**
  85558. * An event triggered when the efffect layer changes its size.
  85559. */
  85560. this.onSizeChangedObservable = new BABYLON.Observable();
  85561. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85562. this._engine = scene.getEngine();
  85563. this._maxSize = this._engine.getCaps().maxTextureSize;
  85564. this._scene.effectLayers.push(this);
  85565. // Generate Buffers
  85566. this._generateIndexBuffer();
  85567. this._genrateVertexBuffer();
  85568. }
  85569. Object.defineProperty(EffectLayer.prototype, "camera", {
  85570. /**
  85571. * Gets the camera attached to the layer.
  85572. */
  85573. get: function () {
  85574. return this._effectLayerOptions.camera;
  85575. },
  85576. enumerable: true,
  85577. configurable: true
  85578. });
  85579. /**
  85580. * Initializes the effect layer with the required options.
  85581. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  85582. */
  85583. EffectLayer.prototype._init = function (options) {
  85584. // Adapt options
  85585. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  85586. this._setMainTextureSize();
  85587. this._createMainTexture();
  85588. this._createTextureAndPostProcesses();
  85589. this._mergeEffect = this._createMergeEffect();
  85590. };
  85591. /**
  85592. * Generates the index buffer of the full screen quad blending to the main canvas.
  85593. */
  85594. EffectLayer.prototype._generateIndexBuffer = function () {
  85595. // Indices
  85596. var indices = [];
  85597. indices.push(0);
  85598. indices.push(1);
  85599. indices.push(2);
  85600. indices.push(0);
  85601. indices.push(2);
  85602. indices.push(3);
  85603. this._indexBuffer = this._engine.createIndexBuffer(indices);
  85604. };
  85605. /**
  85606. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  85607. */
  85608. EffectLayer.prototype._genrateVertexBuffer = function () {
  85609. // VBO
  85610. var vertices = [];
  85611. vertices.push(1, 1);
  85612. vertices.push(-1, 1);
  85613. vertices.push(-1, -1);
  85614. vertices.push(1, -1);
  85615. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  85616. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  85617. };
  85618. /**
  85619. * Sets the main texture desired size which is the closest power of two
  85620. * of the engine canvas size.
  85621. */
  85622. EffectLayer.prototype._setMainTextureSize = function () {
  85623. if (this._effectLayerOptions.mainTextureFixedSize) {
  85624. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  85625. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  85626. }
  85627. else {
  85628. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  85629. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  85630. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  85631. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  85632. }
  85633. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  85634. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  85635. };
  85636. /**
  85637. * Creates the main texture for the effect layer.
  85638. */
  85639. EffectLayer.prototype._createMainTexture = function () {
  85640. var _this = this;
  85641. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  85642. width: this._mainTextureDesiredSize.width,
  85643. height: this._mainTextureDesiredSize.height
  85644. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85645. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  85646. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85647. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85648. this._mainTexture.anisotropicFilteringLevel = 1;
  85649. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85650. this._mainTexture.renderParticles = false;
  85651. this._mainTexture.renderList = null;
  85652. this._mainTexture.ignoreCameraViewport = true;
  85653. // Custom render function
  85654. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  85655. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  85656. var index;
  85657. var engine = _this._scene.getEngine();
  85658. if (depthOnlySubMeshes.length) {
  85659. engine.setColorWrite(false);
  85660. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  85661. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  85662. }
  85663. engine.setColorWrite(true);
  85664. }
  85665. for (index = 0; index < opaqueSubMeshes.length; index++) {
  85666. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  85667. }
  85668. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  85669. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  85670. }
  85671. for (index = 0; index < transparentSubMeshes.length; index++) {
  85672. _this._renderSubMesh(transparentSubMeshes.data[index]);
  85673. }
  85674. };
  85675. this._mainTexture.onClearObservable.add(function (engine) {
  85676. engine.clear(_this.neutralColor, true, true, true);
  85677. });
  85678. };
  85679. /**
  85680. * Checks for the readiness of the element composing the layer.
  85681. * @param subMesh the mesh to check for
  85682. * @param useInstances specify wether or not to use instances to render the mesh
  85683. * @param emissiveTexture the associated emissive texture used to generate the glow
  85684. * @return true if ready otherwise, false
  85685. */
  85686. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  85687. var material = subMesh.getMaterial();
  85688. if (!material) {
  85689. return false;
  85690. }
  85691. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  85692. return false;
  85693. }
  85694. var defines = [];
  85695. var attribs = [BABYLON.VertexBuffer.PositionKind];
  85696. var mesh = subMesh.getMesh();
  85697. var uv1 = false;
  85698. var uv2 = false;
  85699. // Alpha test
  85700. if (material && material.needAlphaTesting()) {
  85701. var alphaTexture = material.getAlphaTestTexture();
  85702. if (alphaTexture) {
  85703. defines.push("#define ALPHATEST");
  85704. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  85705. alphaTexture.coordinatesIndex === 1) {
  85706. defines.push("#define DIFFUSEUV2");
  85707. uv2 = true;
  85708. }
  85709. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85710. defines.push("#define DIFFUSEUV1");
  85711. uv1 = true;
  85712. }
  85713. }
  85714. }
  85715. // Emissive
  85716. if (emissiveTexture) {
  85717. defines.push("#define EMISSIVE");
  85718. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  85719. emissiveTexture.coordinatesIndex === 1) {
  85720. defines.push("#define EMISSIVEUV2");
  85721. uv2 = true;
  85722. }
  85723. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85724. defines.push("#define EMISSIVEUV1");
  85725. uv1 = true;
  85726. }
  85727. }
  85728. if (uv1) {
  85729. attribs.push(BABYLON.VertexBuffer.UVKind);
  85730. defines.push("#define UV1");
  85731. }
  85732. if (uv2) {
  85733. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85734. defines.push("#define UV2");
  85735. }
  85736. // Bones
  85737. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85738. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85739. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85740. if (mesh.numBoneInfluencers > 4) {
  85741. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85742. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85743. }
  85744. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85745. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  85746. }
  85747. else {
  85748. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85749. }
  85750. // Instances
  85751. if (useInstances) {
  85752. defines.push("#define INSTANCES");
  85753. attribs.push("world0");
  85754. attribs.push("world1");
  85755. attribs.push("world2");
  85756. attribs.push("world3");
  85757. }
  85758. // Get correct effect
  85759. var join = defines.join("\n");
  85760. if (this._cachedDefines !== join) {
  85761. this._cachedDefines = join;
  85762. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  85763. }
  85764. return this._effectLayerMapGenerationEffect.isReady();
  85765. };
  85766. /**
  85767. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  85768. */
  85769. EffectLayer.prototype.render = function () {
  85770. var currentEffect = this._mergeEffect;
  85771. // Check
  85772. if (!currentEffect.isReady())
  85773. return;
  85774. for (var i = 0; i < this._postProcesses.length; i++) {
  85775. if (!this._postProcesses[i].isReady()) {
  85776. return;
  85777. }
  85778. }
  85779. var engine = this._scene.getEngine();
  85780. this.onBeforeComposeObservable.notifyObservers(this);
  85781. // Render
  85782. engine.enableEffect(currentEffect);
  85783. engine.setState(false);
  85784. // VBOs
  85785. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  85786. // Cache
  85787. var previousAlphaMode = engine.getAlphaMode();
  85788. // Go Blend.
  85789. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  85790. // Blends the map on the main canvas.
  85791. this._internalRender(currentEffect);
  85792. // Restore Alpha
  85793. engine.setAlphaMode(previousAlphaMode);
  85794. this.onAfterComposeObservable.notifyObservers(this);
  85795. // Handle size changes.
  85796. var size = this._mainTexture.getSize();
  85797. this._setMainTextureSize();
  85798. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  85799. // Recreate RTT and post processes on size change.
  85800. this.onSizeChangedObservable.notifyObservers(this);
  85801. this._disposeTextureAndPostProcesses();
  85802. this._createMainTexture();
  85803. this._createTextureAndPostProcesses();
  85804. }
  85805. };
  85806. /**
  85807. * Determine if a given mesh will be used in the current effect.
  85808. * @param mesh mesh to test
  85809. * @returns true if the mesh will be used
  85810. */
  85811. EffectLayer.prototype.hasMesh = function (mesh) {
  85812. return true;
  85813. };
  85814. /**
  85815. * Returns true if the layer contains information to display, otherwise false.
  85816. * @returns true if the glow layer should be rendered
  85817. */
  85818. EffectLayer.prototype.shouldRender = function () {
  85819. return this.isEnabled && this._shouldRender;
  85820. };
  85821. /**
  85822. * Returns true if the mesh should render, otherwise false.
  85823. * @param mesh The mesh to render
  85824. * @returns true if it should render otherwise false
  85825. */
  85826. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  85827. return true;
  85828. };
  85829. /**
  85830. * Returns true if the mesh should render, otherwise false.
  85831. * @param mesh The mesh to render
  85832. * @returns true if it should render otherwise false
  85833. */
  85834. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  85835. return true;
  85836. };
  85837. /**
  85838. * Renders the submesh passed in parameter to the generation map.
  85839. */
  85840. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  85841. var _this = this;
  85842. if (!this.shouldRender()) {
  85843. return;
  85844. }
  85845. var material = subMesh.getMaterial();
  85846. var mesh = subMesh.getRenderingMesh();
  85847. var scene = this._scene;
  85848. var engine = scene.getEngine();
  85849. if (!material) {
  85850. return;
  85851. }
  85852. // Do not block in blend mode.
  85853. if (material.needAlphaBlendingForMesh(mesh)) {
  85854. return;
  85855. }
  85856. // Culling
  85857. engine.setState(material.backFaceCulling);
  85858. // Managing instances
  85859. var batch = mesh._getInstancesRenderList(subMesh._id);
  85860. if (batch.mustReturn) {
  85861. return;
  85862. }
  85863. // Early Exit per mesh
  85864. if (!this._shouldRenderMesh(mesh)) {
  85865. return;
  85866. }
  85867. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  85868. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  85869. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  85870. engine.enableEffect(this._effectLayerMapGenerationEffect);
  85871. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  85872. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  85873. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  85874. // Alpha test
  85875. if (material && material.needAlphaTesting()) {
  85876. var alphaTexture = material.getAlphaTestTexture();
  85877. if (alphaTexture) {
  85878. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  85879. var textureMatrix = alphaTexture.getTextureMatrix();
  85880. if (textureMatrix) {
  85881. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  85882. }
  85883. }
  85884. }
  85885. // Glow emissive only
  85886. if (this._emissiveTextureAndColor.texture) {
  85887. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  85888. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  85889. }
  85890. // Bones
  85891. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85892. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85893. }
  85894. // Draw
  85895. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  85896. }
  85897. else {
  85898. // Need to reset refresh rate of the shadowMap
  85899. this._mainTexture.resetRefreshCounter();
  85900. }
  85901. };
  85902. /**
  85903. * Rebuild the required buffers.
  85904. * @ignore Internal use only.
  85905. */
  85906. EffectLayer.prototype._rebuild = function () {
  85907. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85908. if (vb) {
  85909. vb._rebuild();
  85910. }
  85911. this._generateIndexBuffer();
  85912. };
  85913. /**
  85914. * Dispose only the render target textures and post process.
  85915. */
  85916. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  85917. this._mainTexture.dispose();
  85918. for (var i = 0; i < this._postProcesses.length; i++) {
  85919. if (this._postProcesses[i]) {
  85920. this._postProcesses[i].dispose();
  85921. }
  85922. }
  85923. this._postProcesses = [];
  85924. for (var i = 0; i < this._textures.length; i++) {
  85925. if (this._textures[i]) {
  85926. this._textures[i].dispose();
  85927. }
  85928. }
  85929. this._textures = [];
  85930. };
  85931. /**
  85932. * Dispose the highlight layer and free resources.
  85933. */
  85934. EffectLayer.prototype.dispose = function () {
  85935. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85936. if (vertexBuffer) {
  85937. vertexBuffer.dispose();
  85938. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85939. }
  85940. if (this._indexBuffer) {
  85941. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85942. this._indexBuffer = null;
  85943. }
  85944. // Clean textures and post processes
  85945. this._disposeTextureAndPostProcesses();
  85946. // Remove from scene
  85947. var index = this._scene.effectLayers.indexOf(this, 0);
  85948. if (index > -1) {
  85949. this._scene.effectLayers.splice(index, 1);
  85950. }
  85951. // Callback
  85952. this.onDisposeObservable.notifyObservers(this);
  85953. this.onDisposeObservable.clear();
  85954. this.onBeforeRenderMainTextureObservable.clear();
  85955. this.onBeforeComposeObservable.clear();
  85956. this.onAfterComposeObservable.clear();
  85957. this.onSizeChangedObservable.clear();
  85958. };
  85959. return EffectLayer;
  85960. }());
  85961. BABYLON.EffectLayer = EffectLayer;
  85962. })(BABYLON || (BABYLON = {}));
  85963. //# sourceMappingURL=babylon.effectLayer.js.map
  85964. var BABYLON;
  85965. (function (BABYLON) {
  85966. /**
  85967. * Special Glow Blur post process only blurring the alpha channel
  85968. * It enforces keeping the most luminous color in the color channel.
  85969. */
  85970. var GlowBlurPostProcess = /** @class */ (function (_super) {
  85971. __extends(GlowBlurPostProcess, _super);
  85972. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  85973. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85974. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  85975. _this.direction = direction;
  85976. _this.kernel = kernel;
  85977. _this.onApplyObservable.add(function (effect) {
  85978. effect.setFloat2("screenSize", _this.width, _this.height);
  85979. effect.setVector2("direction", _this.direction);
  85980. effect.setFloat("blurWidth", _this.kernel);
  85981. });
  85982. return _this;
  85983. }
  85984. return GlowBlurPostProcess;
  85985. }(BABYLON.PostProcess));
  85986. /**
  85987. * The highlight layer Helps adding a glow effect around a mesh.
  85988. *
  85989. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  85990. * glowy meshes to your scene.
  85991. *
  85992. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  85993. */
  85994. var HighlightLayer = /** @class */ (function (_super) {
  85995. __extends(HighlightLayer, _super);
  85996. /**
  85997. * Instantiates a new highlight Layer and references it to the scene..
  85998. * @param name The name of the layer
  85999. * @param scene The scene to use the layer in
  86000. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  86001. */
  86002. function HighlightLayer(name, scene, options) {
  86003. var _this = _super.call(this, name, scene) || this;
  86004. _this.name = name;
  86005. /**
  86006. * Specifies whether or not the inner glow is ACTIVE in the layer.
  86007. */
  86008. _this.innerGlow = true;
  86009. /**
  86010. * Specifies whether or not the outer glow is ACTIVE in the layer.
  86011. */
  86012. _this.outerGlow = true;
  86013. /**
  86014. * An event triggered when the highlight layer is being blurred.
  86015. */
  86016. _this.onBeforeBlurObservable = new BABYLON.Observable();
  86017. /**
  86018. * An event triggered when the highlight layer has been blurred.
  86019. */
  86020. _this.onAfterBlurObservable = new BABYLON.Observable();
  86021. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  86022. _this._meshes = {};
  86023. _this._excludedMeshes = {};
  86024. _this.neutralColor = HighlightLayer.NeutralColor;
  86025. // Warn on stencil
  86026. if (!_this._engine.isStencilEnable) {
  86027. 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 }");
  86028. }
  86029. // Adapt options
  86030. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  86031. // Initialize the layer
  86032. _this._init({
  86033. alphaBlendingMode: _this._options.alphaBlendingMode,
  86034. camera: _this._options.camera,
  86035. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  86036. mainTextureRatio: _this._options.mainTextureRatio
  86037. });
  86038. // Do not render as long as no meshes have been added
  86039. _this._shouldRender = false;
  86040. return _this;
  86041. }
  86042. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  86043. /**
  86044. * Gets the horizontal size of the blur.
  86045. */
  86046. get: function () {
  86047. return this._horizontalBlurPostprocess.kernel;
  86048. },
  86049. /**
  86050. * Specifies the horizontal size of the blur.
  86051. */
  86052. set: function (value) {
  86053. this._horizontalBlurPostprocess.kernel = value;
  86054. },
  86055. enumerable: true,
  86056. configurable: true
  86057. });
  86058. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  86059. /**
  86060. * Gets the vertical size of the blur.
  86061. */
  86062. get: function () {
  86063. return this._verticalBlurPostprocess.kernel;
  86064. },
  86065. /**
  86066. * Specifies the vertical size of the blur.
  86067. */
  86068. set: function (value) {
  86069. this._verticalBlurPostprocess.kernel = value;
  86070. },
  86071. enumerable: true,
  86072. configurable: true
  86073. });
  86074. /**
  86075. * Get the effect name of the layer.
  86076. * @return The effect name
  86077. */
  86078. HighlightLayer.prototype.getEffectName = function () {
  86079. return HighlightLayer.EffectName;
  86080. };
  86081. /**
  86082. * Create the merge effect. This is the shader use to blit the information back
  86083. * to the main canvas at the end of the scene rendering.
  86084. */
  86085. HighlightLayer.prototype._createMergeEffect = function () {
  86086. // Effect
  86087. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  86088. };
  86089. /**
  86090. * Creates the render target textures and post processes used in the highlight layer.
  86091. */
  86092. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  86093. var _this = this;
  86094. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  86095. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  86096. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  86097. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  86098. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  86099. width: blurTextureWidth,
  86100. height: blurTextureHeight
  86101. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86102. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86103. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86104. this._blurTexture.anisotropicFilteringLevel = 16;
  86105. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  86106. this._blurTexture.renderParticles = false;
  86107. this._blurTexture.ignoreCameraViewport = true;
  86108. this._textures = [this._blurTexture];
  86109. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  86110. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86111. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  86112. effect.setTexture("textureSampler", _this._mainTexture);
  86113. });
  86114. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86115. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86116. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86117. });
  86118. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86119. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  86120. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86121. });
  86122. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86123. }
  86124. else {
  86125. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  86126. width: blurTextureWidth,
  86127. height: blurTextureHeight
  86128. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86129. this._horizontalBlurPostprocess.width = blurTextureWidth;
  86130. this._horizontalBlurPostprocess.height = blurTextureHeight;
  86131. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86132. effect.setTexture("textureSampler", _this._mainTexture);
  86133. });
  86134. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  86135. width: blurTextureWidth,
  86136. height: blurTextureHeight
  86137. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86138. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86139. }
  86140. this._mainTexture.onAfterUnbindObservable.add(function () {
  86141. _this.onBeforeBlurObservable.notifyObservers(_this);
  86142. var internalTexture = _this._blurTexture.getInternalTexture();
  86143. if (internalTexture) {
  86144. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  86145. }
  86146. _this.onAfterBlurObservable.notifyObservers(_this);
  86147. });
  86148. // Prevent autoClear.
  86149. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  86150. };
  86151. /**
  86152. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  86153. */
  86154. HighlightLayer.prototype.needStencil = function () {
  86155. return true;
  86156. };
  86157. /**
  86158. * Checks for the readiness of the element composing the layer.
  86159. * @param subMesh the mesh to check for
  86160. * @param useInstances specify wether or not to use instances to render the mesh
  86161. * @param emissiveTexture the associated emissive texture used to generate the glow
  86162. * @return true if ready otherwise, false
  86163. */
  86164. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  86165. var material = subMesh.getMaterial();
  86166. var mesh = subMesh.getRenderingMesh();
  86167. if (!material || !mesh || !this._meshes) {
  86168. return false;
  86169. }
  86170. var emissiveTexture = null;
  86171. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  86172. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  86173. emissiveTexture = material.emissiveTexture;
  86174. }
  86175. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  86176. };
  86177. /**
  86178. * Implementation specific of rendering the generating effect on the main canvas.
  86179. * @param effect The effect used to render through
  86180. */
  86181. HighlightLayer.prototype._internalRender = function (effect) {
  86182. // Texture
  86183. effect.setTexture("textureSampler", this._blurTexture);
  86184. // Cache
  86185. var engine = this._engine;
  86186. var previousStencilBuffer = engine.getStencilBuffer();
  86187. var previousStencilFunction = engine.getStencilFunction();
  86188. var previousStencilMask = engine.getStencilMask();
  86189. var previousStencilOperationPass = engine.getStencilOperationPass();
  86190. var previousStencilOperationFail = engine.getStencilOperationFail();
  86191. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  86192. var previousStencilReference = engine.getStencilFunctionReference();
  86193. // Stencil operations
  86194. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  86195. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  86196. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  86197. // Draw order
  86198. engine.setStencilMask(0x00);
  86199. engine.setStencilBuffer(true);
  86200. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  86201. // 2 passes inner outer
  86202. if (this.outerGlow) {
  86203. effect.setFloat("offset", 0);
  86204. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  86205. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86206. }
  86207. if (this.innerGlow) {
  86208. effect.setFloat("offset", 1);
  86209. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  86210. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86211. }
  86212. // Restore Cache
  86213. engine.setStencilFunction(previousStencilFunction);
  86214. engine.setStencilMask(previousStencilMask);
  86215. engine.setStencilBuffer(previousStencilBuffer);
  86216. engine.setStencilOperationPass(previousStencilOperationPass);
  86217. engine.setStencilOperationFail(previousStencilOperationFail);
  86218. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  86219. engine.setStencilFunctionReference(previousStencilReference);
  86220. };
  86221. /**
  86222. * Returns true if the layer contains information to display, otherwise false.
  86223. */
  86224. HighlightLayer.prototype.shouldRender = function () {
  86225. if (_super.prototype.shouldRender.call(this)) {
  86226. return this._meshes ? true : false;
  86227. }
  86228. return false;
  86229. };
  86230. /**
  86231. * Returns true if the mesh should render, otherwise false.
  86232. * @param mesh The mesh to render
  86233. * @returns true if it should render otherwise false
  86234. */
  86235. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  86236. // Excluded Mesh
  86237. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  86238. return false;
  86239. }
  86240. ;
  86241. return true;
  86242. };
  86243. /**
  86244. * Sets the required values for both the emissive texture and and the main color.
  86245. */
  86246. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  86247. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  86248. if (highlightLayerMesh) {
  86249. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  86250. }
  86251. else {
  86252. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  86253. }
  86254. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  86255. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  86256. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  86257. }
  86258. else {
  86259. this._emissiveTextureAndColor.texture = null;
  86260. }
  86261. };
  86262. /**
  86263. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  86264. * @param mesh The mesh to exclude from the highlight layer
  86265. */
  86266. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  86267. if (!this._excludedMeshes) {
  86268. return;
  86269. }
  86270. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86271. if (!meshExcluded) {
  86272. this._excludedMeshes[mesh.uniqueId] = {
  86273. mesh: mesh,
  86274. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  86275. mesh.getEngine().setStencilBuffer(false);
  86276. }),
  86277. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  86278. mesh.getEngine().setStencilBuffer(true);
  86279. }),
  86280. };
  86281. }
  86282. };
  86283. /**
  86284. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  86285. * @param mesh The mesh to highlight
  86286. */
  86287. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  86288. if (!this._excludedMeshes) {
  86289. return;
  86290. }
  86291. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86292. if (meshExcluded) {
  86293. if (meshExcluded.beforeRender) {
  86294. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  86295. }
  86296. if (meshExcluded.afterRender) {
  86297. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  86298. }
  86299. }
  86300. this._excludedMeshes[mesh.uniqueId] = null;
  86301. };
  86302. /**
  86303. * Determine if a given mesh will be highlighted by the current HighlightLayer
  86304. * @param mesh mesh to test
  86305. * @returns true if the mesh will be highlighted by the current HighlightLayer
  86306. */
  86307. HighlightLayer.prototype.hasMesh = function (mesh) {
  86308. if (!this._meshes) {
  86309. return false;
  86310. }
  86311. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  86312. };
  86313. /**
  86314. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  86315. * @param mesh The mesh to highlight
  86316. * @param color The color of the highlight
  86317. * @param glowEmissiveOnly Extract the glow from the emissive texture
  86318. */
  86319. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  86320. var _this = this;
  86321. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  86322. if (!this._meshes) {
  86323. return;
  86324. }
  86325. var meshHighlight = this._meshes[mesh.uniqueId];
  86326. if (meshHighlight) {
  86327. meshHighlight.color = color;
  86328. }
  86329. else {
  86330. this._meshes[mesh.uniqueId] = {
  86331. mesh: mesh,
  86332. color: color,
  86333. // Lambda required for capture due to Observable this context
  86334. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  86335. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  86336. _this._defaultStencilReference(mesh);
  86337. }
  86338. else {
  86339. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  86340. }
  86341. }),
  86342. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  86343. glowEmissiveOnly: glowEmissiveOnly
  86344. };
  86345. }
  86346. this._shouldRender = true;
  86347. };
  86348. /**
  86349. * Remove a mesh from the highlight layer in order to make it stop glowing.
  86350. * @param mesh The mesh to highlight
  86351. */
  86352. HighlightLayer.prototype.removeMesh = function (mesh) {
  86353. if (!this._meshes) {
  86354. return;
  86355. }
  86356. var meshHighlight = this._meshes[mesh.uniqueId];
  86357. if (meshHighlight) {
  86358. if (meshHighlight.observerHighlight) {
  86359. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  86360. }
  86361. if (meshHighlight.observerDefault) {
  86362. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  86363. }
  86364. delete this._meshes[mesh.uniqueId];
  86365. }
  86366. this._shouldRender = false;
  86367. for (var meshHighlightToCheck in this._meshes) {
  86368. if (this._meshes[meshHighlightToCheck]) {
  86369. this._shouldRender = true;
  86370. break;
  86371. }
  86372. }
  86373. };
  86374. /**
  86375. * Force the stencil to the normal expected value for none glowing parts
  86376. */
  86377. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  86378. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  86379. };
  86380. /**
  86381. * Free any resources and references associated to a mesh.
  86382. * Internal use
  86383. * @param mesh The mesh to free.
  86384. */
  86385. HighlightLayer.prototype._disposeMesh = function (mesh) {
  86386. this.removeMesh(mesh);
  86387. this.removeExcludedMesh(mesh);
  86388. };
  86389. /**
  86390. * Dispose the highlight layer and free resources.
  86391. */
  86392. HighlightLayer.prototype.dispose = function () {
  86393. if (this._meshes) {
  86394. // Clean mesh references
  86395. for (var id in this._meshes) {
  86396. var meshHighlight = this._meshes[id];
  86397. if (meshHighlight && meshHighlight.mesh) {
  86398. if (meshHighlight.observerHighlight) {
  86399. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  86400. }
  86401. if (meshHighlight.observerDefault) {
  86402. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  86403. }
  86404. }
  86405. }
  86406. this._meshes = null;
  86407. }
  86408. if (this._excludedMeshes) {
  86409. for (var id in this._excludedMeshes) {
  86410. var meshHighlight = this._excludedMeshes[id];
  86411. if (meshHighlight) {
  86412. if (meshHighlight.beforeRender) {
  86413. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  86414. }
  86415. if (meshHighlight.afterRender) {
  86416. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  86417. }
  86418. }
  86419. }
  86420. this._excludedMeshes = null;
  86421. }
  86422. _super.prototype.dispose.call(this);
  86423. };
  86424. /**
  86425. * Effect Name of the highlight layer.
  86426. */
  86427. HighlightLayer.EffectName = "HighlightLayer";
  86428. /**
  86429. * The neutral color used during the preparation of the glow effect.
  86430. * This is black by default as the blend operation is a blend operation.
  86431. */
  86432. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  86433. /**
  86434. * Stencil value used for glowing meshes.
  86435. */
  86436. HighlightLayer.GlowingMeshStencilReference = 0x02;
  86437. /**
  86438. * Stencil value used for the other meshes in the scene.
  86439. */
  86440. HighlightLayer.NormalMeshStencilReference = 0x01;
  86441. return HighlightLayer;
  86442. }(BABYLON.EffectLayer));
  86443. BABYLON.HighlightLayer = HighlightLayer;
  86444. })(BABYLON || (BABYLON = {}));
  86445. //# sourceMappingURL=babylon.highlightLayer.js.map
  86446. var BABYLON;
  86447. (function (BABYLON) {
  86448. /**
  86449. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  86450. *
  86451. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  86452. * glowy meshes to your scene.
  86453. *
  86454. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  86455. */
  86456. var GlowLayer = /** @class */ (function (_super) {
  86457. __extends(GlowLayer, _super);
  86458. /**
  86459. * Instantiates a new glow Layer and references it to the scene.
  86460. * @param name The name of the layer
  86461. * @param scene The scene to use the layer in
  86462. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  86463. */
  86464. function GlowLayer(name, scene, options) {
  86465. var _this = _super.call(this, name, scene) || this;
  86466. _this.name = name;
  86467. _this._intensity = 1.0;
  86468. _this._includedOnlyMeshes = [];
  86469. _this._excludedMeshes = [];
  86470. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  86471. // Adapt options
  86472. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  86473. // Initialize the layer
  86474. _this._init({
  86475. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  86476. camera: _this._options.camera,
  86477. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  86478. mainTextureRatio: _this._options.mainTextureRatio
  86479. });
  86480. return _this;
  86481. }
  86482. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  86483. /**
  86484. * Gets the kernel size of the blur.
  86485. */
  86486. get: function () {
  86487. return this._horizontalBlurPostprocess1.kernel;
  86488. },
  86489. /**
  86490. * Sets the kernel size of the blur.
  86491. */
  86492. set: function (value) {
  86493. this._horizontalBlurPostprocess1.kernel = value;
  86494. this._verticalBlurPostprocess1.kernel = value;
  86495. this._horizontalBlurPostprocess2.kernel = value;
  86496. this._verticalBlurPostprocess2.kernel = value;
  86497. },
  86498. enumerable: true,
  86499. configurable: true
  86500. });
  86501. Object.defineProperty(GlowLayer.prototype, "intensity", {
  86502. /**
  86503. * Gets the glow intensity.
  86504. */
  86505. get: function () {
  86506. return this._intensity;
  86507. },
  86508. /**
  86509. * Sets the glow intensity.
  86510. */
  86511. set: function (value) {
  86512. this._intensity = value;
  86513. },
  86514. enumerable: true,
  86515. configurable: true
  86516. });
  86517. /**
  86518. * Get the effect name of the layer.
  86519. * @return The effect name
  86520. */
  86521. GlowLayer.prototype.getEffectName = function () {
  86522. return GlowLayer.EffectName;
  86523. };
  86524. /**
  86525. * Create the merge effect. This is the shader use to blit the information back
  86526. * to the main canvas at the end of the scene rendering.
  86527. */
  86528. GlowLayer.prototype._createMergeEffect = function () {
  86529. // Effect
  86530. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  86531. };
  86532. /**
  86533. * Creates the render target textures and post processes used in the glow layer.
  86534. */
  86535. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  86536. var _this = this;
  86537. var blurTextureWidth = this._mainTextureDesiredSize.width;
  86538. var blurTextureHeight = this._mainTextureDesiredSize.height;
  86539. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  86540. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  86541. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  86542. width: blurTextureWidth,
  86543. height: blurTextureHeight
  86544. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86545. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86546. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86547. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86548. this._blurTexture1.renderParticles = false;
  86549. this._blurTexture1.ignoreCameraViewport = true;
  86550. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  86551. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  86552. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  86553. width: blurTextureWidth2,
  86554. height: blurTextureHeight2
  86555. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86556. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86557. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86558. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86559. this._blurTexture2.renderParticles = false;
  86560. this._blurTexture2.ignoreCameraViewport = true;
  86561. this._textures = [this._blurTexture1, this._blurTexture2];
  86562. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  86563. width: blurTextureWidth,
  86564. height: blurTextureHeight
  86565. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86566. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  86567. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  86568. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  86569. effect.setTexture("textureSampler", _this._mainTexture);
  86570. });
  86571. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  86572. width: blurTextureWidth,
  86573. height: blurTextureHeight
  86574. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86575. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  86576. width: blurTextureWidth2,
  86577. height: blurTextureHeight2
  86578. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86579. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  86580. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  86581. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  86582. effect.setTexture("textureSampler", _this._blurTexture1);
  86583. });
  86584. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  86585. width: blurTextureWidth2,
  86586. height: blurTextureHeight2
  86587. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86588. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  86589. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  86590. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  86591. this._mainTexture.samples = this._options.mainTextureSamples;
  86592. this._mainTexture.onAfterUnbindObservable.add(function () {
  86593. var internalTexture = _this._blurTexture1.getInternalTexture();
  86594. if (internalTexture) {
  86595. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  86596. internalTexture = _this._blurTexture2.getInternalTexture();
  86597. if (internalTexture) {
  86598. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  86599. }
  86600. }
  86601. });
  86602. // Prevent autoClear.
  86603. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  86604. };
  86605. /**
  86606. * Checks for the readiness of the element composing the layer.
  86607. * @param subMesh the mesh to check for
  86608. * @param useInstances specify wether or not to use instances to render the mesh
  86609. * @param emissiveTexture the associated emissive texture used to generate the glow
  86610. * @return true if ready otherwise, false
  86611. */
  86612. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  86613. var material = subMesh.getMaterial();
  86614. var mesh = subMesh.getRenderingMesh();
  86615. if (!material || !mesh) {
  86616. return false;
  86617. }
  86618. var emissiveTexture = material.emissiveTexture;
  86619. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  86620. };
  86621. /**
  86622. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  86623. */
  86624. GlowLayer.prototype.needStencil = function () {
  86625. return false;
  86626. };
  86627. /**
  86628. * Implementation specific of rendering the generating effect on the main canvas.
  86629. * @param effect The effect used to render through
  86630. */
  86631. GlowLayer.prototype._internalRender = function (effect) {
  86632. // Texture
  86633. effect.setTexture("textureSampler", this._blurTexture1);
  86634. effect.setTexture("textureSampler2", this._blurTexture2);
  86635. effect.setFloat("offset", this._intensity);
  86636. // Cache
  86637. var engine = this._engine;
  86638. var previousStencilBuffer = engine.getStencilBuffer();
  86639. // Draw order
  86640. engine.setStencilBuffer(false);
  86641. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86642. // Draw order
  86643. engine.setStencilBuffer(previousStencilBuffer);
  86644. };
  86645. /**
  86646. * Sets the required values for both the emissive texture and and the main color.
  86647. */
  86648. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  86649. var textureLevel = 1.0;
  86650. if (this.customEmissiveTextureSelector) {
  86651. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  86652. }
  86653. else {
  86654. if (material) {
  86655. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  86656. if (this._emissiveTextureAndColor.texture) {
  86657. textureLevel = this._emissiveTextureAndColor.texture.level;
  86658. }
  86659. }
  86660. else {
  86661. this._emissiveTextureAndColor.texture = null;
  86662. }
  86663. }
  86664. if (this.customEmissiveColorSelector) {
  86665. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  86666. }
  86667. else {
  86668. if (material.emissiveColor) {
  86669. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  86670. }
  86671. else {
  86672. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  86673. }
  86674. }
  86675. };
  86676. /**
  86677. * Returns true if the mesh should render, otherwise false.
  86678. * @param mesh The mesh to render
  86679. * @returns true if it should render otherwise false
  86680. */
  86681. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  86682. return this.hasMesh(mesh);
  86683. };
  86684. /**
  86685. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  86686. * @param mesh The mesh to exclude from the glow layer
  86687. */
  86688. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  86689. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  86690. this._excludedMeshes.push(mesh.uniqueId);
  86691. }
  86692. };
  86693. /**
  86694. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  86695. * @param mesh The mesh to remove
  86696. */
  86697. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  86698. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  86699. if (index !== -1) {
  86700. this._excludedMeshes.splice(index, 1);
  86701. }
  86702. };
  86703. /**
  86704. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  86705. * @param mesh The mesh to include in the glow layer
  86706. */
  86707. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  86708. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  86709. this._includedOnlyMeshes.push(mesh.uniqueId);
  86710. }
  86711. };
  86712. /**
  86713. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  86714. * @param mesh The mesh to remove
  86715. */
  86716. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  86717. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  86718. if (index !== -1) {
  86719. this._includedOnlyMeshes.splice(index, 1);
  86720. }
  86721. };
  86722. /**
  86723. * Determine if a given mesh will be used in the glow layer
  86724. * @param mesh The mesh to test
  86725. * @returns true if the mesh will be highlighted by the current glow layer
  86726. */
  86727. GlowLayer.prototype.hasMesh = function (mesh) {
  86728. // Included Mesh
  86729. if (this._includedOnlyMeshes.length) {
  86730. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  86731. }
  86732. ;
  86733. // Excluded Mesh
  86734. if (this._excludedMeshes.length) {
  86735. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  86736. }
  86737. ;
  86738. return true;
  86739. };
  86740. /**
  86741. * Free any resources and references associated to a mesh.
  86742. * Internal use
  86743. * @param mesh The mesh to free.
  86744. */
  86745. GlowLayer.prototype._disposeMesh = function (mesh) {
  86746. this.removeIncludedOnlyMesh(mesh);
  86747. this.removeExcludedMesh(mesh);
  86748. };
  86749. /**
  86750. * Effect Name of the layer.
  86751. */
  86752. GlowLayer.EffectName = "GlowLayer";
  86753. /**
  86754. * The default blur kernel size used for the glow.
  86755. */
  86756. GlowLayer.DefaultBlurKernelSize = 32;
  86757. /**
  86758. * The default texture size ratio used for the glow.
  86759. */
  86760. GlowLayer.DefaultTextureRatio = 0.5;
  86761. return GlowLayer;
  86762. }(BABYLON.EffectLayer));
  86763. BABYLON.GlowLayer = GlowLayer;
  86764. })(BABYLON || (BABYLON = {}));
  86765. //# sourceMappingURL=babylon.glowLayer.js.map
  86766. var BABYLON;
  86767. (function (BABYLON) {
  86768. /**
  86769. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  86770. */
  86771. var AssetTaskState;
  86772. (function (AssetTaskState) {
  86773. /**
  86774. * Initialization
  86775. */
  86776. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  86777. /**
  86778. * Running
  86779. */
  86780. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  86781. /**
  86782. * Done
  86783. */
  86784. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  86785. /**
  86786. * Error
  86787. */
  86788. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  86789. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  86790. /**
  86791. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  86792. */
  86793. var AbstractAssetTask = /** @class */ (function () {
  86794. /**
  86795. * Creates a new {BABYLON.AssetsManager}
  86796. * @param name defines the name of the task
  86797. */
  86798. function AbstractAssetTask(
  86799. /**
  86800. * Task name
  86801. */ name) {
  86802. this.name = name;
  86803. this._isCompleted = false;
  86804. this._taskState = AssetTaskState.INIT;
  86805. }
  86806. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  86807. /**
  86808. * Get if the task is completed
  86809. */
  86810. get: function () {
  86811. return this._isCompleted;
  86812. },
  86813. enumerable: true,
  86814. configurable: true
  86815. });
  86816. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  86817. /**
  86818. * Gets the current state of the task
  86819. */
  86820. get: function () {
  86821. return this._taskState;
  86822. },
  86823. enumerable: true,
  86824. configurable: true
  86825. });
  86826. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  86827. /**
  86828. * Gets the current error object (if task is in error)
  86829. */
  86830. get: function () {
  86831. return this._errorObject;
  86832. },
  86833. enumerable: true,
  86834. configurable: true
  86835. });
  86836. /**
  86837. * Internal only
  86838. * @ignore
  86839. */
  86840. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  86841. if (this._errorObject) {
  86842. return;
  86843. }
  86844. this._errorObject = {
  86845. message: message,
  86846. exception: exception
  86847. };
  86848. };
  86849. /**
  86850. * Execute the current task
  86851. * @param scene defines the scene where you want your assets to be loaded
  86852. * @param onSuccess is a callback called when the task is successfully executed
  86853. * @param onError is a callback called if an error occurs
  86854. */
  86855. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  86856. var _this = this;
  86857. this._taskState = AssetTaskState.RUNNING;
  86858. this.runTask(scene, function () {
  86859. _this.onDoneCallback(onSuccess, onError);
  86860. }, function (msg, exception) {
  86861. _this.onErrorCallback(onError, msg, exception);
  86862. });
  86863. };
  86864. /**
  86865. * Execute the current task
  86866. * @param scene defines the scene where you want your assets to be loaded
  86867. * @param onSuccess is a callback called when the task is successfully executed
  86868. * @param onError is a callback called if an error occurs
  86869. */
  86870. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86871. throw new Error("runTask is not implemented");
  86872. };
  86873. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  86874. this._taskState = AssetTaskState.ERROR;
  86875. this._errorObject = {
  86876. message: message,
  86877. exception: exception
  86878. };
  86879. if (this.onError) {
  86880. this.onError(this, message, exception);
  86881. }
  86882. onError();
  86883. };
  86884. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  86885. try {
  86886. this._taskState = AssetTaskState.DONE;
  86887. this._isCompleted = true;
  86888. if (this.onSuccess) {
  86889. this.onSuccess(this);
  86890. }
  86891. onSuccess();
  86892. }
  86893. catch (e) {
  86894. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  86895. }
  86896. };
  86897. return AbstractAssetTask;
  86898. }());
  86899. BABYLON.AbstractAssetTask = AbstractAssetTask;
  86900. /**
  86901. * Class used to share progress information about assets loading
  86902. */
  86903. var AssetsProgressEvent = /** @class */ (function () {
  86904. /**
  86905. * Creates a {BABYLON.AssetsProgressEvent}
  86906. * @param remainingCount defines the number of remaining tasks to process
  86907. * @param totalCount defines the total number of tasks
  86908. * @param task defines the task that was just processed
  86909. */
  86910. function AssetsProgressEvent(remainingCount, totalCount, task) {
  86911. this.remainingCount = remainingCount;
  86912. this.totalCount = totalCount;
  86913. this.task = task;
  86914. }
  86915. return AssetsProgressEvent;
  86916. }());
  86917. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  86918. /**
  86919. * Define a task used by {BABYLON.AssetsManager} to load meshes
  86920. */
  86921. var MeshAssetTask = /** @class */ (function (_super) {
  86922. __extends(MeshAssetTask, _super);
  86923. /**
  86924. * Creates a new {BABYLON.MeshAssetTask}
  86925. * @param name defines the name of the task
  86926. * @param meshesNames defines the list of mesh's names you want to load
  86927. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  86928. * @param sceneFilename defines the filename of the scene to load from
  86929. */
  86930. function MeshAssetTask(
  86931. /**
  86932. * Defines the name of the task
  86933. */
  86934. name,
  86935. /**
  86936. * Defines the list of mesh's names you want to load
  86937. */
  86938. meshesNames,
  86939. /**
  86940. * Defines the root url to use as a base to load your meshes and associated resources
  86941. */
  86942. rootUrl,
  86943. /**
  86944. * Defines the filename of the scene to load from
  86945. */
  86946. sceneFilename) {
  86947. var _this = _super.call(this, name) || this;
  86948. _this.name = name;
  86949. _this.meshesNames = meshesNames;
  86950. _this.rootUrl = rootUrl;
  86951. _this.sceneFilename = sceneFilename;
  86952. return _this;
  86953. }
  86954. /**
  86955. * Execute the current task
  86956. * @param scene defines the scene where you want your assets to be loaded
  86957. * @param onSuccess is a callback called when the task is successfully executed
  86958. * @param onError is a callback called if an error occurs
  86959. */
  86960. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86961. var _this = this;
  86962. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  86963. _this.loadedMeshes = meshes;
  86964. _this.loadedParticleSystems = particleSystems;
  86965. _this.loadedSkeletons = skeletons;
  86966. onSuccess();
  86967. }, null, function (scene, message, exception) {
  86968. onError(message, exception);
  86969. });
  86970. };
  86971. return MeshAssetTask;
  86972. }(AbstractAssetTask));
  86973. BABYLON.MeshAssetTask = MeshAssetTask;
  86974. /**
  86975. * Define a task used by {BABYLON.AssetsManager} to load text content
  86976. */
  86977. var TextFileAssetTask = /** @class */ (function (_super) {
  86978. __extends(TextFileAssetTask, _super);
  86979. /**
  86980. * Creates a new TextFileAssetTask object
  86981. * @param name defines the name of the task
  86982. * @param url defines the location of the file to load
  86983. */
  86984. function TextFileAssetTask(
  86985. /**
  86986. * Defines the name of the task
  86987. */
  86988. name,
  86989. /**
  86990. * Defines the location of the file to load
  86991. */
  86992. url) {
  86993. var _this = _super.call(this, name) || this;
  86994. _this.name = name;
  86995. _this.url = url;
  86996. return _this;
  86997. }
  86998. /**
  86999. * Execute the current task
  87000. * @param scene defines the scene where you want your assets to be loaded
  87001. * @param onSuccess is a callback called when the task is successfully executed
  87002. * @param onError is a callback called if an error occurs
  87003. */
  87004. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87005. var _this = this;
  87006. scene._loadFile(this.url, function (data) {
  87007. _this.text = data;
  87008. onSuccess();
  87009. }, undefined, false, false, function (request, exception) {
  87010. if (request) {
  87011. onError(request.status + " " + request.statusText, exception);
  87012. }
  87013. });
  87014. };
  87015. return TextFileAssetTask;
  87016. }(AbstractAssetTask));
  87017. BABYLON.TextFileAssetTask = TextFileAssetTask;
  87018. /**
  87019. * Define a task used by {BABYLON.AssetsManager} to load binary data
  87020. */
  87021. var BinaryFileAssetTask = /** @class */ (function (_super) {
  87022. __extends(BinaryFileAssetTask, _super);
  87023. /**
  87024. * Creates a new BinaryFileAssetTask object
  87025. * @param name defines the name of the new task
  87026. * @param url defines the location of the file to load
  87027. */
  87028. function BinaryFileAssetTask(
  87029. /**
  87030. * Defines the name of the task
  87031. */
  87032. name,
  87033. /**
  87034. * Defines the location of the file to load
  87035. */
  87036. url) {
  87037. var _this = _super.call(this, name) || this;
  87038. _this.name = name;
  87039. _this.url = url;
  87040. return _this;
  87041. }
  87042. /**
  87043. * Execute the current task
  87044. * @param scene defines the scene where you want your assets to be loaded
  87045. * @param onSuccess is a callback called when the task is successfully executed
  87046. * @param onError is a callback called if an error occurs
  87047. */
  87048. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87049. var _this = this;
  87050. scene._loadFile(this.url, function (data) {
  87051. _this.data = data;
  87052. onSuccess();
  87053. }, undefined, true, true, function (request, exception) {
  87054. if (request) {
  87055. onError(request.status + " " + request.statusText, exception);
  87056. }
  87057. });
  87058. };
  87059. return BinaryFileAssetTask;
  87060. }(AbstractAssetTask));
  87061. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  87062. /**
  87063. * Define a task used by {BABYLON.AssetsManager} to load images
  87064. */
  87065. var ImageAssetTask = /** @class */ (function (_super) {
  87066. __extends(ImageAssetTask, _super);
  87067. /**
  87068. * Creates a new ImageAssetTask
  87069. * @param name defines the name of the task
  87070. * @param url defines the location of the image to load
  87071. */
  87072. function ImageAssetTask(
  87073. /**
  87074. * Defines the name of the task
  87075. */
  87076. name,
  87077. /**
  87078. * Defines the location of the image to load
  87079. */
  87080. url) {
  87081. var _this = _super.call(this, name) || this;
  87082. _this.name = name;
  87083. _this.url = url;
  87084. return _this;
  87085. }
  87086. /**
  87087. * Execute the current task
  87088. * @param scene defines the scene where you want your assets to be loaded
  87089. * @param onSuccess is a callback called when the task is successfully executed
  87090. * @param onError is a callback called if an error occurs
  87091. */
  87092. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87093. var _this = this;
  87094. var img = new Image();
  87095. BABYLON.Tools.SetCorsBehavior(this.url, img);
  87096. img.onload = function () {
  87097. _this.image = img;
  87098. onSuccess();
  87099. };
  87100. img.onerror = function (err) {
  87101. onError("Error loading image", err);
  87102. };
  87103. img.src = this.url;
  87104. };
  87105. return ImageAssetTask;
  87106. }(AbstractAssetTask));
  87107. BABYLON.ImageAssetTask = ImageAssetTask;
  87108. /**
  87109. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  87110. */
  87111. var TextureAssetTask = /** @class */ (function (_super) {
  87112. __extends(TextureAssetTask, _super);
  87113. /**
  87114. * Creates a new TextureAssetTask object
  87115. * @param name defines the name of the task
  87116. * @param url defines the location of the file to load
  87117. * @param noMipmap defines if mipmap should not be generated (default is false)
  87118. * @param invertY defines if texture must be inverted on Y axis (default is false)
  87119. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87120. */
  87121. function TextureAssetTask(
  87122. /**
  87123. * Defines the name of the task
  87124. */
  87125. name,
  87126. /**
  87127. * Defines the location of the file to load
  87128. */
  87129. url,
  87130. /**
  87131. * Defines if mipmap should not be generated (default is false)
  87132. */
  87133. noMipmap,
  87134. /**
  87135. * Defines if texture must be inverted on Y axis (default is false)
  87136. */
  87137. invertY,
  87138. /**
  87139. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87140. */
  87141. samplingMode) {
  87142. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87143. var _this = _super.call(this, name) || this;
  87144. _this.name = name;
  87145. _this.url = url;
  87146. _this.noMipmap = noMipmap;
  87147. _this.invertY = invertY;
  87148. _this.samplingMode = samplingMode;
  87149. return _this;
  87150. }
  87151. /**
  87152. * Execute the current task
  87153. * @param scene defines the scene where you want your assets to be loaded
  87154. * @param onSuccess is a callback called when the task is successfully executed
  87155. * @param onError is a callback called if an error occurs
  87156. */
  87157. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87158. var onload = function () {
  87159. onSuccess();
  87160. };
  87161. var onerror = function (message, exception) {
  87162. onError(message, exception);
  87163. };
  87164. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  87165. };
  87166. return TextureAssetTask;
  87167. }(AbstractAssetTask));
  87168. BABYLON.TextureAssetTask = TextureAssetTask;
  87169. /**
  87170. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  87171. */
  87172. var CubeTextureAssetTask = /** @class */ (function (_super) {
  87173. __extends(CubeTextureAssetTask, _super);
  87174. /**
  87175. * Creates a new CubeTextureAssetTask
  87176. * @param name defines the name of the task
  87177. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  87178. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  87179. * @param noMipmap defines if mipmaps should not be generated (default is false)
  87180. * @param files defines the explicit list of files (undefined by default)
  87181. */
  87182. function CubeTextureAssetTask(
  87183. /**
  87184. * Defines the name of the task
  87185. */
  87186. name,
  87187. /**
  87188. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  87189. */
  87190. url,
  87191. /**
  87192. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  87193. */
  87194. extensions,
  87195. /**
  87196. * Defines if mipmaps should not be generated (default is false)
  87197. */
  87198. noMipmap,
  87199. /**
  87200. * Defines the explicit list of files (undefined by default)
  87201. */
  87202. files) {
  87203. var _this = _super.call(this, name) || this;
  87204. _this.name = name;
  87205. _this.url = url;
  87206. _this.extensions = extensions;
  87207. _this.noMipmap = noMipmap;
  87208. _this.files = files;
  87209. return _this;
  87210. }
  87211. /**
  87212. * Execute the current task
  87213. * @param scene defines the scene where you want your assets to be loaded
  87214. * @param onSuccess is a callback called when the task is successfully executed
  87215. * @param onError is a callback called if an error occurs
  87216. */
  87217. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87218. var onload = function () {
  87219. onSuccess();
  87220. };
  87221. var onerror = function (message, exception) {
  87222. onError(message, exception);
  87223. };
  87224. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  87225. };
  87226. return CubeTextureAssetTask;
  87227. }(AbstractAssetTask));
  87228. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  87229. /**
  87230. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  87231. */
  87232. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  87233. __extends(HDRCubeTextureAssetTask, _super);
  87234. /**
  87235. * Creates a new HDRCubeTextureAssetTask object
  87236. * @param name defines the name of the task
  87237. * @param url defines the location of the file to load
  87238. * @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.
  87239. * @param noMipmap defines if mipmaps should not be generated (default is false)
  87240. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  87241. * @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)
  87242. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  87243. */
  87244. function HDRCubeTextureAssetTask(
  87245. /**
  87246. * Defines the name of the task
  87247. */
  87248. name,
  87249. /**
  87250. * Defines the location of the file to load
  87251. */
  87252. url,
  87253. /**
  87254. * 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.
  87255. */
  87256. size,
  87257. /**
  87258. * Defines if mipmaps should not be generated (default is false)
  87259. */
  87260. noMipmap,
  87261. /**
  87262. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  87263. */
  87264. generateHarmonics,
  87265. /**
  87266. * 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)
  87267. */
  87268. useInGammaSpace,
  87269. /**
  87270. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  87271. */
  87272. usePMREMGenerator) {
  87273. if (noMipmap === void 0) { noMipmap = false; }
  87274. if (generateHarmonics === void 0) { generateHarmonics = true; }
  87275. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  87276. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  87277. var _this = _super.call(this, name) || this;
  87278. _this.name = name;
  87279. _this.url = url;
  87280. _this.size = size;
  87281. _this.noMipmap = noMipmap;
  87282. _this.generateHarmonics = generateHarmonics;
  87283. _this.useInGammaSpace = useInGammaSpace;
  87284. _this.usePMREMGenerator = usePMREMGenerator;
  87285. return _this;
  87286. }
  87287. /**
  87288. * Execute the current task
  87289. * @param scene defines the scene where you want your assets to be loaded
  87290. * @param onSuccess is a callback called when the task is successfully executed
  87291. * @param onError is a callback called if an error occurs
  87292. */
  87293. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87294. var onload = function () {
  87295. onSuccess();
  87296. };
  87297. var onerror = function (message, exception) {
  87298. onError(message, exception);
  87299. };
  87300. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  87301. };
  87302. return HDRCubeTextureAssetTask;
  87303. }(AbstractAssetTask));
  87304. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  87305. /**
  87306. * This class can be used to easily import assets into a scene
  87307. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  87308. */
  87309. var AssetsManager = /** @class */ (function () {
  87310. /**
  87311. * Creates a new AssetsManager
  87312. * @param scene defines the scene to work on
  87313. */
  87314. function AssetsManager(scene) {
  87315. this._isLoading = false;
  87316. this._tasks = new Array();
  87317. this._waitingTasksCount = 0;
  87318. this._totalTasksCount = 0;
  87319. /**
  87320. * Observable called when all tasks are processed
  87321. */
  87322. this.onTaskSuccessObservable = new BABYLON.Observable();
  87323. /**
  87324. * Observable called when a task had an error
  87325. */
  87326. this.onTaskErrorObservable = new BABYLON.Observable();
  87327. /**
  87328. * Observable called when a task is successful
  87329. */
  87330. this.onTasksDoneObservable = new BABYLON.Observable();
  87331. /**
  87332. * Observable called when a task is done (whatever the result is)
  87333. */
  87334. this.onProgressObservable = new BABYLON.Observable();
  87335. /**
  87336. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  87337. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  87338. */
  87339. this.useDefaultLoadingScreen = true;
  87340. this._scene = scene;
  87341. }
  87342. /**
  87343. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  87344. * @param taskName defines the name of the new task
  87345. * @param meshesNames defines the name of meshes to load
  87346. * @param rootUrl defines the root url to use to locate files
  87347. * @param sceneFilename defines the filename of the scene file
  87348. * @returns a new {BABYLON.MeshAssetTask} object
  87349. */
  87350. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  87351. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  87352. this._tasks.push(task);
  87353. return task;
  87354. };
  87355. /**
  87356. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  87357. * @param taskName defines the name of the new task
  87358. * @param url defines the url of the file to load
  87359. * @returns a new {BABYLON.TextFileAssetTask} object
  87360. */
  87361. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  87362. var task = new TextFileAssetTask(taskName, url);
  87363. this._tasks.push(task);
  87364. return task;
  87365. };
  87366. /**
  87367. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  87368. * @param taskName defines the name of the new task
  87369. * @param url defines the url of the file to load
  87370. * @returns a new {BABYLON.BinaryFileAssetTask} object
  87371. */
  87372. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  87373. var task = new BinaryFileAssetTask(taskName, url);
  87374. this._tasks.push(task);
  87375. return task;
  87376. };
  87377. /**
  87378. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  87379. * @param taskName defines the name of the new task
  87380. * @param url defines the url of the file to load
  87381. * @returns a new {BABYLON.ImageAssetTask} object
  87382. */
  87383. AssetsManager.prototype.addImageTask = function (taskName, url) {
  87384. var task = new ImageAssetTask(taskName, url);
  87385. this._tasks.push(task);
  87386. return task;
  87387. };
  87388. /**
  87389. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  87390. * @param taskName defines the name of the new task
  87391. * @param url defines the url of the file to load
  87392. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87393. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  87394. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  87395. * @returns a new {BABYLON.TextureAssetTask} object
  87396. */
  87397. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  87398. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87399. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  87400. this._tasks.push(task);
  87401. return task;
  87402. };
  87403. /**
  87404. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  87405. * @param taskName defines the name of the new task
  87406. * @param url defines the url of the file to load
  87407. * @param extensions defines the extension to use to load the cube map (can be null)
  87408. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87409. * @param files defines the list of files to load (can be null)
  87410. * @returns a new {BABYLON.CubeTextureAssetTask} object
  87411. */
  87412. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  87413. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  87414. this._tasks.push(task);
  87415. return task;
  87416. };
  87417. /**
  87418. *
  87419. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  87420. * @param taskName defines the name of the new task
  87421. * @param url defines the url of the file to load
  87422. * @param size defines the size you want for the cubemap (can be null)
  87423. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87424. * @param generateHarmonics defines if you want to automatically generate (true by default)
  87425. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  87426. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  87427. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  87428. */
  87429. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  87430. if (noMipmap === void 0) { noMipmap = false; }
  87431. if (generateHarmonics === void 0) { generateHarmonics = true; }
  87432. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  87433. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  87434. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  87435. this._tasks.push(task);
  87436. return task;
  87437. };
  87438. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  87439. var _this = this;
  87440. this._waitingTasksCount--;
  87441. try {
  87442. if (task.taskState === AssetTaskState.DONE) {
  87443. // Let's remove successfull tasks
  87444. BABYLON.Tools.SetImmediate(function () {
  87445. var index = _this._tasks.indexOf(task);
  87446. if (index > -1) {
  87447. _this._tasks.splice(index, 1);
  87448. }
  87449. });
  87450. }
  87451. if (this.onProgress) {
  87452. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  87453. }
  87454. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  87455. }
  87456. catch (e) {
  87457. BABYLON.Tools.Error("Error running progress callbacks.");
  87458. console.log(e);
  87459. }
  87460. if (this._waitingTasksCount === 0) {
  87461. try {
  87462. if (this.onFinish) {
  87463. this.onFinish(this._tasks);
  87464. }
  87465. this.onTasksDoneObservable.notifyObservers(this._tasks);
  87466. }
  87467. catch (e) {
  87468. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  87469. console.log(e);
  87470. }
  87471. this._isLoading = false;
  87472. this._scene.getEngine().hideLoadingUI();
  87473. }
  87474. };
  87475. AssetsManager.prototype._runTask = function (task) {
  87476. var _this = this;
  87477. var done = function () {
  87478. try {
  87479. if (_this.onTaskSuccess) {
  87480. _this.onTaskSuccess(task);
  87481. }
  87482. _this.onTaskSuccessObservable.notifyObservers(task);
  87483. _this._decreaseWaitingTasksCount(task);
  87484. }
  87485. catch (e) {
  87486. error("Error executing task success callbacks", e);
  87487. }
  87488. };
  87489. var error = function (message, exception) {
  87490. task._setErrorObject(message, exception);
  87491. if (_this.onTaskError) {
  87492. _this.onTaskError(task);
  87493. }
  87494. _this.onTaskErrorObservable.notifyObservers(task);
  87495. _this._decreaseWaitingTasksCount(task);
  87496. };
  87497. task.run(this._scene, done, error);
  87498. };
  87499. /**
  87500. * Reset the {BABYLON.AssetsManager} and remove all tasks
  87501. * @return the current instance of the {BABYLON.AssetsManager}
  87502. */
  87503. AssetsManager.prototype.reset = function () {
  87504. this._isLoading = false;
  87505. this._tasks = new Array();
  87506. return this;
  87507. };
  87508. /**
  87509. * Start the loading process
  87510. * @return the current instance of the {BABYLON.AssetsManager}
  87511. */
  87512. AssetsManager.prototype.load = function () {
  87513. if (this._isLoading) {
  87514. return this;
  87515. }
  87516. this._isLoading = true;
  87517. this._waitingTasksCount = this._tasks.length;
  87518. this._totalTasksCount = this._tasks.length;
  87519. if (this._waitingTasksCount === 0) {
  87520. this._isLoading = false;
  87521. if (this.onFinish) {
  87522. this.onFinish(this._tasks);
  87523. }
  87524. this.onTasksDoneObservable.notifyObservers(this._tasks);
  87525. return this;
  87526. }
  87527. if (this.useDefaultLoadingScreen) {
  87528. this._scene.getEngine().displayLoadingUI();
  87529. }
  87530. for (var index = 0; index < this._tasks.length; index++) {
  87531. var task = this._tasks[index];
  87532. this._runTask(task);
  87533. }
  87534. return this;
  87535. };
  87536. return AssetsManager;
  87537. }());
  87538. BABYLON.AssetsManager = AssetsManager;
  87539. })(BABYLON || (BABYLON = {}));
  87540. //# sourceMappingURL=babylon.assetsManager.js.map
  87541. var BABYLON;
  87542. (function (BABYLON) {
  87543. var serializedGeometries = [];
  87544. var serializeGeometry = function (geometry, serializationGeometries) {
  87545. if (serializedGeometries[geometry.id]) {
  87546. return;
  87547. }
  87548. if (geometry.doNotSerialize) {
  87549. return;
  87550. }
  87551. if (geometry instanceof BABYLON.BoxGeometry) {
  87552. serializationGeometries.boxes.push(geometry.serialize());
  87553. }
  87554. else if (geometry instanceof BABYLON.SphereGeometry) {
  87555. serializationGeometries.spheres.push(geometry.serialize());
  87556. }
  87557. else if (geometry instanceof BABYLON.CylinderGeometry) {
  87558. serializationGeometries.cylinders.push(geometry.serialize());
  87559. }
  87560. else if (geometry instanceof BABYLON.TorusGeometry) {
  87561. serializationGeometries.toruses.push(geometry.serialize());
  87562. }
  87563. else if (geometry instanceof BABYLON.GroundGeometry) {
  87564. serializationGeometries.grounds.push(geometry.serialize());
  87565. }
  87566. else if (geometry instanceof BABYLON.Plane) {
  87567. serializationGeometries.planes.push(geometry.serialize());
  87568. }
  87569. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  87570. serializationGeometries.torusKnots.push(geometry.serialize());
  87571. }
  87572. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  87573. throw new Error("Unknown primitive type");
  87574. }
  87575. else {
  87576. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  87577. }
  87578. serializedGeometries[geometry.id] = true;
  87579. };
  87580. var serializeMesh = function (mesh, serializationScene) {
  87581. var serializationObject = {};
  87582. // Geometry
  87583. var geometry = mesh._geometry;
  87584. if (geometry) {
  87585. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  87586. // 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
  87587. serializeGeometry(geometry, serializationScene.geometries);
  87588. }
  87589. }
  87590. // Custom
  87591. if (mesh.serialize) {
  87592. mesh.serialize(serializationObject);
  87593. }
  87594. return serializationObject;
  87595. };
  87596. var finalizeSingleMesh = function (mesh, serializationObject) {
  87597. //only works if the mesh is already loaded
  87598. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  87599. //serialize material
  87600. if (mesh.material) {
  87601. if (mesh.material instanceof BABYLON.StandardMaterial) {
  87602. serializationObject.materials = serializationObject.materials || [];
  87603. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  87604. serializationObject.materials.push(mesh.material.serialize());
  87605. }
  87606. }
  87607. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  87608. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  87609. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  87610. serializationObject.multiMaterials.push(mesh.material.serialize());
  87611. }
  87612. }
  87613. }
  87614. //serialize geometry
  87615. var geometry = mesh._geometry;
  87616. if (geometry) {
  87617. if (!serializationObject.geometries) {
  87618. serializationObject.geometries = {};
  87619. serializationObject.geometries.boxes = [];
  87620. serializationObject.geometries.spheres = [];
  87621. serializationObject.geometries.cylinders = [];
  87622. serializationObject.geometries.toruses = [];
  87623. serializationObject.geometries.grounds = [];
  87624. serializationObject.geometries.planes = [];
  87625. serializationObject.geometries.torusKnots = [];
  87626. serializationObject.geometries.vertexData = [];
  87627. }
  87628. serializeGeometry(geometry, serializationObject.geometries);
  87629. }
  87630. // Skeletons
  87631. if (mesh.skeleton) {
  87632. serializationObject.skeletons = serializationObject.skeletons || [];
  87633. serializationObject.skeletons.push(mesh.skeleton.serialize());
  87634. }
  87635. //serialize the actual mesh
  87636. serializationObject.meshes = serializationObject.meshes || [];
  87637. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  87638. }
  87639. };
  87640. var SceneSerializer = /** @class */ (function () {
  87641. function SceneSerializer() {
  87642. }
  87643. SceneSerializer.ClearCache = function () {
  87644. serializedGeometries = [];
  87645. };
  87646. SceneSerializer.Serialize = function (scene) {
  87647. var serializationObject = {};
  87648. SceneSerializer.ClearCache();
  87649. // Scene
  87650. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  87651. serializationObject.autoClear = scene.autoClear;
  87652. serializationObject.clearColor = scene.clearColor.asArray();
  87653. serializationObject.ambientColor = scene.ambientColor.asArray();
  87654. serializationObject.gravity = scene.gravity.asArray();
  87655. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  87656. serializationObject.workerCollisions = scene.workerCollisions;
  87657. // Fog
  87658. if (scene.fogMode && scene.fogMode !== 0) {
  87659. serializationObject.fogMode = scene.fogMode;
  87660. serializationObject.fogColor = scene.fogColor.asArray();
  87661. serializationObject.fogStart = scene.fogStart;
  87662. serializationObject.fogEnd = scene.fogEnd;
  87663. serializationObject.fogDensity = scene.fogDensity;
  87664. }
  87665. //Physics
  87666. if (scene.isPhysicsEnabled()) {
  87667. var physicEngine = scene.getPhysicsEngine();
  87668. if (physicEngine) {
  87669. serializationObject.physicsEnabled = true;
  87670. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  87671. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  87672. }
  87673. }
  87674. // Metadata
  87675. if (scene.metadata) {
  87676. serializationObject.metadata = scene.metadata;
  87677. }
  87678. // Morph targets
  87679. serializationObject.morphTargetManagers = [];
  87680. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  87681. var abstractMesh = _a[_i];
  87682. var manager = abstractMesh.morphTargetManager;
  87683. if (manager) {
  87684. serializationObject.morphTargetManagers.push(manager.serialize());
  87685. }
  87686. }
  87687. // Lights
  87688. serializationObject.lights = [];
  87689. var index;
  87690. var light;
  87691. for (index = 0; index < scene.lights.length; index++) {
  87692. light = scene.lights[index];
  87693. if (!light.doNotSerialize) {
  87694. serializationObject.lights.push(light.serialize());
  87695. }
  87696. }
  87697. // Cameras
  87698. serializationObject.cameras = [];
  87699. for (index = 0; index < scene.cameras.length; index++) {
  87700. var camera = scene.cameras[index];
  87701. if (!camera.doNotSerialize) {
  87702. serializationObject.cameras.push(camera.serialize());
  87703. }
  87704. }
  87705. if (scene.activeCamera) {
  87706. serializationObject.activeCameraID = scene.activeCamera.id;
  87707. }
  87708. // Animations
  87709. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  87710. // Materials
  87711. serializationObject.materials = [];
  87712. serializationObject.multiMaterials = [];
  87713. var material;
  87714. for (index = 0; index < scene.materials.length; index++) {
  87715. material = scene.materials[index];
  87716. if (!material.doNotSerialize) {
  87717. serializationObject.materials.push(material.serialize());
  87718. }
  87719. }
  87720. // MultiMaterials
  87721. serializationObject.multiMaterials = [];
  87722. for (index = 0; index < scene.multiMaterials.length; index++) {
  87723. var multiMaterial = scene.multiMaterials[index];
  87724. serializationObject.multiMaterials.push(multiMaterial.serialize());
  87725. }
  87726. // Environment texture
  87727. if (scene.environmentTexture) {
  87728. serializationObject.environmentTexture = scene.environmentTexture.name;
  87729. }
  87730. // Skeletons
  87731. serializationObject.skeletons = [];
  87732. for (index = 0; index < scene.skeletons.length; index++) {
  87733. var skeleton = scene.skeletons[index];
  87734. if (!skeleton.doNotSerialize) {
  87735. serializationObject.skeletons.push(skeleton.serialize());
  87736. }
  87737. }
  87738. // Transform nodes
  87739. serializationObject.transformNodes = [];
  87740. for (index = 0; index < scene.transformNodes.length; index++) {
  87741. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  87742. }
  87743. // Geometries
  87744. serializationObject.geometries = {};
  87745. serializationObject.geometries.boxes = [];
  87746. serializationObject.geometries.spheres = [];
  87747. serializationObject.geometries.cylinders = [];
  87748. serializationObject.geometries.toruses = [];
  87749. serializationObject.geometries.grounds = [];
  87750. serializationObject.geometries.planes = [];
  87751. serializationObject.geometries.torusKnots = [];
  87752. serializationObject.geometries.vertexData = [];
  87753. serializedGeometries = [];
  87754. var geometries = scene.getGeometries();
  87755. for (index = 0; index < geometries.length; index++) {
  87756. var geometry = geometries[index];
  87757. if (geometry.isReady()) {
  87758. serializeGeometry(geometry, serializationObject.geometries);
  87759. }
  87760. }
  87761. // Meshes
  87762. serializationObject.meshes = [];
  87763. for (index = 0; index < scene.meshes.length; index++) {
  87764. var abstractMesh = scene.meshes[index];
  87765. if (abstractMesh instanceof BABYLON.Mesh) {
  87766. var mesh = abstractMesh;
  87767. if (!mesh.doNotSerialize) {
  87768. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  87769. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  87770. }
  87771. }
  87772. }
  87773. }
  87774. // Particles Systems
  87775. serializationObject.particleSystems = [];
  87776. for (index = 0; index < scene.particleSystems.length; index++) {
  87777. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  87778. }
  87779. // Lens flares
  87780. serializationObject.lensFlareSystems = [];
  87781. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  87782. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  87783. }
  87784. // Shadows
  87785. serializationObject.shadowGenerators = [];
  87786. for (index = 0; index < scene.lights.length; index++) {
  87787. light = scene.lights[index];
  87788. var shadowGenerator = light.getShadowGenerator();
  87789. if (shadowGenerator) {
  87790. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  87791. }
  87792. }
  87793. // Action Manager
  87794. if (scene.actionManager) {
  87795. serializationObject.actions = scene.actionManager.serialize("scene");
  87796. }
  87797. // Audio
  87798. serializationObject.sounds = [];
  87799. for (index = 0; index < scene.soundTracks.length; index++) {
  87800. var soundtrack = scene.soundTracks[index];
  87801. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  87802. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  87803. }
  87804. }
  87805. return serializationObject;
  87806. };
  87807. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  87808. if (withParents === void 0) { withParents = false; }
  87809. if (withChildren === void 0) { withChildren = false; }
  87810. var serializationObject = {};
  87811. SceneSerializer.ClearCache();
  87812. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  87813. if (withParents || withChildren) {
  87814. //deliberate for loop! not for each, appended should be processed as well.
  87815. for (var i = 0; i < toSerialize.length; ++i) {
  87816. if (withChildren) {
  87817. toSerialize[i].getDescendants().forEach(function (node) {
  87818. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  87819. toSerialize.push(node);
  87820. }
  87821. });
  87822. }
  87823. //make sure the array doesn't contain the object already
  87824. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  87825. toSerialize.push(toSerialize[i].parent);
  87826. }
  87827. }
  87828. }
  87829. toSerialize.forEach(function (mesh) {
  87830. finalizeSingleMesh(mesh, serializationObject);
  87831. });
  87832. return serializationObject;
  87833. };
  87834. return SceneSerializer;
  87835. }());
  87836. BABYLON.SceneSerializer = SceneSerializer;
  87837. })(BABYLON || (BABYLON = {}));
  87838. //# sourceMappingURL=babylon.sceneSerializer.js.map
  87839. var BABYLON;
  87840. (function (BABYLON) {
  87841. var ReflectionProbe = /** @class */ (function () {
  87842. function ReflectionProbe(name, size, scene, generateMipMaps) {
  87843. if (generateMipMaps === void 0) { generateMipMaps = true; }
  87844. var _this = this;
  87845. this.name = name;
  87846. this._viewMatrix = BABYLON.Matrix.Identity();
  87847. this._target = BABYLON.Vector3.Zero();
  87848. this._add = BABYLON.Vector3.Zero();
  87849. this._invertYAxis = false;
  87850. this.position = BABYLON.Vector3.Zero();
  87851. this._scene = scene;
  87852. this._scene.reflectionProbes.push(this);
  87853. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  87854. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  87855. switch (faceIndex) {
  87856. case 0:
  87857. _this._add.copyFromFloats(1, 0, 0);
  87858. break;
  87859. case 1:
  87860. _this._add.copyFromFloats(-1, 0, 0);
  87861. break;
  87862. case 2:
  87863. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  87864. break;
  87865. case 3:
  87866. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  87867. break;
  87868. case 4:
  87869. _this._add.copyFromFloats(0, 0, 1);
  87870. break;
  87871. case 5:
  87872. _this._add.copyFromFloats(0, 0, -1);
  87873. break;
  87874. }
  87875. if (_this._attachedMesh) {
  87876. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  87877. }
  87878. _this.position.addToRef(_this._add, _this._target);
  87879. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  87880. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  87881. scene._forcedViewPosition = _this.position;
  87882. });
  87883. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  87884. scene._forcedViewPosition = null;
  87885. scene.updateTransformMatrix(true);
  87886. });
  87887. if (scene.activeCamera) {
  87888. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  87889. }
  87890. }
  87891. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  87892. get: function () {
  87893. return this._renderTargetTexture.samples;
  87894. },
  87895. set: function (value) {
  87896. this._renderTargetTexture.samples = value;
  87897. },
  87898. enumerable: true,
  87899. configurable: true
  87900. });
  87901. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  87902. get: function () {
  87903. return this._renderTargetTexture.refreshRate;
  87904. },
  87905. set: function (value) {
  87906. this._renderTargetTexture.refreshRate = value;
  87907. },
  87908. enumerable: true,
  87909. configurable: true
  87910. });
  87911. ReflectionProbe.prototype.getScene = function () {
  87912. return this._scene;
  87913. };
  87914. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  87915. get: function () {
  87916. return this._renderTargetTexture;
  87917. },
  87918. enumerable: true,
  87919. configurable: true
  87920. });
  87921. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  87922. get: function () {
  87923. return this._renderTargetTexture.renderList;
  87924. },
  87925. enumerable: true,
  87926. configurable: true
  87927. });
  87928. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  87929. this._attachedMesh = mesh;
  87930. };
  87931. /**
  87932. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  87933. *
  87934. * @param renderingGroupId The rendering group id corresponding to its index
  87935. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  87936. */
  87937. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  87938. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  87939. };
  87940. ReflectionProbe.prototype.dispose = function () {
  87941. var index = this._scene.reflectionProbes.indexOf(this);
  87942. if (index !== -1) {
  87943. // Remove from the scene if found
  87944. this._scene.reflectionProbes.splice(index, 1);
  87945. }
  87946. if (this._renderTargetTexture) {
  87947. this._renderTargetTexture.dispose();
  87948. this._renderTargetTexture = null;
  87949. }
  87950. };
  87951. return ReflectionProbe;
  87952. }());
  87953. BABYLON.ReflectionProbe = ReflectionProbe;
  87954. })(BABYLON || (BABYLON = {}));
  87955. //# sourceMappingURL=babylon.reflectionProbe.js.map
  87956. var BABYLON;
  87957. (function (BABYLON) {
  87958. var Layer = /** @class */ (function () {
  87959. function Layer(name, imgUrl, scene, isBackground, color) {
  87960. this.name = name;
  87961. this.scale = new BABYLON.Vector2(1, 1);
  87962. this.offset = new BABYLON.Vector2(0, 0);
  87963. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  87964. this.layerMask = 0x0FFFFFFF;
  87965. this._vertexBuffers = {};
  87966. // Events
  87967. /**
  87968. * An event triggered when the layer is disposed.
  87969. * @type {BABYLON.Observable}
  87970. */
  87971. this.onDisposeObservable = new BABYLON.Observable();
  87972. /**
  87973. * An event triggered before rendering the scene
  87974. * @type {BABYLON.Observable}
  87975. */
  87976. this.onBeforeRenderObservable = new BABYLON.Observable();
  87977. /**
  87978. * An event triggered after rendering the scene
  87979. * @type {BABYLON.Observable}
  87980. */
  87981. this.onAfterRenderObservable = new BABYLON.Observable();
  87982. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  87983. this.isBackground = isBackground === undefined ? true : isBackground;
  87984. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  87985. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  87986. this._scene.layers.push(this);
  87987. var engine = this._scene.getEngine();
  87988. // VBO
  87989. var vertices = [];
  87990. vertices.push(1, 1);
  87991. vertices.push(-1, 1);
  87992. vertices.push(-1, -1);
  87993. vertices.push(1, -1);
  87994. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  87995. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  87996. this._createIndexBuffer();
  87997. // Effects
  87998. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  87999. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  88000. }
  88001. Object.defineProperty(Layer.prototype, "onDispose", {
  88002. set: function (callback) {
  88003. if (this._onDisposeObserver) {
  88004. this.onDisposeObservable.remove(this._onDisposeObserver);
  88005. }
  88006. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  88007. },
  88008. enumerable: true,
  88009. configurable: true
  88010. });
  88011. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  88012. set: function (callback) {
  88013. if (this._onBeforeRenderObserver) {
  88014. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  88015. }
  88016. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  88017. },
  88018. enumerable: true,
  88019. configurable: true
  88020. });
  88021. Object.defineProperty(Layer.prototype, "onAfterRender", {
  88022. set: function (callback) {
  88023. if (this._onAfterRenderObserver) {
  88024. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  88025. }
  88026. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  88027. },
  88028. enumerable: true,
  88029. configurable: true
  88030. });
  88031. Layer.prototype._createIndexBuffer = function () {
  88032. var engine = this._scene.getEngine();
  88033. // Indices
  88034. var indices = [];
  88035. indices.push(0);
  88036. indices.push(1);
  88037. indices.push(2);
  88038. indices.push(0);
  88039. indices.push(2);
  88040. indices.push(3);
  88041. this._indexBuffer = engine.createIndexBuffer(indices);
  88042. };
  88043. Layer.prototype._rebuild = function () {
  88044. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88045. if (vb) {
  88046. vb._rebuild();
  88047. }
  88048. this._createIndexBuffer();
  88049. };
  88050. Layer.prototype.render = function () {
  88051. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  88052. // Check
  88053. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  88054. return;
  88055. var engine = this._scene.getEngine();
  88056. this.onBeforeRenderObservable.notifyObservers(this);
  88057. // Render
  88058. engine.enableEffect(currentEffect);
  88059. engine.setState(false);
  88060. // Texture
  88061. currentEffect.setTexture("textureSampler", this.texture);
  88062. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  88063. // Color
  88064. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  88065. // Scale / offset
  88066. currentEffect.setVector2("offset", this.offset);
  88067. currentEffect.setVector2("scale", this.scale);
  88068. // VBOs
  88069. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  88070. // Draw order
  88071. if (!this.alphaTest) {
  88072. engine.setAlphaMode(this.alphaBlendingMode);
  88073. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88074. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  88075. }
  88076. else {
  88077. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88078. }
  88079. this.onAfterRenderObservable.notifyObservers(this);
  88080. };
  88081. Layer.prototype.dispose = function () {
  88082. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88083. if (vertexBuffer) {
  88084. vertexBuffer.dispose();
  88085. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88086. }
  88087. if (this._indexBuffer) {
  88088. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  88089. this._indexBuffer = null;
  88090. }
  88091. if (this.texture) {
  88092. this.texture.dispose();
  88093. this.texture = null;
  88094. }
  88095. // Remove from scene
  88096. var index = this._scene.layers.indexOf(this);
  88097. this._scene.layers.splice(index, 1);
  88098. // Callback
  88099. this.onDisposeObservable.notifyObservers(this);
  88100. this.onDisposeObservable.clear();
  88101. this.onAfterRenderObservable.clear();
  88102. this.onBeforeRenderObservable.clear();
  88103. };
  88104. return Layer;
  88105. }());
  88106. BABYLON.Layer = Layer;
  88107. })(BABYLON || (BABYLON = {}));
  88108. //# sourceMappingURL=babylon.layer.js.map
  88109. var BABYLON;
  88110. (function (BABYLON) {
  88111. var TextureTools = /** @class */ (function () {
  88112. function TextureTools() {
  88113. }
  88114. /**
  88115. * Uses the GPU to create a copy texture rescaled at a given size
  88116. * @param texture Texture to copy from
  88117. * @param width Desired width
  88118. * @param height Desired height
  88119. * @return Generated texture
  88120. */
  88121. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  88122. if (useBilinearMode === void 0) { useBilinearMode = true; }
  88123. var scene = texture.getScene();
  88124. var engine = scene.getEngine();
  88125. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  88126. rtt.wrapU = texture.wrapU;
  88127. rtt.wrapV = texture.wrapV;
  88128. rtt.uOffset = texture.uOffset;
  88129. rtt.vOffset = texture.vOffset;
  88130. rtt.uScale = texture.uScale;
  88131. rtt.vScale = texture.vScale;
  88132. rtt.uAng = texture.uAng;
  88133. rtt.vAng = texture.vAng;
  88134. rtt.wAng = texture.wAng;
  88135. rtt.coordinatesIndex = texture.coordinatesIndex;
  88136. rtt.level = texture.level;
  88137. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  88138. rtt._texture.isReady = false;
  88139. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88140. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88141. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  88142. passPostProcess.getEffect().executeWhenCompiled(function () {
  88143. passPostProcess.onApply = function (effect) {
  88144. effect.setTexture("textureSampler", texture);
  88145. };
  88146. var internalTexture = rtt.getInternalTexture();
  88147. if (internalTexture) {
  88148. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  88149. engine.unBindFramebuffer(internalTexture);
  88150. rtt.disposeFramebufferObjects();
  88151. passPostProcess.dispose();
  88152. internalTexture.isReady = true;
  88153. }
  88154. });
  88155. return rtt;
  88156. };
  88157. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  88158. if (!scene._environmentBRDFTexture) {
  88159. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  88160. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88161. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88162. scene._environmentBRDFTexture = texture;
  88163. }
  88164. return scene._environmentBRDFTexture;
  88165. };
  88166. 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=";
  88167. return TextureTools;
  88168. }());
  88169. BABYLON.TextureTools = TextureTools;
  88170. })(BABYLON || (BABYLON = {}));
  88171. //# sourceMappingURL=babylon.textureTools.js.map
  88172. var BABYLON;
  88173. (function (BABYLON) {
  88174. var FramingBehavior = /** @class */ (function () {
  88175. function FramingBehavior() {
  88176. this._mode = FramingBehavior.FitFrustumSidesMode;
  88177. this._radiusScale = 1.0;
  88178. this._positionScale = 0.5;
  88179. this._defaultElevation = 0.3;
  88180. this._elevationReturnTime = 1500;
  88181. this._elevationReturnWaitTime = 1000;
  88182. this._zoomStopsAnimation = false;
  88183. this._framingTime = 1500;
  88184. this._isPointerDown = false;
  88185. this._lastInteractionTime = -Infinity;
  88186. // Framing control
  88187. this._animatables = new Array();
  88188. this._betaIsAnimating = false;
  88189. }
  88190. Object.defineProperty(FramingBehavior.prototype, "name", {
  88191. get: function () {
  88192. return "Framing";
  88193. },
  88194. enumerable: true,
  88195. configurable: true
  88196. });
  88197. Object.defineProperty(FramingBehavior.prototype, "mode", {
  88198. /**
  88199. * Gets current mode used by the behavior.
  88200. */
  88201. get: function () {
  88202. return this._mode;
  88203. },
  88204. /**
  88205. * Sets the current mode used by the behavior
  88206. */
  88207. set: function (mode) {
  88208. this._mode = mode;
  88209. },
  88210. enumerable: true,
  88211. configurable: true
  88212. });
  88213. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  88214. /**
  88215. * Gets the scale applied to the radius
  88216. */
  88217. get: function () {
  88218. return this._radiusScale;
  88219. },
  88220. /**
  88221. * Sets the scale applied to the radius (1 by default)
  88222. */
  88223. set: function (radius) {
  88224. this._radiusScale = radius;
  88225. },
  88226. enumerable: true,
  88227. configurable: true
  88228. });
  88229. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  88230. /**
  88231. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  88232. */
  88233. get: function () {
  88234. return this._positionScale;
  88235. },
  88236. /**
  88237. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  88238. */
  88239. set: function (scale) {
  88240. this._positionScale = scale;
  88241. },
  88242. enumerable: true,
  88243. configurable: true
  88244. });
  88245. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  88246. /**
  88247. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  88248. * behaviour is triggered, in radians.
  88249. */
  88250. get: function () {
  88251. return this._defaultElevation;
  88252. },
  88253. /**
  88254. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  88255. * behaviour is triggered, in radians.
  88256. */
  88257. set: function (elevation) {
  88258. this._defaultElevation = elevation;
  88259. },
  88260. enumerable: true,
  88261. configurable: true
  88262. });
  88263. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  88264. /**
  88265. * Gets the time (in milliseconds) taken to return to the default beta position.
  88266. * Negative value indicates camera should not return to default.
  88267. */
  88268. get: function () {
  88269. return this._elevationReturnTime;
  88270. },
  88271. /**
  88272. * Sets the time (in milliseconds) taken to return to the default beta position.
  88273. * Negative value indicates camera should not return to default.
  88274. */
  88275. set: function (speed) {
  88276. this._elevationReturnTime = speed;
  88277. },
  88278. enumerable: true,
  88279. configurable: true
  88280. });
  88281. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  88282. /**
  88283. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88284. */
  88285. get: function () {
  88286. return this._elevationReturnWaitTime;
  88287. },
  88288. /**
  88289. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88290. */
  88291. set: function (time) {
  88292. this._elevationReturnWaitTime = time;
  88293. },
  88294. enumerable: true,
  88295. configurable: true
  88296. });
  88297. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  88298. /**
  88299. * Gets the flag that indicates if user zooming should stop animation.
  88300. */
  88301. get: function () {
  88302. return this._zoomStopsAnimation;
  88303. },
  88304. /**
  88305. * Sets the flag that indicates if user zooming should stop animation.
  88306. */
  88307. set: function (flag) {
  88308. this._zoomStopsAnimation = flag;
  88309. },
  88310. enumerable: true,
  88311. configurable: true
  88312. });
  88313. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  88314. /**
  88315. * Gets the transition time when framing the mesh, in milliseconds
  88316. */
  88317. get: function () {
  88318. return this._framingTime;
  88319. },
  88320. /**
  88321. * Sets the transition time when framing the mesh, in milliseconds
  88322. */
  88323. set: function (time) {
  88324. this._framingTime = time;
  88325. },
  88326. enumerable: true,
  88327. configurable: true
  88328. });
  88329. FramingBehavior.prototype.init = function () {
  88330. // Do notihng
  88331. };
  88332. FramingBehavior.prototype.attach = function (camera) {
  88333. var _this = this;
  88334. this._attachedCamera = camera;
  88335. var scene = this._attachedCamera.getScene();
  88336. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  88337. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  88338. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88339. _this._isPointerDown = true;
  88340. return;
  88341. }
  88342. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  88343. _this._isPointerDown = false;
  88344. }
  88345. });
  88346. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  88347. if (mesh) {
  88348. _this.zoomOnMesh(mesh);
  88349. }
  88350. });
  88351. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88352. // Stop the animation if there is user interaction and the animation should stop for this interaction
  88353. _this._applyUserInteraction();
  88354. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  88355. // back to the default position after a given timeout
  88356. _this._maintainCameraAboveGround();
  88357. });
  88358. };
  88359. FramingBehavior.prototype.detach = function () {
  88360. if (!this._attachedCamera) {
  88361. return;
  88362. }
  88363. var scene = this._attachedCamera.getScene();
  88364. if (this._onPrePointerObservableObserver) {
  88365. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  88366. }
  88367. if (this._onAfterCheckInputsObserver) {
  88368. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88369. }
  88370. if (this._onMeshTargetChangedObserver) {
  88371. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88372. }
  88373. this._attachedCamera = null;
  88374. };
  88375. /**
  88376. * Targets the given mesh and updates zoom level accordingly.
  88377. * @param mesh The mesh to target.
  88378. * @param radius Optional. If a cached radius position already exists, overrides default.
  88379. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88380. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88381. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88382. */
  88383. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  88384. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88385. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88386. mesh.computeWorldMatrix(true);
  88387. var boundingBox = mesh.getBoundingInfo().boundingBox;
  88388. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  88389. };
  88390. /**
  88391. * Targets the given mesh with its children and updates zoom level accordingly.
  88392. * @param mesh The mesh to target.
  88393. * @param radius Optional. If a cached radius position already exists, overrides default.
  88394. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88395. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88396. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88397. */
  88398. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  88399. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88400. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88401. mesh.computeWorldMatrix(true);
  88402. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  88403. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  88404. };
  88405. /**
  88406. * Targets the given meshes with their children and updates zoom level accordingly.
  88407. * @param meshes The mesh to target.
  88408. * @param radius Optional. If a cached radius position already exists, overrides default.
  88409. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88410. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88411. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88412. */
  88413. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  88414. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88415. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88416. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  88417. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  88418. for (var i = 0; i < meshes.length; i++) {
  88419. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  88420. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  88421. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  88422. }
  88423. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  88424. };
  88425. /**
  88426. * Targets the given mesh and updates zoom level accordingly.
  88427. * @param mesh The mesh to target.
  88428. * @param radius Optional. If a cached radius position already exists, overrides default.
  88429. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88430. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88431. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88432. */
  88433. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  88434. var _this = this;
  88435. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88436. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88437. var zoomTarget;
  88438. if (!this._attachedCamera) {
  88439. return;
  88440. }
  88441. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  88442. var bottom = minimumWorld.y;
  88443. var top = maximumWorld.y;
  88444. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  88445. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  88446. if (focusOnOriginXZ) {
  88447. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  88448. }
  88449. else {
  88450. var centerWorld = minimumWorld.add(radiusWorld);
  88451. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  88452. }
  88453. if (!this._vectorTransition) {
  88454. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  88455. }
  88456. this._betaIsAnimating = true;
  88457. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  88458. if (animatable) {
  88459. this._animatables.push(animatable);
  88460. }
  88461. // sets the radius and lower radius bounds
  88462. // Small delta ensures camera is not always at lower zoom limit.
  88463. var radius = 0;
  88464. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  88465. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  88466. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  88467. radius = position;
  88468. }
  88469. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  88470. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  88471. if (this._attachedCamera.lowerRadiusLimit === null) {
  88472. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  88473. }
  88474. }
  88475. // Set sensibilities
  88476. var extend = maximumWorld.subtract(minimumWorld).length();
  88477. this._attachedCamera.panningSensibility = 5000 / extend;
  88478. this._attachedCamera.wheelPrecision = 100 / radius;
  88479. // transition to new radius
  88480. if (!this._radiusTransition) {
  88481. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  88482. }
  88483. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  88484. _this.stopAllAnimations();
  88485. if (onAnimationEnd) {
  88486. onAnimationEnd();
  88487. }
  88488. if (_this._attachedCamera) {
  88489. _this._attachedCamera.storeState();
  88490. }
  88491. });
  88492. if (animatable) {
  88493. this._animatables.push(animatable);
  88494. }
  88495. };
  88496. /**
  88497. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  88498. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  88499. * frustum width.
  88500. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  88501. * to fully enclose the mesh in the viewing frustum.
  88502. */
  88503. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  88504. var size = maximumWorld.subtract(minimumWorld);
  88505. var boxVectorGlobalDiagonal = size.length();
  88506. var frustumSlope = this._getFrustumSlope();
  88507. // Formula for setting distance
  88508. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  88509. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  88510. // Horizon distance
  88511. var radius = radiusWithoutFraming * this._radiusScale;
  88512. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  88513. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  88514. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  88515. var camera = this._attachedCamera;
  88516. if (!camera) {
  88517. return 0;
  88518. }
  88519. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  88520. // Don't exceed the requested limit
  88521. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  88522. }
  88523. // Don't exceed the upper radius limit
  88524. if (camera.upperRadiusLimit) {
  88525. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  88526. }
  88527. return distance;
  88528. };
  88529. /**
  88530. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  88531. * is automatically returned to its default position (expected to be above ground plane).
  88532. */
  88533. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  88534. var _this = this;
  88535. if (this._elevationReturnTime < 0) {
  88536. return;
  88537. }
  88538. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  88539. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  88540. var limitBeta = Math.PI * 0.5;
  88541. // Bring the camera back up if below the ground plane
  88542. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  88543. this._betaIsAnimating = true;
  88544. //Transition to new position
  88545. this.stopAllAnimations();
  88546. if (!this._betaTransition) {
  88547. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  88548. }
  88549. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  88550. _this._clearAnimationLocks();
  88551. _this.stopAllAnimations();
  88552. });
  88553. if (animatabe) {
  88554. this._animatables.push(animatabe);
  88555. }
  88556. }
  88557. };
  88558. /**
  88559. * Returns the frustum slope based on the canvas ratio and camera FOV
  88560. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  88561. */
  88562. FramingBehavior.prototype._getFrustumSlope = function () {
  88563. // Calculate the viewport ratio
  88564. // Aspect Ratio is Height/Width.
  88565. var camera = this._attachedCamera;
  88566. if (!camera) {
  88567. return BABYLON.Vector2.Zero();
  88568. }
  88569. var engine = camera.getScene().getEngine();
  88570. var aspectRatio = engine.getAspectRatio(camera);
  88571. // Camera FOV is the vertical field of view (top-bottom) in radians.
  88572. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  88573. var frustumSlopeY = Math.tan(camera.fov / 2);
  88574. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  88575. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  88576. // along the forward vector.
  88577. var frustumSlopeX = frustumSlopeY * aspectRatio;
  88578. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  88579. };
  88580. /**
  88581. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  88582. */
  88583. FramingBehavior.prototype._clearAnimationLocks = function () {
  88584. this._betaIsAnimating = false;
  88585. };
  88586. /**
  88587. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  88588. */
  88589. FramingBehavior.prototype._applyUserInteraction = function () {
  88590. if (this.isUserIsMoving) {
  88591. this._lastInteractionTime = BABYLON.Tools.Now;
  88592. this.stopAllAnimations();
  88593. this._clearAnimationLocks();
  88594. }
  88595. };
  88596. /**
  88597. * Stops and removes all animations that have been applied to the camera
  88598. */
  88599. FramingBehavior.prototype.stopAllAnimations = function () {
  88600. if (this._attachedCamera) {
  88601. this._attachedCamera.animations = [];
  88602. }
  88603. while (this._animatables.length) {
  88604. if (this._animatables[0]) {
  88605. this._animatables[0].onAnimationEnd = null;
  88606. this._animatables[0].stop();
  88607. }
  88608. this._animatables.shift();
  88609. }
  88610. };
  88611. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  88612. /**
  88613. * Gets a value indicating if the user is moving the camera
  88614. */
  88615. get: function () {
  88616. if (!this._attachedCamera) {
  88617. return false;
  88618. }
  88619. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  88620. this._attachedCamera.inertialBetaOffset !== 0 ||
  88621. this._attachedCamera.inertialRadiusOffset !== 0 ||
  88622. this._attachedCamera.inertialPanningX !== 0 ||
  88623. this._attachedCamera.inertialPanningY !== 0 ||
  88624. this._isPointerDown;
  88625. },
  88626. enumerable: true,
  88627. configurable: true
  88628. });
  88629. /**
  88630. * The easing function used by animations
  88631. */
  88632. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  88633. /**
  88634. * The easing mode used by animations
  88635. */
  88636. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  88637. // Statics
  88638. /**
  88639. * The camera can move all the way towards the mesh.
  88640. */
  88641. FramingBehavior.IgnoreBoundsSizeMode = 0;
  88642. /**
  88643. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  88644. */
  88645. FramingBehavior.FitFrustumSidesMode = 1;
  88646. return FramingBehavior;
  88647. }());
  88648. BABYLON.FramingBehavior = FramingBehavior;
  88649. })(BABYLON || (BABYLON = {}));
  88650. //# sourceMappingURL=babylon.framingBehavior.js.map
  88651. var BABYLON;
  88652. (function (BABYLON) {
  88653. /**
  88654. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  88655. */
  88656. var BouncingBehavior = /** @class */ (function () {
  88657. function BouncingBehavior() {
  88658. /**
  88659. * The duration of the animation, in milliseconds
  88660. */
  88661. this.transitionDuration = 450;
  88662. /**
  88663. * Length of the distance animated by the transition when lower radius is reached
  88664. */
  88665. this.lowerRadiusTransitionRange = 2;
  88666. /**
  88667. * Length of the distance animated by the transition when upper radius is reached
  88668. */
  88669. this.upperRadiusTransitionRange = -2;
  88670. this._autoTransitionRange = false;
  88671. // Animations
  88672. this._radiusIsAnimating = false;
  88673. this._radiusBounceTransition = null;
  88674. this._animatables = new Array();
  88675. }
  88676. Object.defineProperty(BouncingBehavior.prototype, "name", {
  88677. get: function () {
  88678. return "Bouncing";
  88679. },
  88680. enumerable: true,
  88681. configurable: true
  88682. });
  88683. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  88684. /**
  88685. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  88686. */
  88687. get: function () {
  88688. return this._autoTransitionRange;
  88689. },
  88690. /**
  88691. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  88692. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  88693. */
  88694. set: function (value) {
  88695. var _this = this;
  88696. if (this._autoTransitionRange === value) {
  88697. return;
  88698. }
  88699. this._autoTransitionRange = value;
  88700. var camera = this._attachedCamera;
  88701. if (!camera) {
  88702. return;
  88703. }
  88704. if (value) {
  88705. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  88706. if (!mesh) {
  88707. return;
  88708. }
  88709. mesh.computeWorldMatrix(true);
  88710. var diagonal = mesh.getBoundingInfo().diagonalLength;
  88711. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  88712. _this.upperRadiusTransitionRange = diagonal * 0.05;
  88713. });
  88714. }
  88715. else if (this._onMeshTargetChangedObserver) {
  88716. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88717. }
  88718. },
  88719. enumerable: true,
  88720. configurable: true
  88721. });
  88722. BouncingBehavior.prototype.init = function () {
  88723. // Do notihng
  88724. };
  88725. BouncingBehavior.prototype.attach = function (camera) {
  88726. var _this = this;
  88727. this._attachedCamera = camera;
  88728. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88729. if (!_this._attachedCamera) {
  88730. return;
  88731. }
  88732. // Add the bounce animation to the lower radius limit
  88733. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  88734. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  88735. }
  88736. // Add the bounce animation to the upper radius limit
  88737. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  88738. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  88739. }
  88740. });
  88741. };
  88742. BouncingBehavior.prototype.detach = function () {
  88743. if (!this._attachedCamera) {
  88744. return;
  88745. }
  88746. if (this._onAfterCheckInputsObserver) {
  88747. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88748. }
  88749. if (this._onMeshTargetChangedObserver) {
  88750. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88751. }
  88752. this._attachedCamera = null;
  88753. };
  88754. /**
  88755. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  88756. * @param radiusLimit The limit to check against.
  88757. * @return Bool to indicate if at limit.
  88758. */
  88759. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  88760. if (!this._attachedCamera) {
  88761. return false;
  88762. }
  88763. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  88764. return true;
  88765. }
  88766. return false;
  88767. };
  88768. /**
  88769. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  88770. * @param radiusDelta The delta by which to animate to. Can be negative.
  88771. */
  88772. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  88773. var _this = this;
  88774. if (!this._attachedCamera) {
  88775. return;
  88776. }
  88777. if (!this._radiusBounceTransition) {
  88778. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  88779. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  88780. }
  88781. // Prevent zoom until bounce has completed
  88782. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  88783. this._attachedCamera.wheelPrecision = Infinity;
  88784. this._attachedCamera.inertialRadiusOffset = 0;
  88785. // Animate to the radius limit
  88786. this.stopAllAnimations();
  88787. this._radiusIsAnimating = true;
  88788. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  88789. if (animatable) {
  88790. this._animatables.push(animatable);
  88791. }
  88792. };
  88793. /**
  88794. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  88795. */
  88796. BouncingBehavior.prototype._clearAnimationLocks = function () {
  88797. this._radiusIsAnimating = false;
  88798. if (this._attachedCamera) {
  88799. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  88800. }
  88801. };
  88802. /**
  88803. * Stops and removes all animations that have been applied to the camera
  88804. */
  88805. BouncingBehavior.prototype.stopAllAnimations = function () {
  88806. if (this._attachedCamera) {
  88807. this._attachedCamera.animations = [];
  88808. }
  88809. while (this._animatables.length) {
  88810. this._animatables[0].onAnimationEnd = null;
  88811. this._animatables[0].stop();
  88812. this._animatables.shift();
  88813. }
  88814. };
  88815. /**
  88816. * The easing function used by animations
  88817. */
  88818. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  88819. /**
  88820. * The easing mode used by animations
  88821. */
  88822. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  88823. return BouncingBehavior;
  88824. }());
  88825. BABYLON.BouncingBehavior = BouncingBehavior;
  88826. })(BABYLON || (BABYLON = {}));
  88827. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  88828. var BABYLON;
  88829. (function (BABYLON) {
  88830. var AutoRotationBehavior = /** @class */ (function () {
  88831. function AutoRotationBehavior() {
  88832. this._zoomStopsAnimation = false;
  88833. this._idleRotationSpeed = 0.05;
  88834. this._idleRotationWaitTime = 2000;
  88835. this._idleRotationSpinupTime = 2000;
  88836. this._isPointerDown = false;
  88837. this._lastFrameTime = null;
  88838. this._lastInteractionTime = -Infinity;
  88839. this._cameraRotationSpeed = 0;
  88840. this._lastFrameRadius = 0;
  88841. }
  88842. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  88843. get: function () {
  88844. return "AutoRotation";
  88845. },
  88846. enumerable: true,
  88847. configurable: true
  88848. });
  88849. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  88850. /**
  88851. * Gets the flag that indicates if user zooming should stop animation.
  88852. */
  88853. get: function () {
  88854. return this._zoomStopsAnimation;
  88855. },
  88856. /**
  88857. * Sets the flag that indicates if user zooming should stop animation.
  88858. */
  88859. set: function (flag) {
  88860. this._zoomStopsAnimation = flag;
  88861. },
  88862. enumerable: true,
  88863. configurable: true
  88864. });
  88865. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  88866. /**
  88867. * Gets the default speed at which the camera rotates around the model.
  88868. */
  88869. get: function () {
  88870. return this._idleRotationSpeed;
  88871. },
  88872. /**
  88873. * Sets the default speed at which the camera rotates around the model.
  88874. */
  88875. set: function (speed) {
  88876. this._idleRotationSpeed = speed;
  88877. },
  88878. enumerable: true,
  88879. configurable: true
  88880. });
  88881. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  88882. /**
  88883. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  88884. */
  88885. get: function () {
  88886. return this._idleRotationWaitTime;
  88887. },
  88888. /**
  88889. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  88890. */
  88891. set: function (time) {
  88892. this._idleRotationWaitTime = time;
  88893. },
  88894. enumerable: true,
  88895. configurable: true
  88896. });
  88897. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  88898. /**
  88899. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  88900. */
  88901. get: function () {
  88902. return this._idleRotationSpinupTime;
  88903. },
  88904. /**
  88905. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  88906. */
  88907. set: function (time) {
  88908. this._idleRotationSpinupTime = time;
  88909. },
  88910. enumerable: true,
  88911. configurable: true
  88912. });
  88913. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  88914. /**
  88915. * Gets a value indicating if the camera is currently rotating because of this behavior
  88916. */
  88917. get: function () {
  88918. return Math.abs(this._cameraRotationSpeed) > 0;
  88919. },
  88920. enumerable: true,
  88921. configurable: true
  88922. });
  88923. AutoRotationBehavior.prototype.init = function () {
  88924. // Do notihng
  88925. };
  88926. AutoRotationBehavior.prototype.attach = function (camera) {
  88927. var _this = this;
  88928. this._attachedCamera = camera;
  88929. var scene = this._attachedCamera.getScene();
  88930. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  88931. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88932. _this._isPointerDown = true;
  88933. return;
  88934. }
  88935. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  88936. _this._isPointerDown = false;
  88937. }
  88938. });
  88939. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88940. var now = BABYLON.Tools.Now;
  88941. var dt = 0;
  88942. if (_this._lastFrameTime != null) {
  88943. dt = now - _this._lastFrameTime;
  88944. }
  88945. _this._lastFrameTime = now;
  88946. // Stop the animation if there is user interaction and the animation should stop for this interaction
  88947. _this._applyUserInteraction();
  88948. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  88949. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  88950. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  88951. // Step camera rotation by rotation speed
  88952. if (_this._attachedCamera) {
  88953. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  88954. }
  88955. });
  88956. };
  88957. AutoRotationBehavior.prototype.detach = function () {
  88958. if (!this._attachedCamera) {
  88959. return;
  88960. }
  88961. var scene = this._attachedCamera.getScene();
  88962. if (this._onPrePointerObservableObserver) {
  88963. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  88964. }
  88965. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88966. this._attachedCamera = null;
  88967. };
  88968. /**
  88969. * Returns true if user is scrolling.
  88970. * @return true if user is scrolling.
  88971. */
  88972. AutoRotationBehavior.prototype._userIsZooming = function () {
  88973. if (!this._attachedCamera) {
  88974. return false;
  88975. }
  88976. return this._attachedCamera.inertialRadiusOffset !== 0;
  88977. };
  88978. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  88979. if (!this._attachedCamera) {
  88980. return false;
  88981. }
  88982. var zoomHasHitLimit = false;
  88983. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  88984. zoomHasHitLimit = true;
  88985. }
  88986. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  88987. this._lastFrameRadius = this._attachedCamera.radius;
  88988. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  88989. };
  88990. /**
  88991. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  88992. */
  88993. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  88994. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  88995. this._lastInteractionTime = BABYLON.Tools.Now;
  88996. }
  88997. };
  88998. // Tools
  88999. AutoRotationBehavior.prototype._userIsMoving = function () {
  89000. if (!this._attachedCamera) {
  89001. return false;
  89002. }
  89003. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  89004. this._attachedCamera.inertialBetaOffset !== 0 ||
  89005. this._attachedCamera.inertialRadiusOffset !== 0 ||
  89006. this._attachedCamera.inertialPanningX !== 0 ||
  89007. this._attachedCamera.inertialPanningY !== 0 ||
  89008. this._isPointerDown;
  89009. };
  89010. return AutoRotationBehavior;
  89011. }());
  89012. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  89013. })(BABYLON || (BABYLON = {}));
  89014. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  89015. var BABYLON;
  89016. (function (BABYLON) {
  89017. var NullEngineOptions = /** @class */ (function () {
  89018. function NullEngineOptions() {
  89019. this.renderWidth = 512;
  89020. this.renderHeight = 256;
  89021. this.textureSize = 512;
  89022. this.deterministicLockstep = false;
  89023. this.lockstepMaxSteps = 4;
  89024. }
  89025. return NullEngineOptions;
  89026. }());
  89027. BABYLON.NullEngineOptions = NullEngineOptions;
  89028. /**
  89029. * The null engine class provides support for headless version of babylon.js.
  89030. * This can be used in server side scenario or for testing purposes
  89031. */
  89032. var NullEngine = /** @class */ (function (_super) {
  89033. __extends(NullEngine, _super);
  89034. function NullEngine(options) {
  89035. if (options === void 0) { options = new NullEngineOptions(); }
  89036. var _this = _super.call(this, null) || this;
  89037. if (options.deterministicLockstep === undefined) {
  89038. options.deterministicLockstep = false;
  89039. }
  89040. if (options.lockstepMaxSteps === undefined) {
  89041. options.lockstepMaxSteps = 4;
  89042. }
  89043. _this._options = options;
  89044. // Init caps
  89045. // We consider we are on a webgl1 capable device
  89046. _this._caps = new BABYLON.EngineCapabilities();
  89047. _this._caps.maxTexturesImageUnits = 16;
  89048. _this._caps.maxVertexTextureImageUnits = 16;
  89049. _this._caps.maxTextureSize = 512;
  89050. _this._caps.maxCubemapTextureSize = 512;
  89051. _this._caps.maxRenderTextureSize = 512;
  89052. _this._caps.maxVertexAttribs = 16;
  89053. _this._caps.maxVaryingVectors = 16;
  89054. _this._caps.maxFragmentUniformVectors = 16;
  89055. _this._caps.maxVertexUniformVectors = 16;
  89056. // Extensions
  89057. _this._caps.standardDerivatives = false;
  89058. _this._caps.astc = null;
  89059. _this._caps.s3tc = null;
  89060. _this._caps.pvrtc = null;
  89061. _this._caps.etc1 = null;
  89062. _this._caps.etc2 = null;
  89063. _this._caps.textureAnisotropicFilterExtension = null;
  89064. _this._caps.maxAnisotropy = 0;
  89065. _this._caps.uintIndices = false;
  89066. _this._caps.fragmentDepthSupported = false;
  89067. _this._caps.highPrecisionShaderSupported = true;
  89068. _this._caps.colorBufferFloat = false;
  89069. _this._caps.textureFloat = false;
  89070. _this._caps.textureFloatLinearFiltering = false;
  89071. _this._caps.textureFloatRender = false;
  89072. _this._caps.textureHalfFloat = false;
  89073. _this._caps.textureHalfFloatLinearFiltering = false;
  89074. _this._caps.textureHalfFloatRender = false;
  89075. _this._caps.textureLOD = false;
  89076. _this._caps.drawBuffersExtension = false;
  89077. _this._caps.depthTextureExtension = false;
  89078. _this._caps.vertexArrayObject = false;
  89079. _this._caps.instancedArrays = false;
  89080. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  89081. // Wrappers
  89082. if (typeof URL === "undefined") {
  89083. URL = {
  89084. createObjectURL: function () { },
  89085. revokeObjectURL: function () { }
  89086. };
  89087. }
  89088. if (typeof Blob === "undefined") {
  89089. Blob = function () { };
  89090. }
  89091. return _this;
  89092. }
  89093. NullEngine.prototype.isDeterministicLockStep = function () {
  89094. return this._options.deterministicLockstep;
  89095. };
  89096. NullEngine.prototype.getLockstepMaxSteps = function () {
  89097. return this._options.lockstepMaxSteps;
  89098. };
  89099. NullEngine.prototype.getHardwareScalingLevel = function () {
  89100. return 1.0;
  89101. };
  89102. NullEngine.prototype.createVertexBuffer = function (vertices) {
  89103. return {
  89104. capacity: 0,
  89105. references: 1,
  89106. is32Bits: false
  89107. };
  89108. };
  89109. NullEngine.prototype.createIndexBuffer = function (indices) {
  89110. return {
  89111. capacity: 0,
  89112. references: 1,
  89113. is32Bits: false
  89114. };
  89115. };
  89116. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  89117. if (stencil === void 0) { stencil = false; }
  89118. };
  89119. NullEngine.prototype.getRenderWidth = function (useScreen) {
  89120. if (useScreen === void 0) { useScreen = false; }
  89121. if (!useScreen && this._currentRenderTarget) {
  89122. return this._currentRenderTarget.width;
  89123. }
  89124. return this._options.renderWidth;
  89125. };
  89126. NullEngine.prototype.getRenderHeight = function (useScreen) {
  89127. if (useScreen === void 0) { useScreen = false; }
  89128. if (!useScreen && this._currentRenderTarget) {
  89129. return this._currentRenderTarget.height;
  89130. }
  89131. return this._options.renderHeight;
  89132. };
  89133. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  89134. this._cachedViewport = viewport;
  89135. };
  89136. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  89137. return {
  89138. transformFeedback: null,
  89139. __SPECTOR_rebuildProgram: null
  89140. };
  89141. };
  89142. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  89143. return [];
  89144. };
  89145. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  89146. return [];
  89147. };
  89148. NullEngine.prototype.bindSamplers = function (effect) {
  89149. this._currentEffect = null;
  89150. };
  89151. NullEngine.prototype.enableEffect = function (effect) {
  89152. this._currentEffect = effect;
  89153. if (effect.onBind) {
  89154. effect.onBind(effect);
  89155. }
  89156. effect.onBindObservable.notifyObservers(effect);
  89157. };
  89158. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  89159. if (zOffset === void 0) { zOffset = 0; }
  89160. if (reverseSide === void 0) { reverseSide = false; }
  89161. };
  89162. NullEngine.prototype.setIntArray = function (uniform, array) {
  89163. };
  89164. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  89165. };
  89166. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  89167. };
  89168. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  89169. };
  89170. NullEngine.prototype.setFloatArray = function (uniform, array) {
  89171. };
  89172. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  89173. };
  89174. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  89175. };
  89176. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  89177. };
  89178. NullEngine.prototype.setArray = function (uniform, array) {
  89179. };
  89180. NullEngine.prototype.setArray2 = function (uniform, array) {
  89181. };
  89182. NullEngine.prototype.setArray3 = function (uniform, array) {
  89183. };
  89184. NullEngine.prototype.setArray4 = function (uniform, array) {
  89185. };
  89186. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  89187. };
  89188. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  89189. };
  89190. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  89191. };
  89192. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  89193. };
  89194. NullEngine.prototype.setFloat = function (uniform, value) {
  89195. };
  89196. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  89197. };
  89198. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  89199. };
  89200. NullEngine.prototype.setBool = function (uniform, bool) {
  89201. };
  89202. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  89203. };
  89204. NullEngine.prototype.setColor3 = function (uniform, color3) {
  89205. };
  89206. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  89207. };
  89208. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  89209. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  89210. if (this._alphaMode === mode) {
  89211. return;
  89212. }
  89213. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  89214. if (!noDepthWriteChange) {
  89215. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  89216. }
  89217. this._alphaMode = mode;
  89218. };
  89219. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  89220. };
  89221. NullEngine.prototype.wipeCaches = function (bruteForce) {
  89222. if (this.preventCacheWipeBetweenFrames) {
  89223. return;
  89224. }
  89225. this.resetTextureCache();
  89226. this._currentEffect = null;
  89227. if (bruteForce) {
  89228. this._currentProgram = null;
  89229. this._stencilState.reset();
  89230. this._depthCullingState.reset();
  89231. this._alphaState.reset();
  89232. }
  89233. this._cachedVertexBuffers = null;
  89234. this._cachedIndexBuffer = null;
  89235. this._cachedEffectForVertexBuffers = null;
  89236. };
  89237. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  89238. };
  89239. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  89240. };
  89241. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  89242. };
  89243. NullEngine.prototype._createTexture = function () {
  89244. return {};
  89245. };
  89246. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  89247. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  89248. if (onLoad === void 0) { onLoad = null; }
  89249. if (onError === void 0) { onError = null; }
  89250. if (buffer === void 0) { buffer = null; }
  89251. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  89252. var url = String(urlArg);
  89253. texture.url = url;
  89254. texture.generateMipMaps = !noMipmap;
  89255. texture.samplingMode = samplingMode;
  89256. texture.invertY = invertY;
  89257. texture.baseWidth = this._options.textureSize;
  89258. texture.baseHeight = this._options.textureSize;
  89259. texture.width = this._options.textureSize;
  89260. texture.height = this._options.textureSize;
  89261. if (format) {
  89262. texture.format = format;
  89263. }
  89264. texture.isReady = true;
  89265. if (onLoad) {
  89266. onLoad();
  89267. }
  89268. return texture;
  89269. };
  89270. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  89271. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  89272. if (options !== undefined && typeof options === "object") {
  89273. fullOptions.generateMipMaps = options.generateMipMaps;
  89274. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  89275. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  89276. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  89277. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  89278. }
  89279. else {
  89280. fullOptions.generateMipMaps = options;
  89281. fullOptions.generateDepthBuffer = true;
  89282. fullOptions.generateStencilBuffer = false;
  89283. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89284. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  89285. }
  89286. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  89287. var width = size.width || size;
  89288. var height = size.height || size;
  89289. texture._depthStencilBuffer = {};
  89290. texture._framebuffer = {};
  89291. texture.baseWidth = width;
  89292. texture.baseHeight = height;
  89293. texture.width = width;
  89294. texture.height = height;
  89295. texture.isReady = true;
  89296. texture.samples = 1;
  89297. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  89298. texture.samplingMode = fullOptions.samplingMode;
  89299. texture.type = fullOptions.type;
  89300. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  89301. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  89302. return texture;
  89303. };
  89304. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  89305. texture.samplingMode = samplingMode;
  89306. };
  89307. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  89308. if (this._currentRenderTarget) {
  89309. this.unBindFramebuffer(this._currentRenderTarget);
  89310. }
  89311. this._currentRenderTarget = texture;
  89312. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  89313. if (this._cachedViewport && !forceFullscreenViewport) {
  89314. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  89315. }
  89316. };
  89317. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  89318. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  89319. this._currentRenderTarget = null;
  89320. if (onBeforeUnbind) {
  89321. if (texture._MSAAFramebuffer) {
  89322. this._currentFramebuffer = texture._framebuffer;
  89323. }
  89324. onBeforeUnbind();
  89325. }
  89326. this._currentFramebuffer = null;
  89327. };
  89328. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  89329. var vbo = {
  89330. capacity: 1,
  89331. references: 1,
  89332. is32Bits: false
  89333. };
  89334. return vbo;
  89335. };
  89336. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  89337. if (offset === void 0) { offset = 0; }
  89338. };
  89339. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  89340. };
  89341. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  89342. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  89343. this._boundTexturesCache[this._activeChannel] = texture;
  89344. }
  89345. };
  89346. NullEngine.prototype._bindTexture = function (channel, texture) {
  89347. if (channel < 0) {
  89348. return;
  89349. }
  89350. this._bindTextureDirectly(0, texture);
  89351. };
  89352. NullEngine.prototype._releaseBuffer = function (buffer) {
  89353. buffer.references--;
  89354. if (buffer.references === 0) {
  89355. return true;
  89356. }
  89357. return false;
  89358. };
  89359. return NullEngine;
  89360. }(BABYLON.Engine));
  89361. BABYLON.NullEngine = NullEngine;
  89362. })(BABYLON || (BABYLON = {}));
  89363. //# sourceMappingURL=babylon.nullEngine.js.map
  89364. var BABYLON;
  89365. (function (BABYLON) {
  89366. /**
  89367. * This class can be used to get instrumentation data from a Babylon engine
  89368. */
  89369. var EngineInstrumentation = /** @class */ (function () {
  89370. function EngineInstrumentation(engine) {
  89371. this.engine = engine;
  89372. this._captureGPUFrameTime = false;
  89373. this._gpuFrameTime = new BABYLON.PerfCounter();
  89374. this._captureShaderCompilationTime = false;
  89375. this._shaderCompilationTime = new BABYLON.PerfCounter();
  89376. // Observers
  89377. this._onBeginFrameObserver = null;
  89378. this._onEndFrameObserver = null;
  89379. this._onBeforeShaderCompilationObserver = null;
  89380. this._onAfterShaderCompilationObserver = null;
  89381. }
  89382. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  89383. // Properties
  89384. /**
  89385. * Gets the perf counter used for GPU frame time
  89386. */
  89387. get: function () {
  89388. return this._gpuFrameTime;
  89389. },
  89390. enumerable: true,
  89391. configurable: true
  89392. });
  89393. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  89394. /**
  89395. * Gets the GPU frame time capture status
  89396. */
  89397. get: function () {
  89398. return this._captureGPUFrameTime;
  89399. },
  89400. /**
  89401. * Enable or disable the GPU frame time capture
  89402. */
  89403. set: function (value) {
  89404. var _this = this;
  89405. if (value === this._captureGPUFrameTime) {
  89406. return;
  89407. }
  89408. this._captureGPUFrameTime = value;
  89409. if (value) {
  89410. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  89411. if (!_this._gpuFrameTimeToken) {
  89412. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  89413. }
  89414. });
  89415. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  89416. if (!_this._gpuFrameTimeToken) {
  89417. return;
  89418. }
  89419. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  89420. if (time > -1) {
  89421. _this._gpuFrameTimeToken = null;
  89422. _this._gpuFrameTime.fetchNewFrame();
  89423. _this._gpuFrameTime.addCount(time, true);
  89424. }
  89425. });
  89426. }
  89427. else {
  89428. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  89429. this._onBeginFrameObserver = null;
  89430. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  89431. this._onEndFrameObserver = null;
  89432. }
  89433. },
  89434. enumerable: true,
  89435. configurable: true
  89436. });
  89437. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  89438. /**
  89439. * Gets the perf counter used for shader compilation time
  89440. */
  89441. get: function () {
  89442. return this._shaderCompilationTime;
  89443. },
  89444. enumerable: true,
  89445. configurable: true
  89446. });
  89447. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  89448. /**
  89449. * Gets the shader compilation time capture status
  89450. */
  89451. get: function () {
  89452. return this._captureShaderCompilationTime;
  89453. },
  89454. /**
  89455. * Enable or disable the shader compilation time capture
  89456. */
  89457. set: function (value) {
  89458. var _this = this;
  89459. if (value === this._captureShaderCompilationTime) {
  89460. return;
  89461. }
  89462. this._captureShaderCompilationTime = value;
  89463. if (value) {
  89464. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  89465. _this._shaderCompilationTime.fetchNewFrame();
  89466. _this._shaderCompilationTime.beginMonitoring();
  89467. });
  89468. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  89469. _this._shaderCompilationTime.endMonitoring();
  89470. });
  89471. }
  89472. else {
  89473. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  89474. this._onBeforeShaderCompilationObserver = null;
  89475. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  89476. this._onAfterShaderCompilationObserver = null;
  89477. }
  89478. },
  89479. enumerable: true,
  89480. configurable: true
  89481. });
  89482. EngineInstrumentation.prototype.dispose = function () {
  89483. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  89484. this._onBeginFrameObserver = null;
  89485. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  89486. this._onEndFrameObserver = null;
  89487. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  89488. this._onBeforeShaderCompilationObserver = null;
  89489. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  89490. this._onAfterShaderCompilationObserver = null;
  89491. this.engine = null;
  89492. };
  89493. return EngineInstrumentation;
  89494. }());
  89495. BABYLON.EngineInstrumentation = EngineInstrumentation;
  89496. })(BABYLON || (BABYLON = {}));
  89497. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  89498. var BABYLON;
  89499. (function (BABYLON) {
  89500. /**
  89501. * This class can be used to get instrumentation data from a Babylon engine
  89502. */
  89503. var SceneInstrumentation = /** @class */ (function () {
  89504. function SceneInstrumentation(scene) {
  89505. var _this = this;
  89506. this.scene = scene;
  89507. this._captureActiveMeshesEvaluationTime = false;
  89508. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  89509. this._captureRenderTargetsRenderTime = false;
  89510. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  89511. this._captureFrameTime = false;
  89512. this._frameTime = new BABYLON.PerfCounter();
  89513. this._captureRenderTime = false;
  89514. this._renderTime = new BABYLON.PerfCounter();
  89515. this._captureInterFrameTime = false;
  89516. this._interFrameTime = new BABYLON.PerfCounter();
  89517. this._captureParticlesRenderTime = false;
  89518. this._particlesRenderTime = new BABYLON.PerfCounter();
  89519. this._captureSpritesRenderTime = false;
  89520. this._spritesRenderTime = new BABYLON.PerfCounter();
  89521. this._capturePhysicsTime = false;
  89522. this._physicsTime = new BABYLON.PerfCounter();
  89523. this._captureAnimationsTime = false;
  89524. this._animationsTime = new BABYLON.PerfCounter();
  89525. // Observers
  89526. this._onBeforeActiveMeshesEvaluationObserver = null;
  89527. this._onAfterActiveMeshesEvaluationObserver = null;
  89528. this._onBeforeRenderTargetsRenderObserver = null;
  89529. this._onAfterRenderTargetsRenderObserver = null;
  89530. this._onAfterRenderObserver = null;
  89531. this._onBeforeDrawPhaseObserver = null;
  89532. this._onAfterDrawPhaseObserver = null;
  89533. this._onBeforeAnimationsObserver = null;
  89534. this._onBeforeParticlesRenderingObserver = null;
  89535. this._onAfterParticlesRenderingObserver = null;
  89536. this._onBeforeSpritesRenderingObserver = null;
  89537. this._onAfterSpritesRenderingObserver = null;
  89538. this._onBeforePhysicsObserver = null;
  89539. this._onAfterPhysicsObserver = null;
  89540. this._onAfterAnimationsObserver = null;
  89541. // Before render
  89542. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  89543. if (_this._captureActiveMeshesEvaluationTime) {
  89544. _this._activeMeshesEvaluationTime.fetchNewFrame();
  89545. }
  89546. if (_this._captureRenderTargetsRenderTime) {
  89547. _this._renderTargetsRenderTime.fetchNewFrame();
  89548. }
  89549. if (_this._captureFrameTime) {
  89550. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  89551. _this._frameTime.beginMonitoring();
  89552. }
  89553. if (_this._captureInterFrameTime) {
  89554. _this._interFrameTime.endMonitoring();
  89555. }
  89556. if (_this._captureParticlesRenderTime) {
  89557. _this._particlesRenderTime.fetchNewFrame();
  89558. }
  89559. if (_this._captureSpritesRenderTime) {
  89560. _this._spritesRenderTime.fetchNewFrame();
  89561. }
  89562. if (_this._captureAnimationsTime) {
  89563. _this._animationsTime.beginMonitoring();
  89564. }
  89565. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  89566. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  89567. });
  89568. // After render
  89569. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  89570. if (_this._captureFrameTime) {
  89571. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  89572. _this._frameTime.endMonitoring();
  89573. }
  89574. if (_this._captureRenderTime) {
  89575. _this._renderTime.endMonitoring(false);
  89576. }
  89577. if (_this._captureInterFrameTime) {
  89578. _this._interFrameTime.beginMonitoring();
  89579. }
  89580. });
  89581. }
  89582. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  89583. // Properties
  89584. /**
  89585. * Gets the perf counter used for active meshes evaluation time
  89586. */
  89587. get: function () {
  89588. return this._activeMeshesEvaluationTime;
  89589. },
  89590. enumerable: true,
  89591. configurable: true
  89592. });
  89593. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  89594. /**
  89595. * Gets the active meshes evaluation time capture status
  89596. */
  89597. get: function () {
  89598. return this._captureActiveMeshesEvaluationTime;
  89599. },
  89600. /**
  89601. * Enable or disable the active meshes evaluation time capture
  89602. */
  89603. set: function (value) {
  89604. var _this = this;
  89605. if (value === this._captureActiveMeshesEvaluationTime) {
  89606. return;
  89607. }
  89608. this._captureActiveMeshesEvaluationTime = value;
  89609. if (value) {
  89610. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  89611. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  89612. _this._activeMeshesEvaluationTime.beginMonitoring();
  89613. });
  89614. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  89615. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  89616. _this._activeMeshesEvaluationTime.endMonitoring();
  89617. });
  89618. }
  89619. else {
  89620. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  89621. this._onBeforeActiveMeshesEvaluationObserver = null;
  89622. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  89623. this._onAfterActiveMeshesEvaluationObserver = null;
  89624. }
  89625. },
  89626. enumerable: true,
  89627. configurable: true
  89628. });
  89629. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  89630. /**
  89631. * Gets the perf counter used for render targets render time
  89632. */
  89633. get: function () {
  89634. return this._renderTargetsRenderTime;
  89635. },
  89636. enumerable: true,
  89637. configurable: true
  89638. });
  89639. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  89640. /**
  89641. * Gets the render targets render time capture status
  89642. */
  89643. get: function () {
  89644. return this._captureRenderTargetsRenderTime;
  89645. },
  89646. /**
  89647. * Enable or disable the render targets render time capture
  89648. */
  89649. set: function (value) {
  89650. var _this = this;
  89651. if (value === this._captureRenderTargetsRenderTime) {
  89652. return;
  89653. }
  89654. this._captureRenderTargetsRenderTime = value;
  89655. if (value) {
  89656. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  89657. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  89658. _this._renderTargetsRenderTime.beginMonitoring();
  89659. });
  89660. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  89661. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  89662. _this._renderTargetsRenderTime.endMonitoring(false);
  89663. });
  89664. }
  89665. else {
  89666. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  89667. this._onBeforeRenderTargetsRenderObserver = null;
  89668. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  89669. this._onAfterRenderTargetsRenderObserver = null;
  89670. }
  89671. },
  89672. enumerable: true,
  89673. configurable: true
  89674. });
  89675. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  89676. /**
  89677. * Gets the perf counter used for particles render time
  89678. */
  89679. get: function () {
  89680. return this._particlesRenderTime;
  89681. },
  89682. enumerable: true,
  89683. configurable: true
  89684. });
  89685. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  89686. /**
  89687. * Gets the particles render time capture status
  89688. */
  89689. get: function () {
  89690. return this._captureParticlesRenderTime;
  89691. },
  89692. /**
  89693. * Enable or disable the particles render time capture
  89694. */
  89695. set: function (value) {
  89696. var _this = this;
  89697. if (value === this._captureParticlesRenderTime) {
  89698. return;
  89699. }
  89700. this._captureParticlesRenderTime = value;
  89701. if (value) {
  89702. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  89703. BABYLON.Tools.StartPerformanceCounter("Particles");
  89704. _this._particlesRenderTime.beginMonitoring();
  89705. });
  89706. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  89707. BABYLON.Tools.EndPerformanceCounter("Particles");
  89708. _this._particlesRenderTime.endMonitoring(false);
  89709. });
  89710. }
  89711. else {
  89712. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  89713. this._onBeforeParticlesRenderingObserver = null;
  89714. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  89715. this._onAfterParticlesRenderingObserver = null;
  89716. }
  89717. },
  89718. enumerable: true,
  89719. configurable: true
  89720. });
  89721. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  89722. /**
  89723. * Gets the perf counter used for sprites render time
  89724. */
  89725. get: function () {
  89726. return this._spritesRenderTime;
  89727. },
  89728. enumerable: true,
  89729. configurable: true
  89730. });
  89731. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  89732. /**
  89733. * Gets the sprites render time capture status
  89734. */
  89735. get: function () {
  89736. return this._captureSpritesRenderTime;
  89737. },
  89738. /**
  89739. * Enable or disable the sprites render time capture
  89740. */
  89741. set: function (value) {
  89742. var _this = this;
  89743. if (value === this._captureSpritesRenderTime) {
  89744. return;
  89745. }
  89746. this._captureSpritesRenderTime = value;
  89747. if (value) {
  89748. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  89749. BABYLON.Tools.StartPerformanceCounter("Sprites");
  89750. _this._spritesRenderTime.beginMonitoring();
  89751. });
  89752. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  89753. BABYLON.Tools.EndPerformanceCounter("Sprites");
  89754. _this._spritesRenderTime.endMonitoring(false);
  89755. });
  89756. }
  89757. else {
  89758. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  89759. this._onBeforeSpritesRenderingObserver = null;
  89760. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  89761. this._onAfterSpritesRenderingObserver = null;
  89762. }
  89763. },
  89764. enumerable: true,
  89765. configurable: true
  89766. });
  89767. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  89768. /**
  89769. * Gets the perf counter used for physics time
  89770. */
  89771. get: function () {
  89772. return this._physicsTime;
  89773. },
  89774. enumerable: true,
  89775. configurable: true
  89776. });
  89777. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  89778. /**
  89779. * Gets the physics time capture status
  89780. */
  89781. get: function () {
  89782. return this._capturePhysicsTime;
  89783. },
  89784. /**
  89785. * Enable or disable the physics time capture
  89786. */
  89787. set: function (value) {
  89788. var _this = this;
  89789. if (value === this._capturePhysicsTime) {
  89790. return;
  89791. }
  89792. this._capturePhysicsTime = value;
  89793. if (value) {
  89794. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  89795. BABYLON.Tools.StartPerformanceCounter("Physics");
  89796. _this._physicsTime.beginMonitoring();
  89797. });
  89798. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  89799. BABYLON.Tools.EndPerformanceCounter("Physics");
  89800. _this._physicsTime.endMonitoring();
  89801. });
  89802. }
  89803. else {
  89804. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  89805. this._onBeforePhysicsObserver = null;
  89806. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  89807. this._onAfterPhysicsObserver = null;
  89808. }
  89809. },
  89810. enumerable: true,
  89811. configurable: true
  89812. });
  89813. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  89814. /**
  89815. * Gets the perf counter used for animations time
  89816. */
  89817. get: function () {
  89818. return this._animationsTime;
  89819. },
  89820. enumerable: true,
  89821. configurable: true
  89822. });
  89823. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  89824. /**
  89825. * Gets the animations time capture status
  89826. */
  89827. get: function () {
  89828. return this._captureAnimationsTime;
  89829. },
  89830. /**
  89831. * Enable or disable the animations time capture
  89832. */
  89833. set: function (value) {
  89834. var _this = this;
  89835. if (value === this._captureAnimationsTime) {
  89836. return;
  89837. }
  89838. this._captureAnimationsTime = value;
  89839. if (value) {
  89840. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  89841. _this._animationsTime.endMonitoring();
  89842. });
  89843. }
  89844. else {
  89845. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  89846. this._onAfterAnimationsObserver = null;
  89847. }
  89848. },
  89849. enumerable: true,
  89850. configurable: true
  89851. });
  89852. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  89853. /**
  89854. * Gets the perf counter used for frame time capture
  89855. */
  89856. get: function () {
  89857. return this._frameTime;
  89858. },
  89859. enumerable: true,
  89860. configurable: true
  89861. });
  89862. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  89863. /**
  89864. * Gets the frame time capture status
  89865. */
  89866. get: function () {
  89867. return this._captureFrameTime;
  89868. },
  89869. /**
  89870. * Enable or disable the frame time capture
  89871. */
  89872. set: function (value) {
  89873. this._captureFrameTime = value;
  89874. },
  89875. enumerable: true,
  89876. configurable: true
  89877. });
  89878. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  89879. /**
  89880. * Gets the perf counter used for inter-frames time capture
  89881. */
  89882. get: function () {
  89883. return this._interFrameTime;
  89884. },
  89885. enumerable: true,
  89886. configurable: true
  89887. });
  89888. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  89889. /**
  89890. * Gets the inter-frames time capture status
  89891. */
  89892. get: function () {
  89893. return this._captureInterFrameTime;
  89894. },
  89895. /**
  89896. * Enable or disable the inter-frames time capture
  89897. */
  89898. set: function (value) {
  89899. this._captureInterFrameTime = value;
  89900. },
  89901. enumerable: true,
  89902. configurable: true
  89903. });
  89904. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  89905. /**
  89906. * Gets the perf counter used for render time capture
  89907. */
  89908. get: function () {
  89909. return this._renderTime;
  89910. },
  89911. enumerable: true,
  89912. configurable: true
  89913. });
  89914. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  89915. /**
  89916. * Gets the render time capture status
  89917. */
  89918. get: function () {
  89919. return this._captureRenderTime;
  89920. },
  89921. /**
  89922. * Enable or disable the render time capture
  89923. */
  89924. set: function (value) {
  89925. var _this = this;
  89926. if (value === this._captureRenderTime) {
  89927. return;
  89928. }
  89929. this._captureRenderTime = value;
  89930. if (value) {
  89931. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  89932. _this._renderTime.beginMonitoring();
  89933. BABYLON.Tools.StartPerformanceCounter("Main render");
  89934. });
  89935. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  89936. _this._renderTime.endMonitoring(false);
  89937. BABYLON.Tools.EndPerformanceCounter("Main render");
  89938. });
  89939. }
  89940. else {
  89941. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  89942. this._onBeforeDrawPhaseObserver = null;
  89943. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  89944. this._onAfterDrawPhaseObserver = null;
  89945. }
  89946. },
  89947. enumerable: true,
  89948. configurable: true
  89949. });
  89950. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  89951. /**
  89952. * Gets the perf counter used for draw calls
  89953. */
  89954. get: function () {
  89955. return this.scene.getEngine()._drawCalls;
  89956. },
  89957. enumerable: true,
  89958. configurable: true
  89959. });
  89960. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  89961. /**
  89962. * Gets the perf counter used for texture collisions
  89963. */
  89964. get: function () {
  89965. return this.scene.getEngine()._textureCollisions;
  89966. },
  89967. enumerable: true,
  89968. configurable: true
  89969. });
  89970. SceneInstrumentation.prototype.dispose = function () {
  89971. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  89972. this._onAfterRenderObserver = null;
  89973. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  89974. this._onBeforeActiveMeshesEvaluationObserver = null;
  89975. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  89976. this._onAfterActiveMeshesEvaluationObserver = null;
  89977. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  89978. this._onBeforeRenderTargetsRenderObserver = null;
  89979. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  89980. this._onAfterRenderTargetsRenderObserver = null;
  89981. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  89982. this._onBeforeAnimationsObserver = null;
  89983. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  89984. this._onBeforeParticlesRenderingObserver = null;
  89985. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  89986. this._onAfterParticlesRenderingObserver = null;
  89987. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  89988. this._onBeforeSpritesRenderingObserver = null;
  89989. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  89990. this._onAfterSpritesRenderingObserver = null;
  89991. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  89992. this._onBeforeDrawPhaseObserver = null;
  89993. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  89994. this._onAfterDrawPhaseObserver = null;
  89995. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  89996. this._onBeforePhysicsObserver = null;
  89997. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  89998. this._onAfterPhysicsObserver = null;
  89999. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  90000. this._onAfterAnimationsObserver = null;
  90001. this.scene = null;
  90002. };
  90003. return SceneInstrumentation;
  90004. }());
  90005. BABYLON.SceneInstrumentation = SceneInstrumentation;
  90006. })(BABYLON || (BABYLON = {}));
  90007. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  90008. var BABYLON;
  90009. (function (BABYLON) {
  90010. var _TimeToken = /** @class */ (function () {
  90011. function _TimeToken() {
  90012. this._timeElapsedQueryEnded = false;
  90013. }
  90014. return _TimeToken;
  90015. }());
  90016. BABYLON._TimeToken = _TimeToken;
  90017. })(BABYLON || (BABYLON = {}));
  90018. //# sourceMappingURL=babylon.timeToken.js.map
  90019. var BABYLON;
  90020. (function (BABYLON) {
  90021. /**
  90022. * Background material defines definition.
  90023. * @ignore Mainly internal Use
  90024. */
  90025. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  90026. __extends(BackgroundMaterialDefines, _super);
  90027. /**
  90028. * Constructor of the defines.
  90029. */
  90030. function BackgroundMaterialDefines() {
  90031. var _this = _super.call(this) || this;
  90032. /**
  90033. * True if the diffuse texture is in use.
  90034. */
  90035. _this.DIFFUSE = false;
  90036. /**
  90037. * The direct UV channel to use.
  90038. */
  90039. _this.DIFFUSEDIRECTUV = 0;
  90040. /**
  90041. * True if the diffuse texture is in gamma space.
  90042. */
  90043. _this.GAMMADIFFUSE = false;
  90044. /**
  90045. * True if the diffuse texture has opacity in the alpha channel.
  90046. */
  90047. _this.DIFFUSEHASALPHA = false;
  90048. /**
  90049. * True if you want the material to fade to transparent at grazing angle.
  90050. */
  90051. _this.OPACITYFRESNEL = false;
  90052. /**
  90053. * True if an extra blur needs to be added in the reflection.
  90054. */
  90055. _this.REFLECTIONBLUR = false;
  90056. /**
  90057. * True if you want the material to fade to reflection at grazing angle.
  90058. */
  90059. _this.REFLECTIONFRESNEL = false;
  90060. /**
  90061. * True if you want the material to falloff as far as you move away from the scene center.
  90062. */
  90063. _this.REFLECTIONFALLOFF = false;
  90064. /**
  90065. * False if the current Webgl implementation does not support the texture lod extension.
  90066. */
  90067. _this.TEXTURELODSUPPORT = false;
  90068. /**
  90069. * True to ensure the data are premultiplied.
  90070. */
  90071. _this.PREMULTIPLYALPHA = false;
  90072. /**
  90073. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  90074. */
  90075. _this.USERGBCOLOR = false;
  90076. /**
  90077. * True to add noise in order to reduce the banding effect.
  90078. */
  90079. _this.NOISE = false;
  90080. /**
  90081. * is the reflection texture in BGR color scheme?
  90082. * Mainly used to solve a bug in ios10 video tag
  90083. */
  90084. _this.REFLECTIONBGR = false;
  90085. _this.IMAGEPROCESSING = false;
  90086. _this.VIGNETTE = false;
  90087. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  90088. _this.VIGNETTEBLENDMODEOPAQUE = false;
  90089. _this.TONEMAPPING = false;
  90090. _this.CONTRAST = false;
  90091. _this.COLORCURVES = false;
  90092. _this.COLORGRADING = false;
  90093. _this.COLORGRADING3D = false;
  90094. _this.SAMPLER3DGREENDEPTH = false;
  90095. _this.SAMPLER3DBGRMAP = false;
  90096. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  90097. _this.EXPOSURE = false;
  90098. _this.GRAIN = false;
  90099. // Reflection.
  90100. _this.REFLECTION = false;
  90101. _this.REFLECTIONMAP_3D = false;
  90102. _this.REFLECTIONMAP_SPHERICAL = false;
  90103. _this.REFLECTIONMAP_PLANAR = false;
  90104. _this.REFLECTIONMAP_CUBIC = false;
  90105. _this.REFLECTIONMAP_PROJECTION = false;
  90106. _this.REFLECTIONMAP_SKYBOX = false;
  90107. _this.REFLECTIONMAP_EXPLICIT = false;
  90108. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  90109. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  90110. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  90111. _this.INVERTCUBICMAP = false;
  90112. _this.REFLECTIONMAP_OPPOSITEZ = false;
  90113. _this.LODINREFLECTIONALPHA = false;
  90114. _this.GAMMAREFLECTION = false;
  90115. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  90116. // Default BJS.
  90117. _this.MAINUV1 = false;
  90118. _this.MAINUV2 = false;
  90119. _this.UV1 = false;
  90120. _this.UV2 = false;
  90121. _this.CLIPPLANE = false;
  90122. _this.POINTSIZE = false;
  90123. _this.FOG = false;
  90124. _this.NORMAL = false;
  90125. _this.NUM_BONE_INFLUENCERS = 0;
  90126. _this.BonesPerMesh = 0;
  90127. _this.INSTANCES = false;
  90128. _this.SHADOWFLOAT = false;
  90129. _this.rebuild();
  90130. return _this;
  90131. }
  90132. return BackgroundMaterialDefines;
  90133. }(BABYLON.MaterialDefines));
  90134. /**
  90135. * Background material used to create an efficient environement around your scene.
  90136. */
  90137. var BackgroundMaterial = /** @class */ (function (_super) {
  90138. __extends(BackgroundMaterial, _super);
  90139. /**
  90140. * Instantiates a Background Material in the given scene
  90141. * @param name The friendly name of the material
  90142. * @param scene The scene to add the material to
  90143. */
  90144. function BackgroundMaterial(name, scene) {
  90145. var _this = _super.call(this, name, scene) || this;
  90146. /**
  90147. * Key light Color (multiply against the R channel of the environement texture)
  90148. */
  90149. _this.primaryColor = BABYLON.Color3.White();
  90150. /**
  90151. * Key light Level (allowing HDR output of the background)
  90152. */
  90153. _this.primaryLevel = 1;
  90154. /**
  90155. * Secondary light Color (multiply against the G channel of the environement texture)
  90156. */
  90157. _this.secondaryColor = BABYLON.Color3.Gray();
  90158. /**
  90159. * Secondary light Level (allowing HDR output of the background)
  90160. */
  90161. _this.secondaryLevel = 1;
  90162. /**
  90163. * Tertiary light Color (multiply against the B channel of the environement texture)
  90164. */
  90165. _this.tertiaryColor = BABYLON.Color3.Black();
  90166. /**
  90167. * Tertiary light Level (allowing HDR output of the background)
  90168. */
  90169. _this.tertiaryLevel = 1;
  90170. /**
  90171. * Reflection Texture used in the material.
  90172. * Should be author in a specific way for the best result (refer to the documentation).
  90173. */
  90174. _this.reflectionTexture = null;
  90175. /**
  90176. * Reflection Texture level of blur.
  90177. *
  90178. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  90179. * texture twice.
  90180. */
  90181. _this.reflectionBlur = 0;
  90182. /**
  90183. * Diffuse Texture used in the material.
  90184. * Should be author in a specific way for the best result (refer to the documentation).
  90185. */
  90186. _this.diffuseTexture = null;
  90187. _this._shadowLights = null;
  90188. /**
  90189. * Specify the list of lights casting shadow on the material.
  90190. * All scene shadow lights will be included if null.
  90191. */
  90192. _this.shadowLights = null;
  90193. /**
  90194. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  90195. * soft lighting on the background.
  90196. */
  90197. _this.shadowBlurScale = 1;
  90198. /**
  90199. * Helps adjusting the shadow to a softer level if required.
  90200. * 0 means black shadows and 1 means no shadows.
  90201. */
  90202. _this.shadowLevel = 0;
  90203. /**
  90204. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  90205. * It is usually zero but might be interesting to modify according to your setup.
  90206. */
  90207. _this.sceneCenter = BABYLON.Vector3.Zero();
  90208. /**
  90209. * This helps specifying that the material is falling off to the sky box at grazing angle.
  90210. * This helps ensuring a nice transition when the camera goes under the ground.
  90211. */
  90212. _this.opacityFresnel = true;
  90213. /**
  90214. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  90215. * This helps adding a mirror texture on the ground.
  90216. */
  90217. _this.reflectionFresnel = false;
  90218. /**
  90219. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  90220. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  90221. */
  90222. _this.reflectionFalloffDistance = 0.0;
  90223. /**
  90224. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  90225. */
  90226. _this.reflectionAmount = 1.0;
  90227. /**
  90228. * This specifies the weight of the reflection at grazing angle.
  90229. */
  90230. _this.reflectionReflectance0 = 0.05;
  90231. /**
  90232. * This specifies the weight of the reflection at a perpendicular point of view.
  90233. */
  90234. _this.reflectionReflectance90 = 0.5;
  90235. /**
  90236. * Helps to directly use the maps channels instead of their level.
  90237. */
  90238. _this.useRGBColor = true;
  90239. /**
  90240. * This helps reducing the banding effect that could occur on the background.
  90241. */
  90242. _this.enableNoise = false;
  90243. _this._fovMultiplier = 1.0;
  90244. /**
  90245. * Enable the FOV adjustment feature controlled by fovMultiplier.
  90246. * @type {boolean}
  90247. */
  90248. _this.useEquirectangularFOV = false;
  90249. _this._maxSimultaneousLights = 4;
  90250. /**
  90251. * Number of Simultaneous lights allowed on the material.
  90252. */
  90253. _this.maxSimultaneousLights = 4;
  90254. /**
  90255. * Keep track of the image processing observer to allow dispose and replace.
  90256. */
  90257. _this._imageProcessingObserver = null;
  90258. /**
  90259. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  90260. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  90261. */
  90262. _this.switchToBGR = false;
  90263. // Temp values kept as cache in the material.
  90264. _this._renderTargets = new BABYLON.SmartArray(16);
  90265. _this._reflectionControls = BABYLON.Vector4.Zero();
  90266. // Setup the default processing configuration to the scene.
  90267. _this._attachImageProcessingConfiguration(null);
  90268. _this.getRenderTargetTextures = function () {
  90269. _this._renderTargets.reset();
  90270. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  90271. _this._renderTargets.push(_this._diffuseTexture);
  90272. }
  90273. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  90274. _this._renderTargets.push(_this._reflectionTexture);
  90275. }
  90276. return _this._renderTargets;
  90277. };
  90278. return _this;
  90279. }
  90280. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  90281. /**
  90282. * Sets the reflection reflectance fresnel values according to the default standard
  90283. * empirically know to work well :-)
  90284. */
  90285. set: function (value) {
  90286. var reflectionWeight = value;
  90287. if (reflectionWeight < 0.5) {
  90288. reflectionWeight = reflectionWeight * 2.0;
  90289. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  90290. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  90291. }
  90292. else {
  90293. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  90294. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  90295. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  90296. }
  90297. },
  90298. enumerable: true,
  90299. configurable: true
  90300. });
  90301. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  90302. /**
  90303. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  90304. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  90305. * Recommended to be keep at 1.0 except for special cases.
  90306. */
  90307. get: function () {
  90308. return this._fovMultiplier;
  90309. },
  90310. set: function (value) {
  90311. if (isNaN(value)) {
  90312. value = 1.0;
  90313. }
  90314. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  90315. },
  90316. enumerable: true,
  90317. configurable: true
  90318. });
  90319. /**
  90320. * Attaches a new image processing configuration to the PBR Material.
  90321. * @param configuration (if null the scene configuration will be use)
  90322. */
  90323. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  90324. var _this = this;
  90325. if (configuration === this._imageProcessingConfiguration) {
  90326. return;
  90327. }
  90328. // Detaches observer.
  90329. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90330. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90331. }
  90332. // Pick the scene configuration if needed.
  90333. if (!configuration) {
  90334. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  90335. }
  90336. else {
  90337. this._imageProcessingConfiguration = configuration;
  90338. }
  90339. // Attaches observer.
  90340. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  90341. _this._markAllSubMeshesAsImageProcessingDirty();
  90342. });
  90343. };
  90344. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  90345. /**
  90346. * Gets the image processing configuration used either in this material.
  90347. */
  90348. get: function () {
  90349. return this._imageProcessingConfiguration;
  90350. },
  90351. /**
  90352. * Sets the Default image processing configuration used either in the this material.
  90353. *
  90354. * If sets to null, the scene one is in use.
  90355. */
  90356. set: function (value) {
  90357. this._attachImageProcessingConfiguration(value);
  90358. // Ensure the effect will be rebuilt.
  90359. this._markAllSubMeshesAsTexturesDirty();
  90360. },
  90361. enumerable: true,
  90362. configurable: true
  90363. });
  90364. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  90365. /**
  90366. * Gets wether the color curves effect is enabled.
  90367. */
  90368. get: function () {
  90369. return this.imageProcessingConfiguration.colorCurvesEnabled;
  90370. },
  90371. /**
  90372. * Sets wether the color curves effect is enabled.
  90373. */
  90374. set: function (value) {
  90375. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  90376. },
  90377. enumerable: true,
  90378. configurable: true
  90379. });
  90380. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  90381. /**
  90382. * Gets wether the color grading effect is enabled.
  90383. */
  90384. get: function () {
  90385. return this.imageProcessingConfiguration.colorGradingEnabled;
  90386. },
  90387. /**
  90388. * Gets wether the color grading effect is enabled.
  90389. */
  90390. set: function (value) {
  90391. this.imageProcessingConfiguration.colorGradingEnabled = value;
  90392. },
  90393. enumerable: true,
  90394. configurable: true
  90395. });
  90396. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  90397. /**
  90398. * Gets wether tonemapping is enabled or not.
  90399. */
  90400. get: function () {
  90401. return this._imageProcessingConfiguration.toneMappingEnabled;
  90402. },
  90403. /**
  90404. * Sets wether tonemapping is enabled or not
  90405. */
  90406. set: function (value) {
  90407. this._imageProcessingConfiguration.toneMappingEnabled = value;
  90408. },
  90409. enumerable: true,
  90410. configurable: true
  90411. });
  90412. ;
  90413. ;
  90414. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  90415. /**
  90416. * The camera exposure used on this material.
  90417. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  90418. * This corresponds to a photographic exposure.
  90419. */
  90420. get: function () {
  90421. return this._imageProcessingConfiguration.exposure;
  90422. },
  90423. /**
  90424. * The camera exposure used on this material.
  90425. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  90426. * This corresponds to a photographic exposure.
  90427. */
  90428. set: function (value) {
  90429. this._imageProcessingConfiguration.exposure = value;
  90430. },
  90431. enumerable: true,
  90432. configurable: true
  90433. });
  90434. ;
  90435. ;
  90436. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  90437. /**
  90438. * Gets The camera contrast used on this material.
  90439. */
  90440. get: function () {
  90441. return this._imageProcessingConfiguration.contrast;
  90442. },
  90443. /**
  90444. * Sets The camera contrast used on this material.
  90445. */
  90446. set: function (value) {
  90447. this._imageProcessingConfiguration.contrast = value;
  90448. },
  90449. enumerable: true,
  90450. configurable: true
  90451. });
  90452. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  90453. /**
  90454. * Gets the Color Grading 2D Lookup Texture.
  90455. */
  90456. get: function () {
  90457. return this._imageProcessingConfiguration.colorGradingTexture;
  90458. },
  90459. /**
  90460. * Sets the Color Grading 2D Lookup Texture.
  90461. */
  90462. set: function (value) {
  90463. this.imageProcessingConfiguration.colorGradingTexture = value;
  90464. },
  90465. enumerable: true,
  90466. configurable: true
  90467. });
  90468. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  90469. /**
  90470. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  90471. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  90472. * 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;
  90473. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  90474. */
  90475. get: function () {
  90476. return this.imageProcessingConfiguration.colorCurves;
  90477. },
  90478. /**
  90479. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  90480. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  90481. * 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;
  90482. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  90483. */
  90484. set: function (value) {
  90485. this.imageProcessingConfiguration.colorCurves = value;
  90486. },
  90487. enumerable: true,
  90488. configurable: true
  90489. });
  90490. /**
  90491. * The entire material has been created in order to prevent overdraw.
  90492. * @returns false
  90493. */
  90494. BackgroundMaterial.prototype.needAlphaTesting = function () {
  90495. return true;
  90496. };
  90497. /**
  90498. * The entire material has been created in order to prevent overdraw.
  90499. * @returns true if blending is enable
  90500. */
  90501. BackgroundMaterial.prototype.needAlphaBlending = function () {
  90502. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  90503. };
  90504. /**
  90505. * Checks wether the material is ready to be rendered for a given mesh.
  90506. * @param mesh The mesh to render
  90507. * @param subMesh The submesh to check against
  90508. * @param useInstances Specify wether or not the material is used with instances
  90509. * @returns true if all the dependencies are ready (Textures, Effects...)
  90510. */
  90511. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  90512. var _this = this;
  90513. if (useInstances === void 0) { useInstances = false; }
  90514. if (subMesh.effect && this.isFrozen) {
  90515. if (this._wasPreviouslyReady) {
  90516. return true;
  90517. }
  90518. }
  90519. if (!subMesh._materialDefines) {
  90520. subMesh._materialDefines = new BackgroundMaterialDefines();
  90521. }
  90522. var scene = this.getScene();
  90523. var defines = subMesh._materialDefines;
  90524. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  90525. if (defines._renderId === scene.getRenderId()) {
  90526. return true;
  90527. }
  90528. }
  90529. var engine = scene.getEngine();
  90530. // Lights
  90531. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  90532. defines._needNormals = true;
  90533. // Textures
  90534. if (defines._areTexturesDirty) {
  90535. defines._needUVs = false;
  90536. if (scene.texturesEnabled) {
  90537. if (scene.getEngine().getCaps().textureLOD) {
  90538. defines.TEXTURELODSUPPORT = true;
  90539. }
  90540. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90541. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  90542. return false;
  90543. }
  90544. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  90545. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  90546. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  90547. defines.OPACITYFRESNEL = this._opacityFresnel;
  90548. }
  90549. else {
  90550. defines.DIFFUSE = false;
  90551. defines.DIFFUSEHASALPHA = false;
  90552. defines.GAMMADIFFUSE = false;
  90553. defines.OPACITYFRESNEL = false;
  90554. }
  90555. var reflectionTexture = this._reflectionTexture;
  90556. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90557. if (!reflectionTexture.isReadyOrNotBlocking()) {
  90558. return false;
  90559. }
  90560. defines.REFLECTION = true;
  90561. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  90562. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  90563. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  90564. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  90565. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  90566. defines.REFLECTIONBGR = this.switchToBGR;
  90567. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  90568. defines.INVERTCUBICMAP = true;
  90569. }
  90570. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  90571. switch (reflectionTexture.coordinatesMode) {
  90572. case BABYLON.Texture.CUBIC_MODE:
  90573. case BABYLON.Texture.INVCUBIC_MODE:
  90574. defines.REFLECTIONMAP_CUBIC = true;
  90575. break;
  90576. case BABYLON.Texture.EXPLICIT_MODE:
  90577. defines.REFLECTIONMAP_EXPLICIT = true;
  90578. break;
  90579. case BABYLON.Texture.PLANAR_MODE:
  90580. defines.REFLECTIONMAP_PLANAR = true;
  90581. break;
  90582. case BABYLON.Texture.PROJECTION_MODE:
  90583. defines.REFLECTIONMAP_PROJECTION = true;
  90584. break;
  90585. case BABYLON.Texture.SKYBOX_MODE:
  90586. defines.REFLECTIONMAP_SKYBOX = true;
  90587. break;
  90588. case BABYLON.Texture.SPHERICAL_MODE:
  90589. defines.REFLECTIONMAP_SPHERICAL = true;
  90590. break;
  90591. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  90592. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  90593. break;
  90594. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  90595. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  90596. break;
  90597. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  90598. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  90599. break;
  90600. }
  90601. if (this.reflectionFresnel) {
  90602. defines.REFLECTIONFRESNEL = true;
  90603. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  90604. this._reflectionControls.x = this.reflectionAmount;
  90605. this._reflectionControls.y = this.reflectionReflectance0;
  90606. this._reflectionControls.z = this.reflectionReflectance90;
  90607. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  90608. }
  90609. else {
  90610. defines.REFLECTIONFRESNEL = false;
  90611. defines.REFLECTIONFALLOFF = false;
  90612. }
  90613. }
  90614. else {
  90615. defines.REFLECTION = false;
  90616. defines.REFLECTIONFALLOFF = false;
  90617. defines.REFLECTIONBLUR = false;
  90618. defines.REFLECTIONMAP_3D = false;
  90619. defines.REFLECTIONMAP_SPHERICAL = false;
  90620. defines.REFLECTIONMAP_PLANAR = false;
  90621. defines.REFLECTIONMAP_CUBIC = false;
  90622. defines.REFLECTIONMAP_PROJECTION = false;
  90623. defines.REFLECTIONMAP_SKYBOX = false;
  90624. defines.REFLECTIONMAP_EXPLICIT = false;
  90625. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  90626. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  90627. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  90628. defines.INVERTCUBICMAP = false;
  90629. defines.REFLECTIONMAP_OPPOSITEZ = false;
  90630. defines.LODINREFLECTIONALPHA = false;
  90631. defines.GAMMAREFLECTION = false;
  90632. }
  90633. }
  90634. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  90635. defines.USERGBCOLOR = this._useRGBColor;
  90636. defines.NOISE = this._enableNoise;
  90637. }
  90638. if (defines._areImageProcessingDirty) {
  90639. if (!this._imageProcessingConfiguration.isReady()) {
  90640. return false;
  90641. }
  90642. this._imageProcessingConfiguration.prepareDefines(defines);
  90643. }
  90644. // Misc.
  90645. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  90646. // Values that need to be evaluated on every frame
  90647. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  90648. // Attribs
  90649. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  90650. if (mesh) {
  90651. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  90652. mesh.createNormals(true);
  90653. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  90654. }
  90655. }
  90656. }
  90657. // Get correct effect
  90658. if (defines.isDirty) {
  90659. defines.markAsProcessed();
  90660. scene.resetCachedMaterial();
  90661. // Fallbacks
  90662. var fallbacks = new BABYLON.EffectFallbacks();
  90663. if (defines.FOG) {
  90664. fallbacks.addFallback(0, "FOG");
  90665. }
  90666. if (defines.POINTSIZE) {
  90667. fallbacks.addFallback(1, "POINTSIZE");
  90668. }
  90669. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  90670. if (defines.NUM_BONE_INFLUENCERS > 0) {
  90671. fallbacks.addCPUSkinningFallback(0, mesh);
  90672. }
  90673. //Attributes
  90674. var attribs = [BABYLON.VertexBuffer.PositionKind];
  90675. if (defines.NORMAL) {
  90676. attribs.push(BABYLON.VertexBuffer.NormalKind);
  90677. }
  90678. if (defines.UV1) {
  90679. attribs.push(BABYLON.VertexBuffer.UVKind);
  90680. }
  90681. if (defines.UV2) {
  90682. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90683. }
  90684. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  90685. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  90686. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  90687. "vFogInfos", "vFogColor", "pointSize",
  90688. "vClipPlane", "mBones",
  90689. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  90690. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  90691. "shadowLevel", "alpha",
  90692. "vBackgroundCenter", "vReflectionControl",
  90693. "vDiffuseInfos", "diffuseMatrix",
  90694. ];
  90695. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  90696. var uniformBuffers = ["Material", "Scene"];
  90697. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  90698. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  90699. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  90700. uniformsNames: uniforms,
  90701. uniformBuffersNames: uniformBuffers,
  90702. samplers: samplers,
  90703. defines: defines,
  90704. maxSimultaneousLights: this._maxSimultaneousLights
  90705. });
  90706. var onCompiled = function (effect) {
  90707. if (_this.onCompiled) {
  90708. _this.onCompiled(effect);
  90709. }
  90710. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  90711. };
  90712. var join = defines.toString();
  90713. subMesh.setEffect(scene.getEngine().createEffect("background", {
  90714. attributes: attribs,
  90715. uniformsNames: uniforms,
  90716. uniformBuffersNames: uniformBuffers,
  90717. samplers: samplers,
  90718. defines: join,
  90719. fallbacks: fallbacks,
  90720. onCompiled: onCompiled,
  90721. onError: this.onError,
  90722. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  90723. }, engine), defines);
  90724. this.buildUniformLayout();
  90725. }
  90726. if (!subMesh.effect || !subMesh.effect.isReady()) {
  90727. return false;
  90728. }
  90729. defines._renderId = scene.getRenderId();
  90730. this._wasPreviouslyReady = true;
  90731. return true;
  90732. };
  90733. /**
  90734. * Build the uniform buffer used in the material.
  90735. */
  90736. BackgroundMaterial.prototype.buildUniformLayout = function () {
  90737. // Order is important !
  90738. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  90739. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  90740. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  90741. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  90742. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  90743. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  90744. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  90745. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  90746. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  90747. this._uniformBuffer.addUniform("pointSize", 1);
  90748. this._uniformBuffer.addUniform("shadowLevel", 1);
  90749. this._uniformBuffer.addUniform("alpha", 1);
  90750. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  90751. this._uniformBuffer.addUniform("vReflectionControl", 4);
  90752. this._uniformBuffer.create();
  90753. };
  90754. /**
  90755. * Unbind the material.
  90756. */
  90757. BackgroundMaterial.prototype.unbind = function () {
  90758. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  90759. this._uniformBuffer.setTexture("diffuseSampler", null);
  90760. }
  90761. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  90762. this._uniformBuffer.setTexture("reflectionSampler", null);
  90763. }
  90764. _super.prototype.unbind.call(this);
  90765. };
  90766. /**
  90767. * Bind only the world matrix to the material.
  90768. * @param world The world matrix to bind.
  90769. */
  90770. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  90771. this._activeEffect.setMatrix("world", world);
  90772. };
  90773. /**
  90774. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  90775. * @param world The world matrix to bind.
  90776. * @param subMesh The submesh to bind for.
  90777. */
  90778. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  90779. var scene = this.getScene();
  90780. var defines = subMesh._materialDefines;
  90781. if (!defines) {
  90782. return;
  90783. }
  90784. var effect = subMesh.effect;
  90785. if (!effect) {
  90786. return;
  90787. }
  90788. this._activeEffect = effect;
  90789. // Matrices
  90790. this.bindOnlyWorldMatrix(world);
  90791. // Bones
  90792. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  90793. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  90794. if (mustRebind) {
  90795. this._uniformBuffer.bindToEffect(effect, "Material");
  90796. this.bindViewProjection(effect);
  90797. var reflectionTexture = this._reflectionTexture;
  90798. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  90799. // Texture uniforms
  90800. if (scene.texturesEnabled) {
  90801. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90802. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  90803. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  90804. }
  90805. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90806. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  90807. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  90808. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  90809. }
  90810. }
  90811. if (this.shadowLevel > 0) {
  90812. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  90813. }
  90814. this._uniformBuffer.updateFloat("alpha", this.alpha);
  90815. // Point size
  90816. if (this.pointsCloud) {
  90817. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  90818. }
  90819. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  90820. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  90821. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  90822. }
  90823. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  90824. // Textures
  90825. if (scene.texturesEnabled) {
  90826. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90827. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  90828. }
  90829. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90830. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  90831. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  90832. }
  90833. else if (!defines.REFLECTIONBLUR) {
  90834. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  90835. }
  90836. else {
  90837. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  90838. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  90839. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  90840. }
  90841. if (defines.REFLECTIONFRESNEL) {
  90842. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  90843. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  90844. }
  90845. }
  90846. }
  90847. // Clip plane
  90848. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  90849. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  90850. }
  90851. if (mustRebind || !this.isFrozen) {
  90852. if (scene.lightsEnabled) {
  90853. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  90854. }
  90855. // View
  90856. this.bindView(effect);
  90857. // Fog
  90858. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  90859. // image processing
  90860. this._imageProcessingConfiguration.bind(this._activeEffect);
  90861. }
  90862. this._uniformBuffer.update();
  90863. this._afterBind(mesh);
  90864. };
  90865. /**
  90866. * Dispose the material.
  90867. * @param forceDisposeEffect Force disposal of the associated effect.
  90868. * @param forceDisposeTextures Force disposal of the associated textures.
  90869. */
  90870. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  90871. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  90872. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  90873. if (forceDisposeTextures) {
  90874. if (this.diffuseTexture) {
  90875. this.diffuseTexture.dispose();
  90876. }
  90877. if (this.reflectionTexture) {
  90878. this.reflectionTexture.dispose();
  90879. }
  90880. }
  90881. this._renderTargets.dispose();
  90882. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90883. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90884. }
  90885. _super.prototype.dispose.call(this, forceDisposeEffect);
  90886. };
  90887. /**
  90888. * Clones the material.
  90889. * @param name The cloned name.
  90890. * @returns The cloned material.
  90891. */
  90892. BackgroundMaterial.prototype.clone = function (name) {
  90893. var _this = this;
  90894. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  90895. };
  90896. /**
  90897. * Serializes the current material to its JSON representation.
  90898. * @returns The JSON representation.
  90899. */
  90900. BackgroundMaterial.prototype.serialize = function () {
  90901. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  90902. serializationObject.customType = "BABYLON.BackgroundMaterial";
  90903. return serializationObject;
  90904. };
  90905. /**
  90906. * Gets the class name of the material
  90907. * @returns "BackgroundMaterial"
  90908. */
  90909. BackgroundMaterial.prototype.getClassName = function () {
  90910. return "BackgroundMaterial";
  90911. };
  90912. /**
  90913. * Parse a JSON input to create back a background material.
  90914. * @param source The JSON data to parse
  90915. * @param scene The scene to create the parsed material in
  90916. * @param rootUrl The root url of the assets the material depends upon
  90917. * @returns the instantiated BackgroundMaterial.
  90918. */
  90919. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  90920. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  90921. };
  90922. /**
  90923. * Standard reflectance value at parallel view angle.
  90924. */
  90925. BackgroundMaterial.StandardReflectance0 = 0.05;
  90926. /**
  90927. * Standard reflectance value at grazing angle.
  90928. */
  90929. BackgroundMaterial.StandardReflectance90 = 0.5;
  90930. __decorate([
  90931. BABYLON.serializeAsColor3()
  90932. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  90933. __decorate([
  90934. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90935. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  90936. __decorate([
  90937. BABYLON.serialize()
  90938. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  90939. __decorate([
  90940. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90941. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  90942. __decorate([
  90943. BABYLON.serializeAsColor3()
  90944. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  90945. __decorate([
  90946. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90947. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  90948. __decorate([
  90949. BABYLON.serialize()
  90950. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  90951. __decorate([
  90952. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90953. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  90954. __decorate([
  90955. BABYLON.serializeAsColor3()
  90956. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  90957. __decorate([
  90958. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90959. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  90960. __decorate([
  90961. BABYLON.serialize()
  90962. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  90963. __decorate([
  90964. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90965. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  90966. __decorate([
  90967. BABYLON.serializeAsTexture()
  90968. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  90969. __decorate([
  90970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90971. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  90972. __decorate([
  90973. BABYLON.serialize()
  90974. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  90975. __decorate([
  90976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90977. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  90978. __decorate([
  90979. BABYLON.serializeAsTexture()
  90980. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  90981. __decorate([
  90982. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90983. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  90984. __decorate([
  90985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90986. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  90987. __decorate([
  90988. BABYLON.serialize()
  90989. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  90990. __decorate([
  90991. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90992. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  90993. __decorate([
  90994. BABYLON.serialize()
  90995. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  90996. __decorate([
  90997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90998. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  90999. __decorate([
  91000. BABYLON.serializeAsVector3()
  91001. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  91002. __decorate([
  91003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91004. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  91005. __decorate([
  91006. BABYLON.serialize()
  91007. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  91008. __decorate([
  91009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91010. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  91011. __decorate([
  91012. BABYLON.serialize()
  91013. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  91014. __decorate([
  91015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91016. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  91017. __decorate([
  91018. BABYLON.serialize()
  91019. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  91020. __decorate([
  91021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91022. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  91023. __decorate([
  91024. BABYLON.serialize()
  91025. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  91026. __decorate([
  91027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91028. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  91029. __decorate([
  91030. BABYLON.serialize()
  91031. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  91032. __decorate([
  91033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91034. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  91035. __decorate([
  91036. BABYLON.serialize()
  91037. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  91038. __decorate([
  91039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91040. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  91041. __decorate([
  91042. BABYLON.serialize()
  91043. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  91044. __decorate([
  91045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91046. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  91047. __decorate([
  91048. BABYLON.serialize()
  91049. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  91050. __decorate([
  91051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91052. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  91053. __decorate([
  91054. BABYLON.serialize()
  91055. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  91056. __decorate([
  91057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91058. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  91059. __decorate([
  91060. BABYLON.serializeAsImageProcessingConfiguration()
  91061. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  91062. return BackgroundMaterial;
  91063. }(BABYLON.PushMaterial));
  91064. BABYLON.BackgroundMaterial = BackgroundMaterial;
  91065. })(BABYLON || (BABYLON = {}));
  91066. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  91067. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91068. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91069. s = arguments[i];
  91070. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91071. t[p] = s[p];
  91072. }
  91073. return t;
  91074. };
  91075. var BABYLON;
  91076. (function (BABYLON) {
  91077. /**
  91078. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  91079. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  91080. * It also helps with the default setup of your imageProcessing configuration.
  91081. */
  91082. var EnvironmentHelper = /** @class */ (function () {
  91083. /**
  91084. * constructor
  91085. * @param options
  91086. * @param scene The scene to add the material to
  91087. */
  91088. function EnvironmentHelper(options, scene) {
  91089. var _this = this;
  91090. this._errorHandler = function (message, exception) {
  91091. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  91092. };
  91093. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  91094. this._scene = scene;
  91095. this.onErrorObservable = new BABYLON.Observable();
  91096. this._setupBackground();
  91097. this._setupImageProcessing();
  91098. }
  91099. /**
  91100. * Creates the default options for the helper.
  91101. */
  91102. EnvironmentHelper._getDefaultOptions = function () {
  91103. return {
  91104. createGround: true,
  91105. groundSize: 15,
  91106. groundTexture: this._groundTextureCDNUrl,
  91107. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  91108. groundOpacity: 0.9,
  91109. enableGroundShadow: true,
  91110. groundShadowLevel: 0.5,
  91111. enableGroundMirror: false,
  91112. groundMirrorSizeRatio: 0.3,
  91113. groundMirrorBlurKernel: 64,
  91114. groundMirrorAmount: 1,
  91115. groundMirrorFresnelWeight: 1,
  91116. groundMirrorFallOffDistance: 0,
  91117. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  91118. groundYBias: 0.00001,
  91119. createSkybox: true,
  91120. skyboxSize: 20,
  91121. skyboxTexture: this._skyboxTextureCDNUrl,
  91122. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  91123. backgroundYRotation: 0,
  91124. sizeAuto: true,
  91125. rootPosition: BABYLON.Vector3.Zero(),
  91126. setupImageProcessing: true,
  91127. environmentTexture: this._environmentTextureCDNUrl,
  91128. cameraExposure: 0.8,
  91129. cameraContrast: 1.2,
  91130. toneMappingEnabled: true,
  91131. };
  91132. };
  91133. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  91134. /**
  91135. * Gets the root mesh created by the helper.
  91136. */
  91137. get: function () {
  91138. return this._rootMesh;
  91139. },
  91140. enumerable: true,
  91141. configurable: true
  91142. });
  91143. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  91144. /**
  91145. * Gets the skybox created by the helper.
  91146. */
  91147. get: function () {
  91148. return this._skybox;
  91149. },
  91150. enumerable: true,
  91151. configurable: true
  91152. });
  91153. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  91154. /**
  91155. * Gets the skybox texture created by the helper.
  91156. */
  91157. get: function () {
  91158. return this._skyboxTexture;
  91159. },
  91160. enumerable: true,
  91161. configurable: true
  91162. });
  91163. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  91164. /**
  91165. * Gets the skybox material created by the helper.
  91166. */
  91167. get: function () {
  91168. return this._skyboxMaterial;
  91169. },
  91170. enumerable: true,
  91171. configurable: true
  91172. });
  91173. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  91174. /**
  91175. * Gets the ground mesh created by the helper.
  91176. */
  91177. get: function () {
  91178. return this._ground;
  91179. },
  91180. enumerable: true,
  91181. configurable: true
  91182. });
  91183. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  91184. /**
  91185. * Gets the ground texture created by the helper.
  91186. */
  91187. get: function () {
  91188. return this._groundTexture;
  91189. },
  91190. enumerable: true,
  91191. configurable: true
  91192. });
  91193. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  91194. /**
  91195. * Gets the ground mirror created by the helper.
  91196. */
  91197. get: function () {
  91198. return this._groundMirror;
  91199. },
  91200. enumerable: true,
  91201. configurable: true
  91202. });
  91203. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  91204. /**
  91205. * Gets the ground mirror render list to helps pushing the meshes
  91206. * you wish in the ground reflection.
  91207. */
  91208. get: function () {
  91209. if (this._groundMirror) {
  91210. return this._groundMirror.renderList;
  91211. }
  91212. return null;
  91213. },
  91214. enumerable: true,
  91215. configurable: true
  91216. });
  91217. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  91218. /**
  91219. * Gets the ground material created by the helper.
  91220. */
  91221. get: function () {
  91222. return this._groundMaterial;
  91223. },
  91224. enumerable: true,
  91225. configurable: true
  91226. });
  91227. /**
  91228. * Updates the background according to the new options
  91229. * @param options
  91230. */
  91231. EnvironmentHelper.prototype.updateOptions = function (options) {
  91232. var newOptions = __assign({}, this._options, options);
  91233. if (this._ground && !newOptions.createGround) {
  91234. this._ground.dispose();
  91235. this._ground = null;
  91236. }
  91237. if (this._groundMaterial && !newOptions.createGround) {
  91238. this._groundMaterial.dispose();
  91239. this._groundMaterial = null;
  91240. }
  91241. if (this._groundTexture) {
  91242. if (this._options.groundTexture != newOptions.groundTexture) {
  91243. this._groundTexture.dispose();
  91244. this._groundTexture = null;
  91245. }
  91246. }
  91247. if (this._skybox && !newOptions.createSkybox) {
  91248. this._skybox.dispose();
  91249. this._skybox = null;
  91250. }
  91251. if (this._skyboxMaterial && !newOptions.createSkybox) {
  91252. this._skyboxMaterial.dispose();
  91253. this._skyboxMaterial = null;
  91254. }
  91255. if (this._skyboxTexture) {
  91256. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  91257. this._skyboxTexture.dispose();
  91258. this._skyboxTexture = null;
  91259. }
  91260. }
  91261. if (this._groundMirror && !newOptions.enableGroundMirror) {
  91262. this._groundMirror.dispose();
  91263. this._groundMirror = null;
  91264. }
  91265. if (this._scene.environmentTexture) {
  91266. if (this._options.environmentTexture != newOptions.environmentTexture) {
  91267. this._scene.environmentTexture.dispose();
  91268. }
  91269. }
  91270. this._options = newOptions;
  91271. this._setupBackground();
  91272. this._setupImageProcessing();
  91273. };
  91274. /**
  91275. * Sets the primary color of all the available elements.
  91276. * @param color
  91277. */
  91278. EnvironmentHelper.prototype.setMainColor = function (color) {
  91279. if (this.groundMaterial) {
  91280. this.groundMaterial.primaryColor = color;
  91281. }
  91282. if (this.skyboxMaterial) {
  91283. this.skyboxMaterial.primaryColor = color;
  91284. }
  91285. if (this.groundMirror) {
  91286. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  91287. }
  91288. };
  91289. /**
  91290. * Setup the image processing according to the specified options.
  91291. */
  91292. EnvironmentHelper.prototype._setupImageProcessing = function () {
  91293. if (this._options.setupImageProcessing) {
  91294. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  91295. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  91296. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  91297. this._setupEnvironmentTexture();
  91298. }
  91299. };
  91300. /**
  91301. * Setup the environment texture according to the specified options.
  91302. */
  91303. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  91304. if (this._scene.environmentTexture) {
  91305. return;
  91306. }
  91307. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  91308. this._scene.environmentTexture = this._options.environmentTexture;
  91309. return;
  91310. }
  91311. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  91312. this._scene.environmentTexture = environmentTexture;
  91313. };
  91314. /**
  91315. * Setup the background according to the specified options.
  91316. */
  91317. EnvironmentHelper.prototype._setupBackground = function () {
  91318. if (!this._rootMesh) {
  91319. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  91320. }
  91321. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  91322. var sceneSize = this._getSceneSize();
  91323. if (this._options.createGround) {
  91324. this._setupGround(sceneSize);
  91325. this._setupGroundMaterial();
  91326. this._setupGroundDiffuseTexture();
  91327. if (this._options.enableGroundMirror) {
  91328. this._setupGroundMirrorTexture(sceneSize);
  91329. }
  91330. this._setupMirrorInGroundMaterial();
  91331. }
  91332. if (this._options.createSkybox) {
  91333. this._setupSkybox(sceneSize);
  91334. this._setupSkyboxMaterial();
  91335. this._setupSkyboxReflectionTexture();
  91336. }
  91337. this._rootMesh.position.x = sceneSize.rootPosition.x;
  91338. this._rootMesh.position.z = sceneSize.rootPosition.z;
  91339. this._rootMesh.position.y = sceneSize.rootPosition.y;
  91340. };
  91341. /**
  91342. * Get the scene sizes according to the setup.
  91343. */
  91344. EnvironmentHelper.prototype._getSceneSize = function () {
  91345. var _this = this;
  91346. var groundSize = this._options.groundSize;
  91347. var skyboxSize = this._options.skyboxSize;
  91348. var rootPosition = this._options.rootPosition;
  91349. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  91350. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  91351. }
  91352. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  91353. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  91354. });
  91355. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  91356. if (this._options.sizeAuto) {
  91357. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  91358. this._scene.activeCamera.upperRadiusLimit) {
  91359. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  91360. skyboxSize = groundSize;
  91361. }
  91362. var sceneDiagonalLenght = sceneDiagonal.length();
  91363. if (sceneDiagonalLenght > groundSize) {
  91364. groundSize = sceneDiagonalLenght * 2;
  91365. skyboxSize = groundSize;
  91366. }
  91367. // 10 % bigger.
  91368. groundSize *= 1.1;
  91369. skyboxSize *= 1.5;
  91370. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  91371. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  91372. }
  91373. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  91374. };
  91375. /**
  91376. * Setup the ground according to the specified options.
  91377. */
  91378. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  91379. var _this = this;
  91380. if (!this._ground) {
  91381. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  91382. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  91383. this._ground.parent = this._rootMesh;
  91384. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  91385. }
  91386. this._ground.receiveShadows = this._options.enableGroundShadow;
  91387. };
  91388. /**
  91389. * Setup the ground material according to the specified options.
  91390. */
  91391. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  91392. if (!this._groundMaterial) {
  91393. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  91394. }
  91395. this._groundMaterial.alpha = this._options.groundOpacity;
  91396. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  91397. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  91398. this._groundMaterial.primaryLevel = 1;
  91399. this._groundMaterial.primaryColor = this._options.groundColor;
  91400. this._groundMaterial.secondaryLevel = 0;
  91401. this._groundMaterial.tertiaryLevel = 0;
  91402. this._groundMaterial.useRGBColor = false;
  91403. this._groundMaterial.enableNoise = true;
  91404. if (this._ground) {
  91405. this._ground.material = this._groundMaterial;
  91406. }
  91407. };
  91408. /**
  91409. * Setup the ground diffuse texture according to the specified options.
  91410. */
  91411. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  91412. if (!this._groundMaterial) {
  91413. return;
  91414. }
  91415. if (this._groundTexture) {
  91416. return;
  91417. }
  91418. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  91419. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  91420. return;
  91421. }
  91422. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  91423. diffuseTexture.gammaSpace = false;
  91424. diffuseTexture.hasAlpha = true;
  91425. this._groundMaterial.diffuseTexture = diffuseTexture;
  91426. };
  91427. /**
  91428. * Setup the ground mirror texture according to the specified options.
  91429. */
  91430. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  91431. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91432. if (!this._groundMirror) {
  91433. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  91434. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  91435. this._groundMirror.anisotropicFilteringLevel = 1;
  91436. this._groundMirror.wrapU = wrapping;
  91437. this._groundMirror.wrapV = wrapping;
  91438. this._groundMirror.gammaSpace = false;
  91439. if (this._groundMirror.renderList) {
  91440. for (var i = 0; i < this._scene.meshes.length; i++) {
  91441. var mesh = this._scene.meshes[i];
  91442. if (mesh !== this._ground &&
  91443. mesh !== this._skybox &&
  91444. mesh !== this._rootMesh) {
  91445. this._groundMirror.renderList.push(mesh);
  91446. }
  91447. }
  91448. }
  91449. }
  91450. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  91451. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  91452. };
  91453. /**
  91454. * Setup the ground to receive the mirror texture.
  91455. */
  91456. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  91457. if (this._groundMaterial) {
  91458. this._groundMaterial.reflectionTexture = this._groundMirror;
  91459. this._groundMaterial.reflectionFresnel = true;
  91460. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  91461. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  91462. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  91463. }
  91464. };
  91465. /**
  91466. * Setup the skybox according to the specified options.
  91467. */
  91468. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  91469. var _this = this;
  91470. if (!this._skybox) {
  91471. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  91472. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  91473. }
  91474. this._skybox.parent = this._rootMesh;
  91475. };
  91476. /**
  91477. * Setup the skybox material according to the specified options.
  91478. */
  91479. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  91480. if (!this._skybox) {
  91481. return;
  91482. }
  91483. if (!this._skyboxMaterial) {
  91484. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  91485. }
  91486. this._skyboxMaterial.useRGBColor = false;
  91487. this._skyboxMaterial.primaryLevel = 1;
  91488. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  91489. this._skyboxMaterial.secondaryLevel = 0;
  91490. this._skyboxMaterial.tertiaryLevel = 0;
  91491. this._skyboxMaterial.enableNoise = true;
  91492. this._skybox.material = this._skyboxMaterial;
  91493. };
  91494. /**
  91495. * Setup the skybox reflection texture according to the specified options.
  91496. */
  91497. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  91498. if (!this._skyboxMaterial) {
  91499. return;
  91500. }
  91501. if (this._skyboxTexture) {
  91502. return;
  91503. }
  91504. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  91505. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  91506. return;
  91507. }
  91508. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  91509. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  91510. this._skyboxTexture.gammaSpace = false;
  91511. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  91512. };
  91513. /**
  91514. * Dispose all the elements created by the Helper.
  91515. */
  91516. EnvironmentHelper.prototype.dispose = function () {
  91517. if (this._groundMaterial) {
  91518. this._groundMaterial.dispose(true, true);
  91519. }
  91520. if (this._skyboxMaterial) {
  91521. this._skyboxMaterial.dispose(true, true);
  91522. }
  91523. this._rootMesh.dispose(false);
  91524. };
  91525. /**
  91526. * Default ground texture URL.
  91527. */
  91528. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  91529. /**
  91530. * Default skybox texture URL.
  91531. */
  91532. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  91533. /**
  91534. * Default environment texture URL.
  91535. */
  91536. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  91537. return EnvironmentHelper;
  91538. }());
  91539. BABYLON.EnvironmentHelper = EnvironmentHelper;
  91540. })(BABYLON || (BABYLON = {}));
  91541. //# sourceMappingURL=babylon.environmentHelper.js.map
  91542. var BABYLON;
  91543. (function (BABYLON) {
  91544. /**
  91545. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  91546. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  91547. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  91548. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  91549. */
  91550. var VideoDome = /** @class */ (function (_super) {
  91551. __extends(VideoDome, _super);
  91552. /**
  91553. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  91554. * @param name Element's name, child elements will append suffixes for their own names.
  91555. * @param urlsOrVideo
  91556. * @param options An object containing optional or exposed sub element properties:
  91557. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  91558. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  91559. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  91560. * @param options **loop=true** Automatically loop video on end.
  91561. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  91562. */
  91563. function VideoDome(name, urlsOrVideo, options, scene) {
  91564. var _this = _super.call(this, name, scene) || this;
  91565. // set defaults and manage values
  91566. name = name || "videoDome";
  91567. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  91568. options.clickToPlay = Boolean(options.clickToPlay);
  91569. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  91570. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  91571. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  91572. // create
  91573. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  91574. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  91575. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  91576. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  91577. flat: false,
  91578. radius: options.size,
  91579. subdivisions: options.resolution,
  91580. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  91581. }, scene);
  91582. // configure material
  91583. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  91584. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  91585. material.reflectionTexture = _this._videoTexture;
  91586. material.useEquirectangularFOV = true;
  91587. material.fovMultiplier = 1.0;
  91588. // configure mesh
  91589. _this._mesh.material = material;
  91590. _this._mesh.parent = _this;
  91591. // optional configuration
  91592. if (options.clickToPlay) {
  91593. scene.onPointerUp = function () {
  91594. _this._videoTexture.video.play();
  91595. };
  91596. }
  91597. return _this;
  91598. }
  91599. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  91600. /**
  91601. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  91602. * Also see the options.resolution property.
  91603. */
  91604. get: function () {
  91605. return this._material.fovMultiplier;
  91606. },
  91607. set: function (value) {
  91608. this._material.fovMultiplier = value;
  91609. },
  91610. enumerable: true,
  91611. configurable: true
  91612. });
  91613. /**
  91614. * Releases resources associated with this node.
  91615. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  91616. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  91617. */
  91618. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  91619. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  91620. this._videoTexture.dispose();
  91621. this._mesh.dispose();
  91622. this._material.dispose();
  91623. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  91624. };
  91625. return VideoDome;
  91626. }(BABYLON.Node));
  91627. BABYLON.VideoDome = VideoDome;
  91628. })(BABYLON || (BABYLON = {}));
  91629. //# sourceMappingURL=babylon.videoDome.js.map
  91630. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb);\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h/height;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\n#ifdef GRAIN\nvec2 seed=vUV*(grainAnimatedSeed);\nfloat grain=dither(seed,grainVarianceAmount);\n\nfloat lum=getLuminance(result.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\nresult.rgb+=grain*grainAmount;\nresult.rgb=max(result.rgb,0.0);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifndef GRAIN \n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\n#endif\ngl_FragColor=color;\n}\n"};
  91631. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif\n#ifdef GRAIN\nuniform float grainVarianceAmount;\nuniform float grainAnimatedSeed;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  91632. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  91633. globalObject["BABYLON"] = BABYLON
  91634. return BABYLON;
  91635. });
  91636. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(16)))
  91637. /***/ }),
  91638. /* 1 */
  91639. /***/ (function(module, exports, __webpack_require__) {
  91640. "use strict";
  91641. Object.defineProperty(exports, "__esModule", { value: true });
  91642. var babylonjs_1 = __webpack_require__(0);
  91643. var helper_1 = __webpack_require__(2);
  91644. var HTMLMapper = (function () {
  91645. function HTMLMapper() {
  91646. }
  91647. HTMLMapper.prototype.map = function (element) {
  91648. var config = {};
  91649. var _loop_1 = function (attrIdx) {
  91650. var attr = element.attributes.item(attrIdx);
  91651. var split = attr.nodeName.split('.');
  91652. split.reduce(function (currentConfig, key, idx) {
  91653. var camelKey = helper_1.kebabToCamel(key);
  91654. if (idx === split.length - 1) {
  91655. var val = attr.nodeValue;
  91656. if (val === "true") {
  91657. val = true;
  91658. }
  91659. else if (val === "false") {
  91660. val = false;
  91661. }
  91662. else {
  91663. var isnum = /^\d+$/.test(val);
  91664. if (isnum) {
  91665. var number = parseFloat(val);
  91666. if (!isNaN(number)) {
  91667. val = number;
  91668. }
  91669. }
  91670. }
  91671. currentConfig[camelKey] = val;
  91672. }
  91673. else {
  91674. currentConfig[camelKey] = currentConfig[camelKey] || {};
  91675. }
  91676. return currentConfig[camelKey];
  91677. }, config);
  91678. };
  91679. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  91680. _loop_1(attrIdx);
  91681. }
  91682. return config;
  91683. };
  91684. return HTMLMapper;
  91685. }());
  91686. var JSONMapper = (function () {
  91687. function JSONMapper() {
  91688. }
  91689. JSONMapper.prototype.map = function (rawSource) {
  91690. return JSON.parse(rawSource);
  91691. };
  91692. return JSONMapper;
  91693. }());
  91694. var DOMMapper = (function () {
  91695. function DOMMapper() {
  91696. }
  91697. DOMMapper.prototype.map = function (baseElement) {
  91698. var htmlMapper = new HTMLMapper();
  91699. var config = htmlMapper.map(baseElement);
  91700. var traverseChildren = function (element, partConfig) {
  91701. var children = element.children;
  91702. if (children.length) {
  91703. for (var i = 0; i < children.length; ++i) {
  91704. var item = children.item(i);
  91705. var configMapped = htmlMapper.map(item);
  91706. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  91707. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  91708. partConfig[key] = [];
  91709. }
  91710. else {
  91711. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  91712. partConfig.push(configMapped);
  91713. }
  91714. else if (partConfig[key]) {
  91715. element.setAttribute('array', 'true');
  91716. var oldItem = partConfig[key];
  91717. partConfig = [oldItem, configMapped];
  91718. }
  91719. else {
  91720. partConfig[key] = configMapped;
  91721. }
  91722. }
  91723. traverseChildren(item, partConfig[key] || configMapped);
  91724. }
  91725. }
  91726. return partConfig;
  91727. };
  91728. traverseChildren(baseElement, config);
  91729. return config;
  91730. };
  91731. return DOMMapper;
  91732. }());
  91733. var MapperManager = (function () {
  91734. function MapperManager() {
  91735. this.mappers = {
  91736. "html": new HTMLMapper(),
  91737. "json": new JSONMapper(),
  91738. "dom": new DOMMapper()
  91739. };
  91740. }
  91741. MapperManager.prototype.getMapper = function (type) {
  91742. if (!this.mappers[type]) {
  91743. babylonjs_1.Tools.Error("No mapper defined for " + type);
  91744. }
  91745. return this.mappers[type] || this.mappers[MapperManager.DefaultMapper];
  91746. };
  91747. MapperManager.prototype.registerMapper = function (type, mapper) {
  91748. this.mappers[type] = mapper;
  91749. };
  91750. MapperManager.DefaultMapper = 'json';
  91751. return MapperManager;
  91752. }());
  91753. exports.MapperManager = MapperManager;
  91754. exports.mapperManager = new MapperManager();
  91755. /***/ }),
  91756. /* 2 */
  91757. /***/ (function(module, exports, __webpack_require__) {
  91758. "use strict";
  91759. Object.defineProperty(exports, "__esModule", { value: true });
  91760. function isUrl(urlToCheck) {
  91761. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  91762. return true;
  91763. }
  91764. return false;
  91765. }
  91766. exports.isUrl = isUrl;
  91767. function kebabToCamel(s) {
  91768. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  91769. }
  91770. exports.kebabToCamel = kebabToCamel;
  91771. function camelToKebab(str) {
  91772. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  91773. }
  91774. exports.camelToKebab = camelToKebab;
  91775. /***/ }),
  91776. /* 3 */
  91777. /***/ (function(module, exports, __webpack_require__) {
  91778. "use strict";
  91779. Object.defineProperty(exports, "__esModule", { value: true });
  91780. var babylonjs_1 = __webpack_require__(0);
  91781. var ViewerManager = (function () {
  91782. function ViewerManager() {
  91783. this.viewers = {};
  91784. this.onViewerAddedObservable = new babylonjs_1.Observable();
  91785. }
  91786. ViewerManager.prototype.addViewer = function (viewer) {
  91787. this.viewers[viewer.getBaseId()] = viewer;
  91788. this._onViewerAdded(viewer);
  91789. };
  91790. ViewerManager.prototype.getViewerById = function (id) {
  91791. return this.viewers[id];
  91792. };
  91793. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  91794. for (var id in this.viewers) {
  91795. if (this.viewers[id].containerElement === element) {
  91796. return this.getViewerById(id);
  91797. }
  91798. }
  91799. };
  91800. ViewerManager.prototype.getViewerPromiseById = function (id) {
  91801. var _this = this;
  91802. return new Promise(function (resolve, reject) {
  91803. var localViewer = _this.getViewerById(id);
  91804. if (localViewer) {
  91805. return resolve(localViewer);
  91806. }
  91807. var viewerFunction = function (viewer) {
  91808. if (viewer.getBaseId() === id) {
  91809. resolve(viewer);
  91810. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  91811. }
  91812. };
  91813. _this.onViewerAddedObservable.add(viewerFunction);
  91814. });
  91815. };
  91816. ViewerManager.prototype._onViewerAdded = function (viewer) {
  91817. this.onViewerAdded && this.onViewerAdded(viewer);
  91818. this.onViewerAddedObservable.notifyObservers(viewer);
  91819. };
  91820. return ViewerManager;
  91821. }());
  91822. exports.ViewerManager = ViewerManager;
  91823. exports.viewerManager = new ViewerManager();
  91824. /***/ }),
  91825. /* 4 */
  91826. /***/ (function(module, exports, __webpack_require__) {
  91827. "use strict";
  91828. var __extends = (this && this.__extends) || (function () {
  91829. var extendStatics = Object.setPrototypeOf ||
  91830. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  91831. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  91832. return function (d, b) {
  91833. extendStatics(d, b);
  91834. function __() { this.constructor = d; }
  91835. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  91836. };
  91837. })();
  91838. Object.defineProperty(exports, "__esModule", { value: true });
  91839. var viewer_1 = __webpack_require__(5);
  91840. var babylonjs_1 = __webpack_require__(0);
  91841. var DefaultViewer = (function (_super) {
  91842. __extends(DefaultViewer, _super);
  91843. function DefaultViewer(containerElement, initialConfiguration) {
  91844. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  91845. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  91846. _this.containerElement = containerElement;
  91847. _this.onModelLoaded = function (model) {
  91848. var hideLoadingDelay = 500;
  91849. if (_this.configuration.lab && _this.configuration.lab.hideLoadingDelay !== undefined) {
  91850. hideLoadingDelay = _this.configuration.lab.hideLoadingDelay;
  91851. }
  91852. setTimeout(function () {
  91853. _this.hideLoadingScreen();
  91854. }, hideLoadingDelay);
  91855. return;
  91856. };
  91857. _this.onModelLoadedObservable.add(_this.onModelLoaded);
  91858. return _this;
  91859. }
  91860. DefaultViewer.prototype.initScene = function () {
  91861. var _this = this;
  91862. return _super.prototype.initScene.call(this).then(function () {
  91863. _this.extendClassWithConfig(_this.scene, _this.configuration.scene);
  91864. return _this.scene;
  91865. });
  91866. };
  91867. DefaultViewer.prototype.onTemplatesLoaded = function () {
  91868. var _this = this;
  91869. this.showLoadingScreen();
  91870. this.initNavbar();
  91871. var closeButton = document.getElementById('close-button');
  91872. if (closeButton) {
  91873. closeButton.addEventListener('pointerdown', function () {
  91874. _this.hideOverlayScreen();
  91875. });
  91876. }
  91877. return _super.prototype.onTemplatesLoaded.call(this);
  91878. };
  91879. DefaultViewer.prototype.initNavbar = function () {
  91880. var navbar = this.templateManager.getTemplate('navBar');
  91881. if (navbar) {
  91882. var navbarHeight_1 = navbar.parent.clientHeight + 'px';
  91883. var navbarShown_1 = true;
  91884. var timeoutCancel_1;
  91885. var triggerNavbar = function (show, evt) {
  91886. if (show === void 0) { show = false; }
  91887. if (!navbar || evt.button > 0)
  91888. return;
  91889. timeoutCancel_1 && clearTimeout(timeoutCancel_1);
  91890. if (show === navbarShown_1)
  91891. return;
  91892. if (show) {
  91893. navbar.parent.style.bottom = show ? '0px' : '-' + navbarHeight_1;
  91894. navbarShown_1 = show;
  91895. }
  91896. else {
  91897. var visibilityTimeout = 2000;
  91898. if (navbar.configuration.params && navbar.configuration.params.visibilityTimeout !== undefined) {
  91899. visibilityTimeout = navbar.configuration.params.visibilityTimeout;
  91900. }
  91901. timeoutCancel_1 = setTimeout(function () {
  91902. if (navbar) {
  91903. navbar.parent.style.bottom = '-' + navbarHeight_1;
  91904. }
  91905. navbarShown_1 = show;
  91906. }, visibilityTimeout);
  91907. }
  91908. };
  91909. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerout');
  91910. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, true), 'pointerdown');
  91911. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerup');
  91912. this.templateManager.eventManager.registerCallback('navBar', triggerNavbar.bind(this, true), 'pointerover');
  91913. var viewerTemplate = this.templateManager.getTemplate('viewer');
  91914. var viewerElement_1 = viewerTemplate && viewerTemplate.parent;
  91915. var triggerFullscren = function (eventData) {
  91916. if (viewerElement_1) {
  91917. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  91918. if (!fullscreenElement) {
  91919. var requestFullScreen = viewerElement_1.requestFullscreen || viewerElement_1.webkitRequestFullscreen || viewerElement_1.msRequestFullscreen || viewerElement_1.mozRequestFullScreen;
  91920. requestFullScreen.call(viewerElement_1);
  91921. }
  91922. else {
  91923. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  91924. exitFullscreen.call(document);
  91925. }
  91926. }
  91927. };
  91928. this.templateManager.eventManager.registerCallback('navBar', triggerFullscren, 'pointerdown', '#fullscreen-button');
  91929. }
  91930. };
  91931. DefaultViewer.prototype.prepareContainerElement = function () {
  91932. this.containerElement.style.position = 'relative';
  91933. this.containerElement.style.display = 'flex';
  91934. };
  91935. DefaultViewer.prototype.configureModel = function (modelConfiguration, model) {
  91936. _super.prototype.configureModel.call(this, modelConfiguration, model);
  91937. var navbar = this.templateManager.getTemplate('navBar');
  91938. if (!navbar)
  91939. return;
  91940. var metadataContainer = navbar.parent.querySelector('#model-metadata');
  91941. if (metadataContainer) {
  91942. if (modelConfiguration.title !== undefined) {
  91943. var element = metadataContainer.querySelector('span.model-title');
  91944. if (element) {
  91945. element.innerHTML = modelConfiguration.title;
  91946. }
  91947. }
  91948. if (modelConfiguration.subtitle !== undefined) {
  91949. var element = metadataContainer.querySelector('span.model-subtitle');
  91950. if (element) {
  91951. element.innerHTML = modelConfiguration.subtitle;
  91952. }
  91953. }
  91954. if (modelConfiguration.thumbnail !== undefined) {
  91955. metadataContainer.querySelector('.thumbnail').style.backgroundImage = "url('" + modelConfiguration.thumbnail + "')";
  91956. }
  91957. }
  91958. };
  91959. DefaultViewer.prototype.loadModel = function (model) {
  91960. var _this = this;
  91961. if (model === void 0) { model = this.configuration.model; }
  91962. this.showLoadingScreen();
  91963. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  91964. console.log(error);
  91965. _this.hideLoadingScreen();
  91966. _this.showOverlayScreen('error');
  91967. return Promise.reject(error);
  91968. });
  91969. };
  91970. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  91971. var _this = this;
  91972. var template = this.templateManager.getTemplate('overlay');
  91973. if (!template)
  91974. return Promise.resolve('Overlay template not found');
  91975. return template.show((function (template) {
  91976. var canvasRect = _this.containerElement.getBoundingClientRect();
  91977. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  91978. template.parent.style.display = 'flex';
  91979. template.parent.style.width = canvasRect.width + "px";
  91980. template.parent.style.height = canvasRect.height + "px";
  91981. template.parent.style.opacity = "1";
  91982. var subTemplate = _this.templateManager.getTemplate(subScreen);
  91983. if (!subTemplate) {
  91984. return Promise.reject(subScreen + ' template not found');
  91985. }
  91986. return subTemplate.show((function (template) {
  91987. template.parent.style.display = 'flex';
  91988. return Promise.resolve(template);
  91989. }));
  91990. }));
  91991. };
  91992. DefaultViewer.prototype.hideOverlayScreen = function () {
  91993. var template = this.templateManager.getTemplate('overlay');
  91994. if (!template)
  91995. return Promise.resolve('Overlay template not found');
  91996. return template.hide((function (template) {
  91997. template.parent.style.opacity = "0";
  91998. var onTransitionEnd = function () {
  91999. template.parent.removeEventListener("transitionend", onTransitionEnd);
  92000. template.parent.style.display = 'none';
  92001. };
  92002. template.parent.addEventListener("transitionend", onTransitionEnd);
  92003. var overlays = template.parent.querySelectorAll('.overlay');
  92004. if (overlays) {
  92005. for (var i = 0; i < overlays.length; ++i) {
  92006. var htmlElement = overlays.item(i);
  92007. htmlElement.style.display = 'none';
  92008. }
  92009. }
  92010. return Promise.resolve(template);
  92011. }));
  92012. };
  92013. DefaultViewer.prototype.showLoadingScreen = function () {
  92014. var _this = this;
  92015. var template = this.templateManager.getTemplate('loadingScreen');
  92016. if (!template)
  92017. return Promise.resolve('Loading Screen template not found');
  92018. return template.show((function (template) {
  92019. var canvasRect = _this.containerElement.getBoundingClientRect();
  92020. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  92021. template.parent.style.display = 'flex';
  92022. template.parent.style.width = canvasRect.width + "px";
  92023. template.parent.style.height = canvasRect.height + "px";
  92024. template.parent.style.opacity = "1";
  92025. template.parent.style.backgroundColor = "black";
  92026. return Promise.resolve(template);
  92027. }));
  92028. };
  92029. DefaultViewer.prototype.hideLoadingScreen = function () {
  92030. var template = this.templateManager.getTemplate('loadingScreen');
  92031. if (!template)
  92032. return Promise.resolve('Loading Screen template not found');
  92033. return template.hide((function (template) {
  92034. template.parent.style.opacity = "0";
  92035. var onTransitionEnd = function () {
  92036. template.parent.removeEventListener("transitionend", onTransitionEnd);
  92037. template.parent.style.display = 'none';
  92038. };
  92039. template.parent.addEventListener("transitionend", onTransitionEnd);
  92040. return Promise.resolve(template);
  92041. }));
  92042. };
  92043. DefaultViewer.prototype.configureLights = function (lightsConfiguration, model) {
  92044. var _this = this;
  92045. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  92046. _super.prototype.configureLights.call(this, lightsConfiguration, model);
  92047. if (this.configuration.lab && this.configuration.lab.flashlight) {
  92048. var pointerPosition = BABYLON.Vector3.Zero();
  92049. var lightTarget_1;
  92050. var angle = 0.5;
  92051. var exponent = Math.PI / 2;
  92052. if (typeof this.configuration.lab.flashlight === "object") {
  92053. exponent = this.configuration.lab.flashlight.exponent || exponent;
  92054. angle = this.configuration.lab.flashlight.angle || angle;
  92055. }
  92056. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.scene);
  92057. if (typeof this.configuration.lab.flashlight === "object") {
  92058. flashlight.intensity = this.configuration.lab.flashlight.intensity || flashlight.intensity;
  92059. if (this.configuration.lab.flashlight.diffuse) {
  92060. flashlight.diffuse.r = this.configuration.lab.flashlight.diffuse.r;
  92061. flashlight.diffuse.g = this.configuration.lab.flashlight.diffuse.g;
  92062. flashlight.diffuse.b = this.configuration.lab.flashlight.diffuse.b;
  92063. }
  92064. if (this.configuration.lab.flashlight.specular) {
  92065. flashlight.specular.r = this.configuration.lab.flashlight.specular.r;
  92066. flashlight.specular.g = this.configuration.lab.flashlight.specular.g;
  92067. flashlight.specular.b = this.configuration.lab.flashlight.specular.b;
  92068. }
  92069. }
  92070. this.scene.constantlyUpdateMeshUnderPointer = true;
  92071. this.scene.onPointerObservable.add(function (eventData, eventState) {
  92072. if (eventData.type === 4 && eventData.pickInfo) {
  92073. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  92074. }
  92075. else {
  92076. lightTarget_1 = undefined;
  92077. }
  92078. });
  92079. var updateFlashlightFunction = function () {
  92080. if (_this.camera && flashlight) {
  92081. flashlight.position.copyFrom(_this.camera.position);
  92082. if (lightTarget_1) {
  92083. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  92084. }
  92085. }
  92086. };
  92087. this.scene.registerBeforeRender(updateFlashlightFunction);
  92088. this.registeredOnBeforerenderFunctions.push(updateFlashlightFunction);
  92089. }
  92090. };
  92091. return DefaultViewer;
  92092. }(viewer_1.AbstractViewer));
  92093. exports.DefaultViewer = DefaultViewer;
  92094. /***/ }),
  92095. /* 5 */
  92096. /***/ (function(module, exports, __webpack_require__) {
  92097. "use strict";
  92098. Object.defineProperty(exports, "__esModule", { value: true });
  92099. var viewerManager_1 = __webpack_require__(3);
  92100. var templateManager_1 = __webpack_require__(19);
  92101. var loader_1 = __webpack_require__(22);
  92102. var babylonjs_1 = __webpack_require__(0);
  92103. var deepmerge = __webpack_require__(13);
  92104. var viewerModel_1 = __webpack_require__(30);
  92105. var AbstractViewer = (function () {
  92106. function AbstractViewer(containerElement, initialConfiguration) {
  92107. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  92108. var _this = this;
  92109. this.containerElement = containerElement;
  92110. this.resize = function () {
  92111. if (!_this.isCanvasInDOM()) {
  92112. return;
  92113. }
  92114. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  92115. return;
  92116. }
  92117. _this.engine.resize();
  92118. };
  92119. this.render = function () {
  92120. _this.scene && _this.scene.activeCamera && _this.scene.render();
  92121. };
  92122. if (containerElement.id) {
  92123. this.baseId = containerElement.id;
  92124. }
  92125. else {
  92126. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  92127. }
  92128. this.onSceneInitObservable = new babylonjs_1.Observable();
  92129. this.onEngineInitObservable = new babylonjs_1.Observable();
  92130. this.onModelLoadedObservable = new babylonjs_1.Observable();
  92131. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  92132. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  92133. this.onInitDoneObservable = new babylonjs_1.Observable();
  92134. this.onLoaderInitObservable = new babylonjs_1.Observable();
  92135. this.registeredOnBeforerenderFunctions = [];
  92136. this.models = [];
  92137. viewerManager_1.viewerManager.addViewer(this);
  92138. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  92139. this.prepareContainerElement();
  92140. loader_1.default.loadConfiguration(initialConfiguration, function (configuration) {
  92141. _this.configuration = deepmerge(_this.configuration || {}, configuration);
  92142. if (_this.configuration.observers) {
  92143. _this.configureObservers(_this.configuration.observers);
  92144. }
  92145. var templateConfiguration = _this.configuration.templates || {};
  92146. _this.templateManager.initTemplate(templateConfiguration);
  92147. _this.templateManager.onAllLoaded.add(function () {
  92148. var canvas = _this.templateManager.getCanvas();
  92149. if (canvas) {
  92150. _this.canvas = canvas;
  92151. }
  92152. _this._onTemplateLoaded();
  92153. });
  92154. });
  92155. }
  92156. Object.defineProperty(AbstractViewer.prototype, "isHdrSupported", {
  92157. get: function () {
  92158. return this._hdrSupport;
  92159. },
  92160. enumerable: true,
  92161. configurable: true
  92162. });
  92163. AbstractViewer.prototype.getBaseId = function () {
  92164. return this.baseId;
  92165. };
  92166. AbstractViewer.prototype.isCanvasInDOM = function () {
  92167. return !!this.canvas && !!this.canvas.parentElement;
  92168. };
  92169. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  92170. if (newConfiguration === void 0) { newConfiguration = this.configuration; }
  92171. this.configuration = deepmerge(this.configuration || {}, newConfiguration);
  92172. if (newConfiguration.scene) {
  92173. this.configureScene(newConfiguration.scene);
  92174. }
  92175. if (newConfiguration.optimizer) {
  92176. this.configureOptimizer(newConfiguration.optimizer);
  92177. }
  92178. if (newConfiguration.observers) {
  92179. this.configureObservers(newConfiguration.observers);
  92180. }
  92181. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  92182. this.configureModel(newConfiguration.model);
  92183. }
  92184. if (newConfiguration.lights) {
  92185. this.configureLights(newConfiguration.lights);
  92186. }
  92187. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  92188. this.configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  92189. }
  92190. if (newConfiguration.camera) {
  92191. this.configureCamera(newConfiguration.camera);
  92192. }
  92193. };
  92194. AbstractViewer.prototype.configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  92195. if (!skyboxConifguration && !groundConfiguration) {
  92196. if (this.environmentHelper) {
  92197. this.environmentHelper.dispose();
  92198. delete this.environmentHelper;
  92199. }
  92200. ;
  92201. return Promise.resolve(this.scene);
  92202. }
  92203. var options = {
  92204. createGround: !!groundConfiguration,
  92205. createSkybox: !!skyboxConifguration,
  92206. setupImageProcessing: false
  92207. };
  92208. if (groundConfiguration) {
  92209. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  92210. var groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  92211. if (groundSize) {
  92212. options.groundSize = groundSize;
  92213. }
  92214. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  92215. if (groundConfig.shadowLevel !== undefined) {
  92216. options.groundShadowLevel = groundConfig.shadowLevel;
  92217. }
  92218. options.enableGroundMirror = !!groundConfig.mirror;
  92219. if (groundConfig.texture) {
  92220. options.groundTexture = groundConfig.texture;
  92221. }
  92222. if (groundConfig.color) {
  92223. options.groundColor = new babylonjs_1.Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b);
  92224. }
  92225. if (groundConfig.opacity !== undefined) {
  92226. options.groundOpacity = groundConfig.opacity;
  92227. }
  92228. if (groundConfig.mirror) {
  92229. options.enableGroundMirror = true;
  92230. if (typeof groundConfig.mirror === "object") {
  92231. if (groundConfig.mirror.amount !== undefined)
  92232. options.groundMirrorAmount = groundConfig.mirror.amount;
  92233. if (groundConfig.mirror.sizeRatio !== undefined)
  92234. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  92235. if (groundConfig.mirror.blurKernel !== undefined)
  92236. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  92237. if (groundConfig.mirror.fresnelWeight !== undefined)
  92238. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  92239. if (groundConfig.mirror.fallOffDistance !== undefined)
  92240. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  92241. if (this.defaultPipelineTextureType !== undefined)
  92242. options.groundMirrorTextureType = this.defaultPipelineTextureType;
  92243. }
  92244. }
  92245. }
  92246. var postInitSkyboxMaterial = false;
  92247. if (skyboxConifguration) {
  92248. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  92249. if (conf.material && conf.material.imageProcessingConfiguration) {
  92250. options.setupImageProcessing = false;
  92251. }
  92252. var skyboxSize = conf.scale;
  92253. if (skyboxSize) {
  92254. options.skyboxSize = skyboxSize;
  92255. }
  92256. options.sizeAuto = !options.skyboxSize;
  92257. if (conf.color) {
  92258. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  92259. }
  92260. if (conf.cubeTexture && conf.cubeTexture.url) {
  92261. if (typeof conf.cubeTexture.url === "string") {
  92262. options.skyboxTexture = conf.cubeTexture.url;
  92263. }
  92264. else {
  92265. postInitSkyboxMaterial = true;
  92266. }
  92267. }
  92268. if (conf.material && conf.material.imageProcessingConfiguration) {
  92269. postInitSkyboxMaterial = true;
  92270. }
  92271. }
  92272. options.setupImageProcessing = false;
  92273. if (!this.environmentHelper) {
  92274. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  92275. }
  92276. else {
  92277. var scene = this.environmentHelper.rootMesh.getScene();
  92278. if (scene !== this.scene) {
  92279. this.environmentHelper.dispose();
  92280. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  92281. }
  92282. else {
  92283. this.environmentHelper.updateOptions(options);
  92284. }
  92285. }
  92286. if (postInitSkyboxMaterial) {
  92287. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  92288. if (skyboxMaterial) {
  92289. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  92290. this.extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  92291. }
  92292. }
  92293. }
  92294. };
  92295. AbstractViewer.prototype.configureScene = function (sceneConfig, optimizerConfig) {
  92296. if (!this.scene) {
  92297. return;
  92298. }
  92299. if (sceneConfig.debug) {
  92300. this.scene.debugLayer.show();
  92301. }
  92302. else {
  92303. if (this.scene.debugLayer.isVisible()) {
  92304. this.scene.debugLayer.hide();
  92305. }
  92306. }
  92307. if (sceneConfig.clearColor) {
  92308. var cc = sceneConfig.clearColor;
  92309. var oldcc = this.scene.clearColor;
  92310. if (cc.r !== undefined) {
  92311. oldcc.r = cc.r;
  92312. }
  92313. if (cc.g !== undefined) {
  92314. oldcc.g = cc.g;
  92315. }
  92316. if (cc.b !== undefined) {
  92317. oldcc.b = cc.b;
  92318. }
  92319. if (cc.a !== undefined) {
  92320. oldcc.a = cc.a;
  92321. }
  92322. }
  92323. if (sceneConfig.imageProcessingConfiguration) {
  92324. this.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  92325. }
  92326. if (sceneConfig.environmentTexture) {
  92327. if (this.scene.environmentTexture) {
  92328. this.scene.environmentTexture.dispose();
  92329. }
  92330. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  92331. this.scene.environmentTexture = environmentTexture;
  92332. }
  92333. if (sceneConfig.autoRotate) {
  92334. this.camera.useAutoRotationBehavior = true;
  92335. }
  92336. };
  92337. AbstractViewer.prototype.configureOptimizer = function (optimizerConfig) {
  92338. if (typeof optimizerConfig === 'boolean') {
  92339. if (this.sceneOptimizer) {
  92340. this.sceneOptimizer.stop();
  92341. this.sceneOptimizer.dispose();
  92342. delete this.sceneOptimizer;
  92343. }
  92344. if (optimizerConfig) {
  92345. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  92346. this.sceneOptimizer.start();
  92347. }
  92348. }
  92349. else {
  92350. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  92351. if (optimizerConfig.degradation) {
  92352. switch (optimizerConfig.degradation) {
  92353. case "low":
  92354. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  92355. break;
  92356. case "moderate":
  92357. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  92358. break;
  92359. case "hight":
  92360. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  92361. break;
  92362. }
  92363. }
  92364. if (this.sceneOptimizer) {
  92365. this.sceneOptimizer.stop();
  92366. this.sceneOptimizer.dispose();
  92367. }
  92368. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  92369. this.sceneOptimizer.start();
  92370. }
  92371. };
  92372. AbstractViewer.prototype.configureObservers = function (observersConfiguration) {
  92373. if (observersConfiguration.onEngineInit) {
  92374. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  92375. }
  92376. else {
  92377. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers.onEngineInit) {
  92378. this.onEngineInitObservable.removeCallback(window[this.configuration.observers.onEngineInit]);
  92379. }
  92380. }
  92381. if (observersConfiguration.onSceneInit) {
  92382. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  92383. }
  92384. else {
  92385. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers.onSceneInit) {
  92386. this.onSceneInitObservable.removeCallback(window[this.configuration.observers.onSceneInit]);
  92387. }
  92388. }
  92389. if (observersConfiguration.onModelLoaded) {
  92390. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  92391. }
  92392. else {
  92393. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers.onModelLoaded) {
  92394. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers.onModelLoaded]);
  92395. }
  92396. }
  92397. };
  92398. AbstractViewer.prototype.configureCamera = function (cameraConfig, model) {
  92399. var _this = this;
  92400. var focusMeshes = model ? model.meshes : this.scene.meshes;
  92401. if (!this.scene.activeCamera) {
  92402. this.scene.createDefaultCamera(true, true, true);
  92403. this.camera = this.scene.activeCamera;
  92404. }
  92405. if (cameraConfig.position) {
  92406. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  92407. }
  92408. if (cameraConfig.rotation) {
  92409. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  92410. }
  92411. this.extendClassWithConfig(this.camera, cameraConfig);
  92412. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  92413. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  92414. if (cameraConfig.behaviors) {
  92415. for (var name_1 in cameraConfig.behaviors) {
  92416. this.setCameraBehavior(cameraConfig.behaviors[name_1], focusMeshes);
  92417. }
  92418. }
  92419. ;
  92420. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  92421. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  92422. });
  92423. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  92424. var sceneDiagonalLenght = sceneDiagonal.length();
  92425. if (isFinite(sceneDiagonalLenght))
  92426. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  92427. };
  92428. AbstractViewer.prototype.configureLights = function (lightsConfiguration, model) {
  92429. var _this = this;
  92430. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  92431. var focusMeshes = model ? model.meshes : this.scene.meshes;
  92432. if (!Object.keys(lightsConfiguration).length)
  92433. return;
  92434. var lightsAvailable = this.scene.lights.map(function (light) { return light.name; });
  92435. var lightsToConfigure = Object.keys(this.configuration.lights || []);
  92436. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  92437. lightsAvailable.forEach(function (lName) {
  92438. if (lightsToConfigure.indexOf(lName) === -1) {
  92439. _this.scene.getLightByName(lName).dispose();
  92440. }
  92441. });
  92442. }
  92443. Object.keys(lightsConfiguration).forEach(function (name, idx) {
  92444. var lightConfig = { type: 0 };
  92445. if (typeof lightsConfiguration[name] === 'object') {
  92446. lightConfig = lightsConfiguration[name];
  92447. }
  92448. lightConfig.name = name;
  92449. var light;
  92450. if (lightsAvailable.indexOf(name) === -1) {
  92451. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  92452. if (!constructor)
  92453. return;
  92454. light = constructor();
  92455. }
  92456. else {
  92457. light = _this.scene.getLightByName(name);
  92458. lightsAvailable = lightsAvailable.filter(function (ln) { return ln !== name; });
  92459. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  92460. light.dispose();
  92461. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  92462. if (!constructor)
  92463. return;
  92464. light = constructor();
  92465. }
  92466. }
  92467. if (lightsConfiguration[name] === false) {
  92468. light.dispose();
  92469. return;
  92470. }
  92471. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  92472. light.setEnabled(enabled);
  92473. _this.extendClassWithConfig(light, lightConfig);
  92474. if (light instanceof babylonjs_1.ShadowLight) {
  92475. if (lightConfig.target) {
  92476. if (light.setDirectionToTarget) {
  92477. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  92478. light.setDirectionToTarget(target);
  92479. }
  92480. }
  92481. else if (lightConfig.direction) {
  92482. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  92483. light.direction = direction;
  92484. }
  92485. var shadowGenerator = light.getShadowGenerator();
  92486. if (lightConfig.shadowEnabled && _this.maxShadows) {
  92487. if (!shadowGenerator) {
  92488. shadowGenerator = new babylonjs_1.ShadowGenerator(512, light);
  92489. }
  92490. _this.extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  92491. var shadownMap = shadowGenerator.getShadowMap();
  92492. if (!shadownMap)
  92493. return;
  92494. var renderList = shadownMap.renderList;
  92495. for (var index = 0; index < focusMeshes.length; index++) {
  92496. if (babylonjs_1.Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  92497. renderList && renderList.push(focusMeshes[index]);
  92498. }
  92499. }
  92500. }
  92501. else if (shadowGenerator) {
  92502. shadowGenerator.dispose();
  92503. }
  92504. }
  92505. });
  92506. };
  92507. AbstractViewer.prototype.configureModel = function (modelConfiguration, model) {
  92508. var focusMeshes = model ? model.meshes : this.scene.meshes;
  92509. var meshesWithNoParent = focusMeshes.filter(function (m) { return !m.parent; });
  92510. var updateMeshesWithNoParent = function (variable, value, param) {
  92511. meshesWithNoParent.forEach(function (mesh) {
  92512. if (param) {
  92513. mesh[variable][param] = value;
  92514. }
  92515. else {
  92516. mesh[variable] = value;
  92517. }
  92518. });
  92519. };
  92520. var updateXYZ = function (variable, configValues) {
  92521. if (configValues.x !== undefined) {
  92522. updateMeshesWithNoParent(variable, configValues.x, 'x');
  92523. }
  92524. if (configValues.y !== undefined) {
  92525. updateMeshesWithNoParent(variable, configValues.y, 'y');
  92526. }
  92527. if (configValues.z !== undefined) {
  92528. updateMeshesWithNoParent(variable, configValues.z, 'z');
  92529. }
  92530. if (configValues.w !== undefined) {
  92531. updateMeshesWithNoParent(variable, configValues.w, 'w');
  92532. }
  92533. };
  92534. if (modelConfiguration.position) {
  92535. updateXYZ('position', modelConfiguration.position);
  92536. }
  92537. if (modelConfiguration.rotation) {
  92538. if (modelConfiguration.rotation.w) {
  92539. meshesWithNoParent.forEach(function (mesh) {
  92540. if (!mesh.rotationQuaternion) {
  92541. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  92542. }
  92543. });
  92544. updateXYZ('rotationQuaternion', modelConfiguration.rotation);
  92545. }
  92546. else {
  92547. updateXYZ('rotation', modelConfiguration.rotation);
  92548. }
  92549. }
  92550. if (modelConfiguration.scaling) {
  92551. updateXYZ('scaling', modelConfiguration.scaling);
  92552. }
  92553. if (modelConfiguration.castShadow) {
  92554. focusMeshes.forEach(function (mesh) {
  92555. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  92556. });
  92557. }
  92558. if (modelConfiguration.normalize) {
  92559. var center = false;
  92560. var unitSize = false;
  92561. var parentIndex = void 0;
  92562. if (modelConfiguration.normalize === true) {
  92563. center = true;
  92564. unitSize = true;
  92565. parentIndex = 0;
  92566. }
  92567. else {
  92568. center = !!modelConfiguration.normalize.center;
  92569. unitSize = !!modelConfiguration.normalize.unitSize;
  92570. parentIndex = modelConfiguration.normalize.parentIndex;
  92571. }
  92572. var meshesToNormalize = [];
  92573. if (parentIndex !== undefined) {
  92574. meshesToNormalize.push(focusMeshes[parentIndex]);
  92575. }
  92576. else {
  92577. meshesToNormalize = meshesWithNoParent;
  92578. }
  92579. if (unitSize) {
  92580. meshesToNormalize.forEach(function (mesh) {
  92581. mesh.normalizeToUnitCube(true);
  92582. mesh.computeWorldMatrix(true);
  92583. });
  92584. }
  92585. if (center) {
  92586. meshesToNormalize.forEach(function (mesh) {
  92587. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  92588. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  92589. var halfSizeVec = sizeVec.scale(0.5);
  92590. var center = boundingInfo.min.add(halfSizeVec);
  92591. mesh.position = center.scale(-1);
  92592. mesh.position.y += halfSizeVec.y;
  92593. mesh.computeWorldMatrix(true);
  92594. });
  92595. }
  92596. }
  92597. };
  92598. AbstractViewer.prototype.dispose = function () {
  92599. window.removeEventListener('resize', this.resize);
  92600. if (this.sceneOptimizer) {
  92601. this.sceneOptimizer.stop();
  92602. this.sceneOptimizer.dispose();
  92603. }
  92604. if (this.scene.activeCamera) {
  92605. this.scene.activeCamera.detachControl(this.canvas);
  92606. }
  92607. this.scene.dispose();
  92608. this.engine.dispose();
  92609. this.templateManager.dispose();
  92610. };
  92611. AbstractViewer.prototype.onTemplatesLoaded = function () {
  92612. return Promise.resolve(this);
  92613. };
  92614. AbstractViewer.prototype._onTemplateLoaded = function () {
  92615. var _this = this;
  92616. return this.onTemplatesLoaded().then(function () {
  92617. var autoLoadModel = !!_this.configuration.model;
  92618. return _this.initEngine().then(function (engine) {
  92619. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  92620. }).then(function () {
  92621. if (autoLoadModel) {
  92622. return _this.loadModel().then(function () { return _this.scene; });
  92623. }
  92624. else {
  92625. return _this.scene || _this.initScene();
  92626. }
  92627. }).then(function (scene) {
  92628. return _this.onSceneInitObservable.notifyObserversWithPromise(scene);
  92629. }).then(function () {
  92630. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  92631. });
  92632. });
  92633. };
  92634. AbstractViewer.prototype.initEngine = function () {
  92635. this.injectCustomShaders();
  92636. var canvasElement = this.templateManager.getCanvas();
  92637. if (!canvasElement) {
  92638. return Promise.reject('Canvas element not found!');
  92639. }
  92640. var config = this.configuration.engine || {};
  92641. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  92642. babylonjs_1.Database.IDBStorageEnabled = false;
  92643. if (!config.disableResize) {
  92644. window.addEventListener('resize', this.resize);
  92645. }
  92646. this.engine.runRenderLoop(this.render);
  92647. if (this.configuration.engine && this.configuration.engine.adaptiveQuality) {
  92648. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  92649. this.engine.setHardwareScalingLevel(scale);
  92650. }
  92651. this.handleHardwareLimitations();
  92652. return Promise.resolve(this.engine);
  92653. };
  92654. AbstractViewer.prototype.initScene = function () {
  92655. if (this.scene) {
  92656. this.scene.dispose();
  92657. }
  92658. this.scene = new babylonjs_1.Scene(this.engine);
  92659. this.scene.createDefaultLight(true);
  92660. if (this.configuration.scene) {
  92661. this.configureScene(this.configuration.scene);
  92662. if (this.configuration.optimizer) {
  92663. this.configureOptimizer(this.configuration.optimizer);
  92664. }
  92665. }
  92666. return Promise.resolve(this.scene);
  92667. };
  92668. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  92669. var _this = this;
  92670. if (modelConfig === void 0) { modelConfig = this.configuration.model; }
  92671. if (clearScene === void 0) { clearScene = true; }
  92672. var modelUrl = (typeof modelConfig === 'string') ? modelConfig : modelConfig.url;
  92673. if (!modelUrl) {
  92674. return Promise.reject("no model configuration found");
  92675. }
  92676. if (this.isLoading) {
  92677. return Promise.reject("sanother model is curently being loaded.");
  92678. }
  92679. this.isLoading = true;
  92680. if ((typeof modelConfig === 'string')) {
  92681. if (this.configuration.model && typeof this.configuration.model === 'object') {
  92682. this.configuration.model.url = modelConfig;
  92683. }
  92684. }
  92685. else {
  92686. if (this.configuration.model) {
  92687. deepmerge(this.configuration.model, modelConfig);
  92688. }
  92689. else {
  92690. this.configuration.model = modelConfig;
  92691. }
  92692. }
  92693. return Promise.resolve(this.scene).then(function (scene) {
  92694. if (!scene)
  92695. return _this.initScene();
  92696. if (clearScene) {
  92697. _this.models.forEach(function (m) { return m.dispose(); });
  92698. _this.models.length = 0;
  92699. }
  92700. return scene;
  92701. }).then(function () {
  92702. return new Promise(function (resolve, reject) {
  92703. var model = new viewerModel_1.ViewerModel(_this.configuration.model, _this.scene);
  92704. _this.models.push(model);
  92705. _this.lastUsedLoader = model.loader;
  92706. model.onLoadedObservable.add(function (model) {
  92707. resolve(model);
  92708. });
  92709. model.onLoadErrorObservable.add(function (errorObject) {
  92710. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject).then(function () {
  92711. reject(errorObject.exception);
  92712. });
  92713. });
  92714. model.onLoadProgressObservable.add(function (progressEvent) {
  92715. return _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  92716. });
  92717. _this.onLoaderInitObservable.notifyObserversWithPromise(_this.lastUsedLoader);
  92718. });
  92719. }).then(function (model) {
  92720. return _this.onModelLoadedObservable.notifyObserversWithPromise(model)
  92721. .then(function () {
  92722. _this.configureModel(_this.configuration.model || modelConfig, model);
  92723. _this.configureLights(_this.configuration.lights);
  92724. if (_this.configuration.camera) {
  92725. _this.configureCamera(_this.configuration.camera, model);
  92726. }
  92727. return _this.initEnvironment(model);
  92728. }).then(function () {
  92729. _this.isLoading = false;
  92730. return model;
  92731. });
  92732. });
  92733. };
  92734. AbstractViewer.prototype.initEnvironment = function (model) {
  92735. this.configureEnvironment(this.configuration.skybox, this.configuration.ground);
  92736. return Promise.resolve(this.scene);
  92737. };
  92738. AbstractViewer.prototype.handleHardwareLimitations = function () {
  92739. var maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  92740. var maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  92741. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  92742. this.maxShadows = 0;
  92743. }
  92744. else {
  92745. this.maxShadows = 3;
  92746. }
  92747. var caps = this.engine.getCaps();
  92748. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  92749. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  92750. this._hdrSupport = !!(linearFloatTargets || linearHalfFloatTargets);
  92751. if (linearHalfFloatTargets) {
  92752. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  92753. this.shadowGeneratorBias = 0.002;
  92754. }
  92755. else if (linearFloatTargets) {
  92756. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  92757. this.shadowGeneratorBias = 0.001;
  92758. }
  92759. else {
  92760. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  92761. this.shadowGeneratorBias = 0.001;
  92762. }
  92763. this.defaultPipelineTextureType = this._hdrSupport ? this.defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  92764. };
  92765. AbstractViewer.prototype.injectCustomShaders = function () {
  92766. var customShaders = this.configuration.customShaders;
  92767. if (!customShaders) {
  92768. return;
  92769. }
  92770. if (customShaders.shaders) {
  92771. Object.keys(customShaders.shaders).forEach(function (key) {
  92772. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  92773. });
  92774. }
  92775. if (customShaders.includes) {
  92776. Object.keys(customShaders.includes).forEach(function (key) {
  92777. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  92778. });
  92779. }
  92780. };
  92781. AbstractViewer.prototype.extendClassWithConfig = function (object, config) {
  92782. var _this = this;
  92783. if (!config)
  92784. return;
  92785. Object.keys(config).forEach(function (key) {
  92786. if (key in object && typeof object[key] !== 'function') {
  92787. if (typeof object[key] === 'object') {
  92788. _this.extendClassWithConfig(object[key], config[key]);
  92789. }
  92790. else {
  92791. if (config[key] !== undefined) {
  92792. object[key] = config[key];
  92793. }
  92794. }
  92795. }
  92796. });
  92797. };
  92798. AbstractViewer.prototype.setCameraBehavior = function (behaviorConfig, payload) {
  92799. var behavior;
  92800. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  92801. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  92802. switch (type) {
  92803. case 0:
  92804. this.camera.useAutoRotationBehavior = true;
  92805. behavior = this.camera.autoRotationBehavior;
  92806. break;
  92807. case 1:
  92808. this.camera.useBouncingBehavior = true;
  92809. behavior = this.camera.bouncingBehavior;
  92810. break;
  92811. case 2:
  92812. this.camera.useFramingBehavior = true;
  92813. behavior = this.camera.framingBehavior;
  92814. break;
  92815. default:
  92816. behavior = null;
  92817. break;
  92818. }
  92819. if (behavior) {
  92820. if (typeof behaviorConfig === "object") {
  92821. this.extendClassWithConfig(behavior, behaviorConfig);
  92822. }
  92823. }
  92824. switch (type) {
  92825. case 0:
  92826. break;
  92827. case 1:
  92828. break;
  92829. case 2:
  92830. if (config.zoomOnBoundingInfo) {
  92831. var meshes = payload;
  92832. var bounding = meshes[0].getHierarchyBoundingVectors();
  92833. behavior.zoomOnBoundingInfo(bounding.min, bounding.max);
  92834. }
  92835. break;
  92836. }
  92837. };
  92838. return AbstractViewer;
  92839. }());
  92840. exports.AbstractViewer = AbstractViewer;
  92841. /***/ }),
  92842. /* 6 */
  92843. /***/ (function(module, exports) {
  92844. module.exports = "<viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  92845. /***/ }),
  92846. /* 7 */
  92847. /***/ (function(module, exports) {
  92848. 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}}>";
  92849. /***/ }),
  92850. /* 8 */
  92851. /***/ (function(module, exports) {
  92852. 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=="
  92853. /***/ }),
  92854. /* 9 */
  92855. /***/ (function(module, exports) {
  92856. 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>";
  92857. /***/ }),
  92858. /* 10 */
  92859. /***/ (function(module, exports) {
  92860. 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>";
  92861. /***/ }),
  92862. /* 11 */
  92863. /***/ (function(module, exports) {
  92864. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  92865. /***/ }),
  92866. /* 12 */
  92867. /***/ (function(module, exports) {
  92868. module.exports = "Error loading the model";
  92869. /***/ }),
  92870. /* 13 */
  92871. /***/ (function(module, exports, __webpack_require__) {
  92872. (function (global, factory) {
  92873. true ? module.exports = factory() :
  92874. typeof define === 'function' && define.amd ? define(factory) :
  92875. (global.deepmerge = factory());
  92876. }(this, (function () { 'use strict';
  92877. var isMergeableObject = function isMergeableObject(value) {
  92878. return isNonNullObject(value)
  92879. && !isSpecial(value)
  92880. };
  92881. function isNonNullObject(value) {
  92882. return !!value && typeof value === 'object'
  92883. }
  92884. function isSpecial(value) {
  92885. var stringValue = Object.prototype.toString.call(value);
  92886. return stringValue === '[object RegExp]'
  92887. || stringValue === '[object Date]'
  92888. || isReactElement(value)
  92889. }
  92890. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  92891. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  92892. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  92893. function isReactElement(value) {
  92894. return value.$$typeof === REACT_ELEMENT_TYPE
  92895. }
  92896. function emptyTarget(val) {
  92897. return Array.isArray(val) ? [] : {}
  92898. }
  92899. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  92900. var clone = !optionsArgument || optionsArgument.clone !== false;
  92901. return (clone && isMergeableObject(value))
  92902. ? deepmerge(emptyTarget(value), value, optionsArgument)
  92903. : value
  92904. }
  92905. function defaultArrayMerge(target, source, optionsArgument) {
  92906. return target.concat(source).map(function(element) {
  92907. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  92908. })
  92909. }
  92910. function mergeObject(target, source, optionsArgument) {
  92911. var destination = {};
  92912. if (isMergeableObject(target)) {
  92913. Object.keys(target).forEach(function(key) {
  92914. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  92915. });
  92916. }
  92917. Object.keys(source).forEach(function(key) {
  92918. if (!isMergeableObject(source[key]) || !target[key]) {
  92919. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  92920. } else {
  92921. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  92922. }
  92923. });
  92924. return destination
  92925. }
  92926. function deepmerge(target, source, optionsArgument) {
  92927. var sourceIsArray = Array.isArray(source);
  92928. var targetIsArray = Array.isArray(target);
  92929. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  92930. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  92931. if (!sourceAndTargetTypesMatch) {
  92932. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  92933. } else if (sourceIsArray) {
  92934. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  92935. return arrayMerge(target, source, optionsArgument)
  92936. } else {
  92937. return mergeObject(target, source, optionsArgument)
  92938. }
  92939. }
  92940. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  92941. if (!Array.isArray(array)) {
  92942. throw new Error('first argument should be an array')
  92943. }
  92944. return array.reduce(function(prev, next) {
  92945. return deepmerge(prev, next, optionsArgument)
  92946. }, {})
  92947. };
  92948. var deepmerge_1 = deepmerge;
  92949. return deepmerge_1;
  92950. })));
  92951. /***/ }),
  92952. /* 14 */
  92953. /***/ (function(module, exports, __webpack_require__) {
  92954. module.exports = __webpack_require__(15);
  92955. /***/ }),
  92956. /* 15 */
  92957. /***/ (function(module, exports, __webpack_require__) {
  92958. "use strict";
  92959. Object.defineProperty(exports, "__esModule", { value: true });
  92960. var mappers_1 = __webpack_require__(1);
  92961. exports.mapperManager = mappers_1.mapperManager;
  92962. var viewerManager_1 = __webpack_require__(3);
  92963. exports.viewerManager = viewerManager_1.viewerManager;
  92964. var defaultViewer_1 = __webpack_require__(4);
  92965. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  92966. var viewer_1 = __webpack_require__(5);
  92967. exports.AbstractViewer = viewer_1.AbstractViewer;
  92968. var babylonjs_1 = __webpack_require__(0);
  92969. __webpack_require__(32);
  92970. __webpack_require__(33);
  92971. var initializer_1 = __webpack_require__(34);
  92972. exports.InitTags = initializer_1.InitTags;
  92973. babylonjs_1.PromisePolyfill.Apply();
  92974. exports.disableInit = false;
  92975. document.addEventListener("DOMContentLoaded", function (event) {
  92976. if (exports.disableInit)
  92977. return;
  92978. initializer_1.InitTags();
  92979. });
  92980. /***/ }),
  92981. /* 16 */
  92982. /***/ (function(module, exports) {
  92983. var g;
  92984. // This works in non-strict mode
  92985. g = (function() {
  92986. return this;
  92987. })();
  92988. try {
  92989. // This works if eval is allowed (see CSP)
  92990. g = g || Function("return this")() || (1,eval)("this");
  92991. } catch(e) {
  92992. // This works if the window reference is available
  92993. if(typeof window === "object")
  92994. g = window;
  92995. }
  92996. // g can still be undefined, but nothing to do about it...
  92997. // We return undefined, instead of nothing here, so it's
  92998. // easier to handle this case. if(!global) { ...}
  92999. module.exports = g;
  93000. /***/ }),
  93001. /* 17 */
  93002. /***/ (function(module, exports) {
  93003. module.exports = cannon;
  93004. /***/ }),
  93005. /* 18 */
  93006. /***/ (function(module, exports, __webpack_require__) {
  93007. /**
  93008. * from OimoPhysics DEV 1.1.0a AS3
  93009. * @author Saharan / http://el-ement.com/
  93010. *
  93011. * to Oimo.js 2015 JAVASCRIPT
  93012. * @author LoTh / http://lo-th.github.io/labs/
  93013. */
  93014. var OIMO = {
  93015. REVISION: "1.2",
  93016. // Global identification of next shape.
  93017. // This will be incremented every time a shape is created.
  93018. nextID: 0,
  93019. proxyID: 0,
  93020. // BroadPhase
  93021. BR_NULL: 0,
  93022. BR_BRUTE_FORCE: 1,
  93023. BR_SWEEP_AND_PRUNE: 2,
  93024. BR_BOUNDING_VOLUME_TREE: 3,
  93025. // body type
  93026. BODY_NULL: 0,
  93027. BODY_DYNAMIC: 1,
  93028. BODY_STATIC: 2,
  93029. // shape type
  93030. SHAPE_NULL: 0,
  93031. SHAPE_SPHERE: 1,
  93032. SHAPE_BOX: 2,
  93033. SHAPE_CYLINDER: 3,
  93034. SHAPE_TETRA: 4,
  93035. // joint type
  93036. JOINT_NULL: 0,
  93037. JOINT_DISTANCE: 1,
  93038. JOINT_BALL_AND_SOCKET: 2,
  93039. JOINT_HINGE: 3,
  93040. JOINT_WHEEL: 4,
  93041. JOINT_SLIDER: 5,
  93042. JOINT_PRISMATIC: 6,
  93043. // this world scale defaut is 0.1 to 10 meters max for dynamique body
  93044. // scale all by 100 so object is between 10 to 10000 three unit.
  93045. WORLD_SCALE: 100,
  93046. INV_SCALE: 0.01,
  93047. // AABB aproximation
  93048. AABB_PROX: 0.005,
  93049. // Math function
  93050. sqrt: Math.sqrt,
  93051. abs: Math.abs,
  93052. floor: Math.floor,
  93053. cos: Math.cos,
  93054. sin: Math.sin,
  93055. acos: Math.acos,
  93056. asin: Math.asin,
  93057. atan2: Math.atan2,
  93058. round: Math.round,
  93059. pow: Math.pow,
  93060. max: Math.max,
  93061. min: Math.min,
  93062. random: Math.random,
  93063. lerp: function (a, b, percent) { return a + (b - a) * percent; },
  93064. rand: function (a, b) { return OIMO.lerp(a, b, OIMO.random()); },
  93065. randInt: function (a, b, n) { return OIMO.lerp(a, b, OIMO.random()).toFixed(n || 0) * 1; },
  93066. int: function (x) { return ~~x; },
  93067. fix: function (x, n) { return x.toFixed(n || 3, 10); },
  93068. clamp: function (value, min, max) { return OIMO.max(min, OIMO.min(max, value)); },
  93069. degtorad: 0.0174532925199432957,
  93070. radtodeg: 57.295779513082320876,
  93071. PI: 3.141592653589793,
  93072. TwoPI: 6.283185307179586,
  93073. PI90: 1.570796326794896,
  93074. PI270: 4.712388980384689,
  93075. CustomError: null,
  93076. Error: function (Class, Msg) {
  93077. if (OIMO.CustomError == null) console.error(Class, Msg);
  93078. else OIMO.CustomError.innerHTML += Class + " - " + Msg + '<br>';
  93079. }
  93080. };
  93081. var OIMO_ARRAY_TYPE;
  93082. if (!OIMO_ARRAY_TYPE) { OIMO_ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array; }
  93083. try {
  93084. (function (w) {
  93085. var perfNow;
  93086. var perfNowNames = ['now', 'webkitNow', 'msNow', 'mozNow'];
  93087. if (!!w['performance']) for (var i = 0; i < perfNowNames.length; ++i) {
  93088. var n = perfNowNames[i];
  93089. if (!!w['performance'][n]) {
  93090. perfNow = function () { return w['performance'][n]() };
  93091. break;
  93092. }
  93093. }
  93094. if (!perfNow) perfNow = Date.now;
  93095. //w.perfNow = perfNow;
  93096. OIMO.now = perfNow;
  93097. })(window);
  93098. } catch (e) { OIMO.now = function () { return 0; }; }
  93099. /**
  93100. * The class of physical computing world.
  93101. * You must be added to the world physical all computing objects
  93102. * @author saharan
  93103. * @author lo-th
  93104. */
  93105. OIMO.World = function (TimeStep, BroadPhaseType, Iterations, NoStat) {
  93106. // The time between each step
  93107. this.timeStep = TimeStep || 0.01666; // 1/60;
  93108. // The number of iterations for constraint solvers.
  93109. this.numIterations = Iterations || 8;
  93110. // It is a wide-area collision judgment that is used in order to reduce as much as possible a detailed collision judgment.
  93111. switch (BroadPhaseType || 2) {
  93112. case 1: this.broadPhase = new OIMO.BruteForceBroadPhase(); break;
  93113. case 2: default: this.broadPhase = new OIMO.SAPBroadPhase(); break;
  93114. case 3: this.broadPhase = new OIMO.DBVTBroadPhase(); break;
  93115. }
  93116. // This is the detailed information of the performance.
  93117. this.performance = null;
  93118. this.isNoStat = NoStat || false;
  93119. if (!this.isNoStat) this.performance = new OIMO.Performance(this);
  93120. // Whether the constraints randomizer is enabled or not.
  93121. this.enableRandomizer = true;
  93122. // The rigid body list
  93123. this.rigidBodies = null;
  93124. // number of rigid body
  93125. this.numRigidBodies = 0;
  93126. // The contact list
  93127. this.contacts = null;
  93128. this.unusedContacts = null;
  93129. // The number of contact
  93130. this.numContacts = 0;
  93131. // The number of contact points
  93132. this.numContactPoints = 0;
  93133. // The joint list
  93134. this.joints = null;
  93135. // The number of joints.
  93136. this.numJoints = 0;
  93137. // The number of simulation islands.
  93138. this.numIslands = 0;
  93139. // The gravity in the world.
  93140. this.gravity = new OIMO.Vec3(0, -9.80665, 0);
  93141. var numShapeTypes = 5;//4;//3;
  93142. this.detectors = [];
  93143. this.detectors.length = numShapeTypes;
  93144. var i = numShapeTypes;
  93145. while (i--) {
  93146. this.detectors[i] = [];
  93147. this.detectors[i].length = numShapeTypes;
  93148. }
  93149. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_SPHERE] = new OIMO.SphereSphereCollisionDetector();
  93150. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_BOX] = new OIMO.SphereBoxCollisionDetector(false);
  93151. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_SPHERE] = new OIMO.SphereBoxCollisionDetector(true);
  93152. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_BOX] = new OIMO.BoxBoxCollisionDetector();
  93153. // CYLINDER add
  93154. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_CYLINDER] = new OIMO.CylinderCylinderCollisionDetector();
  93155. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_BOX] = new OIMO.BoxCylinderCollisionDetector(true);
  93156. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_CYLINDER] = new OIMO.BoxCylinderCollisionDetector(false);
  93157. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_SPHERE] = new OIMO.SphereCylinderCollisionDetector(true);
  93158. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_CYLINDER] = new OIMO.SphereCylinderCollisionDetector(false);
  93159. // TETRA add
  93160. this.detectors[OIMO.SHAPE_TETRA][OIMO.SHAPE_TETRA] = new OIMO.TetraTetraCollisionDetector();
  93161. this.randX = 65535;
  93162. this.randA = 98765;
  93163. this.randB = 123456789;
  93164. //this.maxIslandRigidBodies = 64;
  93165. this.islandRigidBodies = [];
  93166. //this.islandRigidBodies.length = this.maxIslandRigidBodies;
  93167. this.islandStack = [];
  93168. //this.islandStack.length = this.maxIslandRigidBodies;
  93169. //this.maxIslandConstraints = 128;
  93170. this.islandConstraints = [];
  93171. //this.islandConstraints.length = this.maxIslandConstraints;
  93172. };
  93173. OIMO.World.prototype = {
  93174. constructor: OIMO.World,
  93175. /**
  93176. * Reset the randomizer and remove all rigid bodies, shapes, joints and any object from the world.
  93177. */
  93178. clear: function () {
  93179. this.randX = 65535;
  93180. while (this.joints !== null) {
  93181. this.removeJoint(this.joints);
  93182. }
  93183. while (this.contacts !== null) {
  93184. this.removeContact(this.contacts);
  93185. }
  93186. while (this.rigidBodies !== null) {
  93187. this.removeRigidBody(this.rigidBodies);
  93188. }
  93189. OIMO.nextID = 0;
  93190. OIMO.proxyID = 0;
  93191. },
  93192. /**
  93193. * I'll add a rigid body to the world.
  93194. * Rigid body that has been added will be the operands of each step.
  93195. * @param rigidBody Rigid body that you want to add
  93196. */
  93197. addRigidBody: function (rigidBody) {
  93198. if (rigidBody.parent) {
  93199. OIMO.Error("World", "It is not possible to be added to more than one world one of the rigid body");
  93200. }
  93201. rigidBody.parent = this;
  93202. rigidBody.awake();
  93203. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  93204. this.addShape(shape);
  93205. }
  93206. if (this.rigidBodies !== null) (this.rigidBodies.prev = rigidBody).next = this.rigidBodies;
  93207. this.rigidBodies = rigidBody;
  93208. this.numRigidBodies++;
  93209. },
  93210. /**
  93211. * I will remove the rigid body from the world.
  93212. * Rigid body that has been deleted is excluded from the calculation on a step-by-step basis.
  93213. * @param rigidBody Rigid body to be removed
  93214. */
  93215. removeRigidBody: function (rigidBody) {
  93216. var remove = rigidBody;
  93217. if (remove.parent !== this) return;
  93218. remove.awake();
  93219. var js = remove.jointLink;
  93220. while (js != null) {
  93221. var joint = js.joint;
  93222. js = js.next;
  93223. this.removeJoint(joint);
  93224. }
  93225. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  93226. this.removeShape(shape);
  93227. }
  93228. var prev = remove.prev;
  93229. var next = remove.next;
  93230. if (prev !== null) prev.next = next;
  93231. if (next !== null) next.prev = prev;
  93232. if (this.rigidBodies == remove) this.rigidBodies = next;
  93233. remove.prev = null;
  93234. remove.next = null;
  93235. remove.parent = null;
  93236. this.numRigidBodies--;
  93237. },
  93238. getByName: function (name) {
  93239. var result = null;
  93240. var body = this.rigidBodies;
  93241. while (body !== null) {
  93242. if (body.name !== " " && body.name === name) result = body;
  93243. body = body.next;
  93244. }
  93245. var joint = this.joints;
  93246. while (joint !== null) {
  93247. if (joint.name !== "" && joint.name === name) result = joint;
  93248. joint = joint.next;
  93249. }
  93250. return result;
  93251. },
  93252. /**
  93253. * I'll add a shape to the world..
  93254. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  93255. * Shape will be added to the world automatically, please do not call from outside this method.
  93256. * @param shape Shape you want to add
  93257. */
  93258. addShape: function (shape) {
  93259. if (!shape.parent || !shape.parent.parent) {
  93260. OIMO.Error("World", "It is not possible to be added alone to shape world");
  93261. }
  93262. shape.proxy = this.broadPhase.createProxy(shape);
  93263. shape.updateProxy();
  93264. this.broadPhase.addProxy(shape.proxy);
  93265. },
  93266. /**
  93267. * I will remove the shape from the world.
  93268. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  93269. * Shape will be added to the world automatically, please do not call from outside this method.
  93270. * @param shape Shape you want to delete
  93271. */
  93272. removeShape: function (shape) {
  93273. this.broadPhase.removeProxy(shape.proxy);
  93274. shape.proxy = null;
  93275. },
  93276. /**
  93277. * I'll add a joint to the world.
  93278. * Joint that has been added will be the operands of each step.
  93279. * @param shape Joint to be added
  93280. */
  93281. addJoint: function (joint) {
  93282. if (joint.parent) {
  93283. OIMO.Error("World", "It is not possible to be added to more than one world one of the joint");
  93284. }
  93285. if (this.joints != null) (this.joints.prev = joint).next = this.joints;
  93286. this.joints = joint;
  93287. joint.parent = this;
  93288. this.numJoints++;
  93289. joint.awake();
  93290. joint.attach();
  93291. },
  93292. /**
  93293. * I will remove the joint from the world.
  93294. * Joint that has been added will be the operands of each step.
  93295. * @param shape Joint to be deleted
  93296. */
  93297. removeJoint: function (joint) {
  93298. var remove = joint;
  93299. var prev = remove.prev;
  93300. var next = remove.next;
  93301. if (prev !== null) prev.next = next;
  93302. if (next !== null) next.prev = prev;
  93303. if (this.joints == remove) this.joints = next;
  93304. remove.prev = null;
  93305. remove.next = null;
  93306. this.numJoints--;
  93307. remove.awake();
  93308. remove.detach();
  93309. remove.parent = null;
  93310. },
  93311. worldscale: function (scale) {
  93312. OIMO.WORLD_SCALE = scale || 100;
  93313. OIMO.INV_SCALE = 1 / OIMO.WORLD_SCALE;
  93314. },
  93315. addContact: function (s1, s2) {
  93316. var newContact;
  93317. if (this.unusedContacts !== null) {
  93318. newContact = this.unusedContacts;
  93319. this.unusedContacts = this.unusedContacts.next;
  93320. } else {
  93321. newContact = new OIMO.Contact();
  93322. }
  93323. newContact.attach(s1, s2);
  93324. newContact.detector = this.detectors[s1.type][s2.type];
  93325. if (this.contacts) (this.contacts.prev = newContact).next = this.contacts;
  93326. this.contacts = newContact;
  93327. this.numContacts++;
  93328. },
  93329. removeContact: function (contact) {
  93330. var prev = contact.prev;
  93331. var next = contact.next;
  93332. if (next) next.prev = prev;
  93333. if (prev) prev.next = next;
  93334. if (this.contacts == contact) this.contacts = next;
  93335. contact.prev = null;
  93336. contact.next = null;
  93337. contact.detach();
  93338. contact.next = this.unusedContacts;
  93339. this.unusedContacts = contact;
  93340. this.numContacts--;
  93341. },
  93342. checkContact: function (name1, name2) {
  93343. var n1, n2;
  93344. var contact = this.contacts;
  93345. while (contact !== null) {
  93346. n1 = contact.body1.name || ' ';
  93347. n2 = contact.body2.name || ' ';
  93348. if ((n1 == name1 && n2 == name2) || (n2 == name1 && n1 == name2)) { if (contact.touching) return true; else return false; }
  93349. else contact = contact.next;
  93350. }
  93351. return false;
  93352. },
  93353. callSleep: function (body) {
  93354. if (!body.allowSleep) return false;
  93355. if (body.linearVelocity.lengthSq() > 0.04) return false;
  93356. if (body.angularVelocity.lengthSq() > 0.25) return false;
  93357. return true;
  93358. },
  93359. /**
  93360. * I will proceed only time step seconds time of World.
  93361. */
  93362. step: function () {
  93363. var time0, time1, time2, time3;
  93364. var stat = !this.isNoStat ? true : false;
  93365. if (stat) time0 = OIMO.now();
  93366. var body = this.rigidBodies;
  93367. while (body !== null) {
  93368. body.addedToIsland = false;
  93369. if (body.sleeping) {
  93370. if (
  93371. body.linearVelocity.testZero() ||
  93372. body.angularVelocity.testZero() ||
  93373. body.position.testDiff(body.sleepPosition) ||
  93374. body.orientation.testDiff(body.sleepOrientation)
  93375. ) body.awake(); // awake the body
  93376. }
  93377. body = body.next;
  93378. }
  93379. //------------------------------------------------------
  93380. // UPDATE CONTACT
  93381. //------------------------------------------------------
  93382. // broad phase
  93383. if (stat) time1 = OIMO.now();
  93384. this.broadPhase.detectPairs();
  93385. var pairs = this.broadPhase.pairs;
  93386. var i = this.broadPhase.numPairs;
  93387. //do{
  93388. while (i--) {
  93389. //for(var i=0, l=numPairs; i<l; i++){
  93390. var pair = pairs[i];
  93391. var s1;
  93392. var s2;
  93393. if (pair.shape1.id < pair.shape2.id) {
  93394. s1 = pair.shape1;
  93395. s2 = pair.shape2;
  93396. } else {
  93397. s1 = pair.shape2;
  93398. s2 = pair.shape1;
  93399. }
  93400. var link;
  93401. if (s1.numContacts < s2.numContacts) link = s1.contactLink;
  93402. else link = s2.contactLink;
  93403. var exists = false;
  93404. while (link) {
  93405. var contact = link.contact;
  93406. if (contact.shape1 == s1 && contact.shape2 == s2) {
  93407. contact.persisting = true;
  93408. exists = true;// contact already exists
  93409. break;
  93410. }
  93411. link = link.next;
  93412. }
  93413. if (!exists) {
  93414. this.addContact(s1, s2);
  93415. }
  93416. }// while(i-- >0);
  93417. if (stat) {
  93418. time2 = OIMO.now();
  93419. this.performance.broadPhaseTime = time2 - time1;
  93420. }
  93421. // update & narrow phase
  93422. this.numContactPoints = 0;
  93423. contact = this.contacts;
  93424. while (contact !== null) {
  93425. if (!contact.persisting) {
  93426. if (contact.shape1.aabb.intersectTest(contact.shape2.aabb)) {
  93427. /*var aabb1=contact.shape1.aabb;
  93428. var aabb2=contact.shape2.aabb;
  93429. if(
  93430. aabb1.minX>aabb2.maxX || aabb1.maxX<aabb2.minX ||
  93431. aabb1.minY>aabb2.maxY || aabb1.maxY<aabb2.minY ||
  93432. aabb1.minZ>aabb2.maxZ || aabb1.maxZ<aabb2.minZ
  93433. ){*/
  93434. var next = contact.next;
  93435. this.removeContact(contact);
  93436. contact = next;
  93437. continue;
  93438. }
  93439. }
  93440. var b1 = contact.body1;
  93441. var b2 = contact.body2;
  93442. if (b1.isDynamic && !b1.sleeping || b2.isDynamic && !b2.sleeping) {
  93443. contact.updateManifold();
  93444. }
  93445. this.numContactPoints += contact.manifold.numPoints;
  93446. contact.persisting = false;
  93447. contact.constraint.addedToIsland = false;
  93448. contact = contact.next;
  93449. }
  93450. if (stat) {
  93451. time3 = OIMO.now();
  93452. this.performance.narrowPhaseTime = time3 - time2;
  93453. }
  93454. //------------------------------------------------------
  93455. // SOLVE ISLANDS
  93456. //------------------------------------------------------
  93457. var invTimeStep = 1 / this.timeStep;
  93458. //var body;
  93459. var joint;
  93460. var constraint;
  93461. //var num;
  93462. for (joint = this.joints; joint !== null; joint = joint.next) {
  93463. joint.addedToIsland = false;
  93464. }
  93465. // clear old island array
  93466. this.islandRigidBodies = [];
  93467. this.islandConstraints = [];
  93468. this.islandStack = [];
  93469. // expand island buffers
  93470. /*if(this.maxIslandRigidBodies<this.numRigidBodies){
  93471. this.maxIslandRigidBodies=this.numRigidBodies<<1;
  93472. //this.maxIslandRigidBodies=this.numRigidBodies*2;
  93473. this.islandRigidBodies=[];
  93474. this.islandStack=[];
  93475. this.islandRigidBodies.length = this.maxIslandRigidBodies;
  93476. this.islandStack.length = this.maxIslandRigidBodies;
  93477. }
  93478. var numConstraints=this.numJoints+this.numContacts;
  93479. if(this.maxIslandConstraints<numConstraints){
  93480. this.maxIslandConstraints=numConstraints<<1;
  93481. //this.maxIslandConstraints=numConstraints*2;
  93482. this.islandConstraints=[];
  93483. this.islandConstraints.length = this.maxIslandConstraints;
  93484. }*/
  93485. time1 = OIMO.now();
  93486. this.numIslands = 0;
  93487. // build and solve simulation islands
  93488. for (var base = this.rigidBodies; base !== null; base = base.next) {
  93489. if (base.addedToIsland || base.isStatic || base.sleeping) continue;// ignore
  93490. if (base.isLonely()) {// update single body
  93491. if (base.isDynamic) {
  93492. base.linearVelocity.addTime(this.gravity, this.timeStep);
  93493. /*base.linearVelocity.x+=this.gravity.x*this.timeStep;
  93494. base.linearVelocity.y+=this.gravity.y*this.timeStep;
  93495. base.linearVelocity.z+=this.gravity.z*this.timeStep;*/
  93496. }
  93497. if (this.callSleep(base)) {
  93498. base.sleepTime += this.timeStep;
  93499. if (base.sleepTime > 0.5) base.sleep();
  93500. else base.updatePosition(this.timeStep);
  93501. } else {
  93502. base.sleepTime = 0;
  93503. base.updatePosition(this.timeStep);
  93504. }
  93505. this.numIslands++;
  93506. continue;
  93507. }
  93508. var islandNumRigidBodies = 0;
  93509. var islandNumConstraints = 0;
  93510. var stackCount = 1;
  93511. // add rigid body to stack
  93512. this.islandStack[0] = base;
  93513. base.addedToIsland = true;
  93514. // build an island
  93515. do {
  93516. // get rigid body from stack
  93517. body = this.islandStack[--stackCount];
  93518. this.islandStack[stackCount] = null;
  93519. body.sleeping = false;
  93520. // add rigid body to the island
  93521. this.islandRigidBodies[islandNumRigidBodies++] = body;
  93522. if (body.isStatic) continue;
  93523. // search connections
  93524. for (var cs = body.contactLink; cs !== null; cs = cs.next) {
  93525. var contact = cs.contact;
  93526. constraint = contact.constraint;
  93527. if (constraint.addedToIsland || !contact.touching) continue;// ignore
  93528. // add constraint to the island
  93529. this.islandConstraints[islandNumConstraints++] = constraint;
  93530. constraint.addedToIsland = true;
  93531. var next = cs.body;
  93532. if (next.addedToIsland) continue;
  93533. // add rigid body to stack
  93534. this.islandStack[stackCount++] = next;
  93535. next.addedToIsland = true;
  93536. }
  93537. for (var js = body.jointLink; js !== null; js = js.next) {
  93538. constraint = js.joint;
  93539. if (constraint.addedToIsland) continue;// ignore
  93540. // add constraint to the island
  93541. this.islandConstraints[islandNumConstraints++] = constraint;
  93542. constraint.addedToIsland = true;
  93543. next = js.body;
  93544. if (next.addedToIsland || !next.isDynamic) continue;
  93545. // add rigid body to stack
  93546. this.islandStack[stackCount++] = next;
  93547. next.addedToIsland = true;
  93548. }
  93549. } while (stackCount != 0);
  93550. // update velocities
  93551. var gVel = new OIMO.Vec3().addTime(this.gravity, this.timeStep);
  93552. /*var gx=this.gravity.x*this.timeStep;
  93553. var gy=this.gravity.y*this.timeStep;
  93554. var gz=this.gravity.z*this.timeStep;*/
  93555. var j = islandNumRigidBodies;
  93556. while (j--) {
  93557. //or(var j=0, l=islandNumRigidBodies; j<l; j++){
  93558. body = this.islandRigidBodies[j];
  93559. if (body.isDynamic) {
  93560. body.linearVelocity.addEqual(gVel);
  93561. /*body.linearVelocity.x+=gx;
  93562. body.linearVelocity.y+=gy;
  93563. body.linearVelocity.z+=gz;*/
  93564. }
  93565. }
  93566. // randomizing order
  93567. if (this.enableRandomizer) {
  93568. //for(var j=1, l=islandNumConstraints; j<l; j++){
  93569. j = islandNumConstraints;
  93570. while (j--) {
  93571. if (j !== 0) {
  93572. var swap = (this.randX = (this.randX * this.randA + this.randB & 0x7fffffff)) / 2147483648.0 * j | 0;
  93573. constraint = this.islandConstraints[j];
  93574. this.islandConstraints[j] = this.islandConstraints[swap];
  93575. this.islandConstraints[swap] = constraint;
  93576. }
  93577. }
  93578. }
  93579. // solve contraints
  93580. j = islandNumConstraints;
  93581. while (j--) {
  93582. //for(j=0, l=islandNumConstraints; j<l; j++){
  93583. this.islandConstraints[j].preSolve(this.timeStep, invTimeStep);// pre-solve
  93584. }
  93585. var k = this.numIterations;
  93586. while (k--) {
  93587. //for(var k=0, l=this.numIterations; k<l; k++){
  93588. j = islandNumConstraints;
  93589. while (j--) {
  93590. //for(j=0, m=islandNumConstraints; j<m; j++){
  93591. this.islandConstraints[j].solve();// main-solve
  93592. }
  93593. }
  93594. j = islandNumConstraints;
  93595. while (j--) {
  93596. //for(j=0, l=islandNumConstraints; j<l; j++){
  93597. this.islandConstraints[j].postSolve();// post-solve
  93598. this.islandConstraints[j] = null;// gc
  93599. }
  93600. // sleeping check
  93601. var sleepTime = 10;
  93602. j = islandNumRigidBodies;
  93603. while (j--) {
  93604. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  93605. body = this.islandRigidBodies[j];
  93606. if (this.callSleep(body)) {
  93607. body.sleepTime += this.timeStep;
  93608. if (body.sleepTime < sleepTime) sleepTime = body.sleepTime;
  93609. } else {
  93610. body.sleepTime = 0;
  93611. sleepTime = 0;
  93612. continue;
  93613. }
  93614. }
  93615. if (sleepTime > 0.5) {
  93616. // sleep the island
  93617. j = islandNumRigidBodies;
  93618. while (j--) {
  93619. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  93620. this.islandRigidBodies[j].sleep();
  93621. this.islandRigidBodies[j] = null;// gc
  93622. }
  93623. } else {
  93624. // update positions
  93625. j = islandNumRigidBodies;
  93626. while (j--) {
  93627. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  93628. this.islandRigidBodies[j].updatePosition(this.timeStep);
  93629. this.islandRigidBodies[j] = null;// gc
  93630. }
  93631. }
  93632. this.numIslands++;
  93633. }
  93634. if (stat) {
  93635. time2 = OIMO.now();
  93636. this.performance.solvingTime = time2 - time1;
  93637. //------------------------------------------------------
  93638. // END SIMULATION
  93639. //------------------------------------------------------
  93640. time2 = OIMO.now();
  93641. // fps update
  93642. this.performance.upfps();
  93643. this.performance.totalTime = time2 - time0;
  93644. }
  93645. }
  93646. }
  93647. /**
  93648. * The class of rigid body.
  93649. * Rigid body has the shape of a single or multiple collision processing,
  93650. * I can set the parameters individually.
  93651. * @author saharan
  93652. */
  93653. OIMO.RigidBody = function (x, y, z, rad, ax, ay, az) {
  93654. this.name = " ";
  93655. // The maximum number of shapes that can be added to a one rigid.
  93656. this.MAX_SHAPES = 64;//64;
  93657. this.prev = null;
  93658. this.next = null;
  93659. // I represent the kind of rigid body.
  93660. // Please do not change from the outside this variable.
  93661. // If you want to change the type of rigid body, always
  93662. // Please specify the type you want to set the arguments of setupMass method.
  93663. this.type = OIMO.BODY_NULL;
  93664. this.massInfo = new OIMO.MassInfo();
  93665. // It is the world coordinate of the center of gravity.
  93666. this.position = new OIMO.Vec3(x, y, z);
  93667. this.orientation = this.rotationAxisToQuad(rad || 0, ax || 0, ay || 0, az || 0);
  93668. this.newPosition = new OIMO.Vec3();
  93669. this.controlPos = false;
  93670. this.newOrientation = new OIMO.Quat();
  93671. this.newRotation = new OIMO.Vec3();
  93672. this.currentRotation = new OIMO.Vec3();
  93673. this.controlRot = false;
  93674. this.controlRotInTime = false;
  93675. // Is the translational velocity.
  93676. this.linearVelocity = new OIMO.Vec3();
  93677. // Is the angular velocity.
  93678. this.angularVelocity = new OIMO.Vec3();
  93679. // return matrix for three.js
  93680. this.matrix = new OIMO.Mat44();
  93681. //--------------------------------------------
  93682. // Please do not change from the outside this variables.
  93683. //--------------------------------------------
  93684. // It is a world that rigid body has been added.
  93685. this.parent = null;
  93686. this.contactLink = null;
  93687. this.numContacts = 0;
  93688. // An array of shapes that are included in the rigid body.
  93689. this.shapes = null;
  93690. // The number of shapes that are included in the rigid body.
  93691. this.numShapes = 0;
  93692. // It is the link array of joint that is connected to the rigid body.
  93693. this.jointLink = null;
  93694. // The number of joints that are connected to the rigid body.
  93695. this.numJoints = 0;
  93696. // It is the world coordinate of the center of gravity in the sleep just before.
  93697. this.sleepPosition = new OIMO.Vec3();
  93698. // It is a quaternion that represents the attitude of sleep just before.
  93699. this.sleepOrientation = new OIMO.Quat();
  93700. // I will show this rigid body to determine whether it is a rigid body static.
  93701. this.isStatic = false;
  93702. // I indicates that this rigid body to determine whether it is a rigid body dynamic.
  93703. this.isDynamic = false;
  93704. // It is a rotation matrix representing the orientation.
  93705. this.rotation = new OIMO.Mat33();
  93706. //--------------------------------------------
  93707. // It will be recalculated automatically from the shape, which is included.
  93708. //--------------------------------------------
  93709. // This is the weight.
  93710. this.mass = NaN;
  93711. // It is the reciprocal of the mass.
  93712. this.inverseMass = NaN;
  93713. // It is the inverse of the inertia tensor in the world system.
  93714. this.inverseInertia = new OIMO.Mat33();
  93715. // It is the inertia tensor in the initial state.
  93716. this.localInertia = new OIMO.Mat33();
  93717. // It is the inverse of the inertia tensor in the initial state.
  93718. this.inverseLocalInertia = new OIMO.Mat33();
  93719. // I indicates rigid body whether it has been added to the simulation Island.
  93720. this.addedToIsland = false;
  93721. // It shows how to sleep rigid body.
  93722. this.allowSleep = true;
  93723. // This is the time from when the rigid body at rest.
  93724. this.sleepTime = 0;
  93725. // I shows rigid body to determine whether it is a sleep state.
  93726. this.sleeping = false;
  93727. };
  93728. OIMO.RigidBody.prototype = {
  93729. constructor: OIMO.RigidBody,
  93730. /**
  93731. * I'll add a shape to rigid body.
  93732. * If you add a shape, please call the setupMass method to step up to the start of the next.
  93733. * @param shape shape to Add
  93734. */
  93735. addShape: function (shape) {
  93736. if (shape.parent) OIMO.Error("RigidBody", "It is not possible that you add to the multi-rigid body the shape of one");
  93737. if (this.shapes != null) (this.shapes.prev = shape).next = this.shapes;
  93738. this.shapes = shape;
  93739. shape.parent = this;
  93740. if (this.parent) this.parent.addShape(shape);
  93741. this.numShapes++;
  93742. },
  93743. /**
  93744. * I will delete the shape from the rigid body.
  93745. * If you delete a shape, please call the setupMass method to step up to the start of the next.
  93746. * @param shape shape to Delete
  93747. */
  93748. removeShape: function (shape) {
  93749. var remove = shape;
  93750. if (remove.parent != this) return;
  93751. var prev = remove.prev;
  93752. var next = remove.next;
  93753. if (prev != null) prev.next = next;
  93754. if (next != null) next.prev = prev;
  93755. if (this.shapes == remove) this.shapes = next;
  93756. remove.prev = null;
  93757. remove.next = null;
  93758. remove.parent = null;
  93759. if (this.parent) this.parent.removeShape(remove);
  93760. this.numShapes--;
  93761. },
  93762. remove: function () {
  93763. this.dispose();
  93764. },
  93765. dispose: function () {
  93766. this.parent.removeRigidBody(this);
  93767. },
  93768. checkContact: function (name) {
  93769. this.parent.checkContact(this.name, name);
  93770. },
  93771. /**
  93772. * Calulates mass datas(center of gravity, mass, moment inertia, etc...).
  93773. * If the parameter type is set to BODY_STATIC, the rigid body will be fixed to the space.
  93774. * If the parameter adjustPosition is set to true, the shapes' relative positions and
  93775. * the rigid body's position will be adjusted to the center of gravity.
  93776. * @param type
  93777. * @param adjustPosition
  93778. */
  93779. setupMass: function (type, AdjustPosition) {
  93780. var adjustPosition = (AdjustPosition !== undefined) ? AdjustPosition : true;
  93781. this.type = type || OIMO.BODY_DYNAMIC;
  93782. this.isDynamic = this.type == OIMO.BODY_DYNAMIC;
  93783. this.isStatic = this.type == OIMO.BODY_STATIC;
  93784. this.mass = 0;
  93785. this.localInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  93786. var te = this.localInertia.elements;
  93787. //
  93788. var tmpM = new OIMO.Mat33();
  93789. var tmpV = new OIMO.Vec3();
  93790. for (var shape = this.shapes; shape != null; shape = shape.next) {
  93791. shape.calculateMassInfo(this.massInfo);
  93792. var shapeMass = this.massInfo.mass;
  93793. var relX = shape.relativePosition.x;
  93794. var relY = shape.relativePosition.y;
  93795. var relZ = shape.relativePosition.z;
  93796. /*tmpV.x+=relX*shapeMass;
  93797. tmpV.y+=relY*shapeMass;
  93798. tmpV.z+=relZ*shapeMass;*/
  93799. tmpV.addScale(shape.relativePosition, shapeMass);
  93800. this.mass += shapeMass;
  93801. this.rotateInertia(shape.relativeRotation, this.massInfo.inertia, tmpM);
  93802. this.localInertia.addEqual(tmpM);
  93803. // add offset inertia
  93804. te[0] += shapeMass * (relY * relY + relZ * relZ);
  93805. te[4] += shapeMass * (relX * relX + relZ * relZ);
  93806. te[8] += shapeMass * (relX * relX + relY * relY);
  93807. var xy = shapeMass * relX * relY;
  93808. var yz = shapeMass * relY * relZ;
  93809. var zx = shapeMass * relZ * relX;
  93810. te[1] -= xy;
  93811. te[3] -= xy;
  93812. te[2] -= yz;
  93813. te[6] -= yz;
  93814. te[5] -= zx;
  93815. te[7] -= zx;
  93816. }
  93817. this.inverseMass = 1 / this.mass;
  93818. tmpV.scaleEqual(this.inverseMass);
  93819. if (adjustPosition) {
  93820. this.position.addEqual(tmpV);
  93821. for (shape = this.shapes; shape != null; shape = shape.next) {
  93822. shape.relativePosition.subEqual(tmpV);
  93823. }
  93824. // subtract offset inertia
  93825. relX = tmpV.x;
  93826. relY = tmpV.y;
  93827. relZ = tmpV.z;
  93828. //var te = this.localInertia.elements;
  93829. te[0] -= this.mass * (relY * relY + relZ * relZ);
  93830. te[4] -= this.mass * (relX * relX + relZ * relZ);
  93831. te[8] -= this.mass * (relX * relX + relY * relY);
  93832. xy = this.mass * relX * relY;
  93833. yz = this.mass * relY * relZ;
  93834. zx = this.mass * relZ * relX;
  93835. te[1] += xy;
  93836. te[3] += xy;
  93837. te[2] += yz;
  93838. te[6] += yz;
  93839. te[5] += zx;
  93840. te[7] += zx;
  93841. }
  93842. this.inverseLocalInertia.invert(this.localInertia);
  93843. if (this.type == OIMO.BODY_STATIC) {
  93844. this.inverseMass = 0;
  93845. this.inverseLocalInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  93846. }
  93847. this.syncShapes();
  93848. this.awake();
  93849. },
  93850. /**
  93851. * Awake the rigid body.
  93852. */
  93853. awake: function () {
  93854. if (!this.allowSleep || !this.sleeping) return;
  93855. this.sleeping = false;
  93856. this.sleepTime = 0;
  93857. // awake connected constraints
  93858. var cs = this.contactLink;
  93859. while (cs != null) {
  93860. cs.body.sleepTime = 0;
  93861. cs.body.sleeping = false;
  93862. cs = cs.next;
  93863. }
  93864. var js = this.jointLink;
  93865. while (js != null) {
  93866. js.body.sleepTime = 0;
  93867. js.body.sleeping = false;
  93868. js = js.next;
  93869. }
  93870. for (var shape = this.shapes; shape != null; shape = shape.next) {
  93871. shape.updateProxy();
  93872. }
  93873. },
  93874. /**
  93875. * Sleep the rigid body.
  93876. */
  93877. sleep: function () {
  93878. if (!this.allowSleep || this.sleeping) return;
  93879. this.linearVelocity.set(0, 0, 0);
  93880. this.angularVelocity.set(0, 0, 0);
  93881. this.sleepPosition.copy(this.position);
  93882. this.sleepOrientation.copy(this.orientation);
  93883. /*this.linearVelocity.x=0;
  93884. this.linearVelocity.y=0;
  93885. this.linearVelocity.z=0;
  93886. this.angularVelocity.x=0;
  93887. this.angularVelocity.y=0;
  93888. this.angularVelocity.z=0;
  93889. this.sleepPosition.x=this.position.x;
  93890. this.sleepPosition.y=this.position.y;
  93891. this.sleepPosition.z=this.position.z;*/
  93892. /*this.sleepOrientation.s=this.orientation.s;
  93893. this.sleepOrientation.x=this.orientation.x;
  93894. this.sleepOrientation.y=this.orientation.y;
  93895. this.sleepOrientation.z=this.orientation.z;*/
  93896. this.sleepTime = 0;
  93897. this.sleeping = true;
  93898. for (var shape = this.shapes; shape != null; shape = shape.next) {
  93899. shape.updateProxy();
  93900. }
  93901. },
  93902. /**
  93903. * Get whether the rigid body has not any connection with others.
  93904. * @return
  93905. */
  93906. isLonely: function () {
  93907. return this.numJoints == 0 && this.numContacts == 0;
  93908. },
  93909. /**
  93910. * The time integration of the motion of a rigid body, you can update the information such as the shape.
  93911. * This method is invoked automatically when calling the step of the World,
  93912. * There is no need to call from outside usually.
  93913. * @param timeStep time
  93914. */
  93915. updatePosition: function (timeStep) {
  93916. switch (this.type) {
  93917. case OIMO.BODY_STATIC:
  93918. this.linearVelocity.set(0, 0, 0);
  93919. this.angularVelocity.set(0, 0, 0);
  93920. // ONLY FOR TEST
  93921. if (this.controlPos) {
  93922. this.position.copy(this.newPosition);
  93923. this.controlPos = false;
  93924. }
  93925. if (this.controlRot) {
  93926. this.orientation.copy(this.newOrientation);
  93927. this.controlRot = false;
  93928. }
  93929. /*this.linearVelocity.x=0;
  93930. this.linearVelocity.y=0;
  93931. this.linearVelocity.z=0;
  93932. this.angularVelocity.x=0;
  93933. this.angularVelocity.y=0;
  93934. this.angularVelocity.z=0;*/
  93935. break;
  93936. case OIMO.BODY_DYNAMIC:
  93937. if (this.controlPos) {
  93938. this.angularVelocity.set(0, 0, 0);
  93939. this.linearVelocity.set(0, 0, 0);
  93940. this.linearVelocity.x = (this.newPosition.x - this.position.x) / timeStep;
  93941. this.linearVelocity.y = (this.newPosition.y - this.position.y) / timeStep;
  93942. this.linearVelocity.z = (this.newPosition.z - this.position.z) / timeStep;
  93943. this.controlPos = false;
  93944. }
  93945. if (this.controlRot) {
  93946. this.angularVelocity.set(0, 0, 0);
  93947. this.orientation.copy(this.newOrientation);
  93948. //var t=timeStep//*0.5;
  93949. //var q = new OIMO.Quat();
  93950. //q.sub(this.newOrientation, this.orientation);
  93951. //q.normalize(q);
  93952. /*q.s = (this.newOrientation.s - this.orientation.s)/t;
  93953. q.x = (this.newOrientation.x - this.orientation.x)/t;
  93954. q.y = (this.newOrientation.y - this.orientation.y)/t;
  93955. q.z = (this.newOrientation.z - this.orientation.z)/t;*/
  93956. //this.angularVelocity.applyQuaternion(q);
  93957. //this.angularVelocity.x = this.angularVelocity.x/t;
  93958. //this.angularVelocity.y = this.angularVelocity.y/t;
  93959. //this.angularVelocity.z = this.angularVelocity.z/t;
  93960. this.controlRot = false;
  93961. }
  93962. this.position.addTime(this.linearVelocity, timeStep);
  93963. this.orientation.addTime(this.angularVelocity, timeStep);
  93964. break;
  93965. default: OIMO.Error("RigidBody", "Invalid type.");
  93966. }
  93967. this.syncShapes();
  93968. },
  93969. rotateInertia: function (rot, inertia, out) {
  93970. var tm1 = rot.elements;
  93971. var tm2 = inertia.elements;
  93972. var a0 = tm1[0], a3 = tm1[3], a6 = tm1[6];
  93973. var a1 = tm1[1], a4 = tm1[4], a7 = tm1[7];
  93974. var a2 = tm1[2], a5 = tm1[5], a8 = tm1[8];
  93975. var b0 = tm2[0], b3 = tm2[3], b6 = tm2[6];
  93976. var b1 = tm2[1], b4 = tm2[4], b7 = tm2[7];
  93977. var b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  93978. var e00 = a0 * b0 + a1 * b3 + a2 * b6;
  93979. var e01 = a0 * b1 + a1 * b4 + a2 * b7;
  93980. var e02 = a0 * b2 + a1 * b5 + a2 * b8;
  93981. var e10 = a3 * b0 + a4 * b3 + a5 * b6;
  93982. var e11 = a3 * b1 + a4 * b4 + a5 * b7;
  93983. var e12 = a3 * b2 + a4 * b5 + a5 * b8;
  93984. var e20 = a6 * b0 + a7 * b3 + a8 * b6;
  93985. var e21 = a6 * b1 + a7 * b4 + a8 * b7;
  93986. var e22 = a6 * b2 + a7 * b5 + a8 * b8;
  93987. var oe = out.elements;
  93988. oe[0] = e00 * a0 + e01 * a1 + e02 * a2;
  93989. oe[1] = e00 * a3 + e01 * a4 + e02 * a5;
  93990. oe[2] = e00 * a6 + e01 * a7 + e02 * a8;
  93991. oe[3] = e10 * a0 + e11 * a1 + e12 * a2;
  93992. oe[4] = e10 * a3 + e11 * a4 + e12 * a5;
  93993. oe[5] = e10 * a6 + e11 * a7 + e12 * a8;
  93994. oe[6] = e20 * a0 + e21 * a1 + e22 * a2;
  93995. oe[7] = e20 * a3 + e21 * a4 + e22 * a5;
  93996. oe[8] = e20 * a6 + e21 * a7 + e22 * a8;
  93997. },
  93998. syncShapes: function () {
  93999. var s = this.orientation.s;
  94000. var x = this.orientation.x;
  94001. var y = this.orientation.y;
  94002. var z = this.orientation.z;
  94003. var x2 = 2 * x;
  94004. var y2 = 2 * y;
  94005. var z2 = 2 * z;
  94006. var xx = x * x2;
  94007. var yy = y * y2;
  94008. var zz = z * z2;
  94009. var xy = x * y2;
  94010. var yz = y * z2;
  94011. var xz = x * z2;
  94012. var sx = s * x2;
  94013. var sy = s * y2;
  94014. var sz = s * z2;
  94015. var tr = this.rotation.elements;
  94016. tr[0] = 1 - yy - zz;
  94017. tr[1] = xy - sz;
  94018. tr[2] = xz + sy;
  94019. tr[3] = xy + sz;
  94020. tr[4] = 1 - xx - zz;
  94021. tr[5] = yz - sx;
  94022. tr[6] = xz - sy;
  94023. tr[7] = yz + sx;
  94024. tr[8] = 1 - xx - yy;
  94025. this.rotateInertia(this.rotation, this.inverseLocalInertia, this.inverseInertia);
  94026. for (var shape = this.shapes; shape != null; shape = shape.next) {
  94027. //var relPos=shape.relativePosition;
  94028. //var relRot=shape.relativeRotation;
  94029. //var rot=shape.rotation;
  94030. /*var lx=relPos.x;
  94031. var ly=relPos.y;
  94032. var lz=relPos.z;
  94033. shape.position.x=this.position.x+lx*tr[0]+ly*tr[1]+lz*tr[2];
  94034. shape.position.y=this.position.y+lx*tr[3]+ly*tr[4]+lz*tr[5];
  94035. shape.position.z=this.position.z+lx*tr[6]+ly*tr[7]+lz*tr[8];*/
  94036. shape.position.mul(this.position, shape.relativePosition, this.rotation);
  94037. //shape.rotation.mul(shape.relativeRotation,this.rotation);
  94038. // add by QuaziKb
  94039. shape.rotation.mul(this.rotation, shape.relativeRotation);
  94040. shape.updateProxy();
  94041. }
  94042. },
  94043. applyImpulse: function (position, force) {
  94044. this.linearVelocity.addScale(force, this.inverseMass);
  94045. /*this.linearVelocity.x+=force.x*this.inverseMass;
  94046. this.linearVelocity.y+=force.y*this.inverseMass;
  94047. this.linearVelocity.z+=force.z*this.inverseMass;*/
  94048. var rel = new OIMO.Vec3();
  94049. rel.sub(position, this.position).cross(rel, force).mulMat(this.inverseInertia, rel);
  94050. this.angularVelocity.addEqual(rel);
  94051. /*this.angularVelocity.x+=rel.x;
  94052. this.angularVelocity.y+=rel.y;
  94053. this.angularVelocity.z+=rel.z;*/
  94054. },
  94055. //---------------------------------------------
  94056. //
  94057. // FOR THREE JS
  94058. //
  94059. //---------------------------------------------
  94060. rotationVectToQuad: function (rot) {
  94061. var r = OIMO.EulerToAxis(rot.x * OIMO.degtorad, rot.y * OIMO.degtorad, rot.z * OIMO.degtorad);
  94062. return this.rotationAxisToQuad(r[0], r[1], r[2], r[3]);
  94063. },
  94064. rotationAxisToQuad: function (rad, ax, ay, az) { // in radian
  94065. var len = ax * ax + ay * ay + az * az;
  94066. if (len > 0) {
  94067. len = 1 / OIMO.sqrt(len);
  94068. ax *= len;
  94069. ay *= len;
  94070. az *= len;
  94071. }
  94072. var sin = OIMO.sin(rad * 0.5);
  94073. var cos = OIMO.cos(rad * 0.5);
  94074. return new OIMO.Quat(cos, sin * ax, sin * ay, sin * az);
  94075. },
  94076. //---------------------------------------------
  94077. // SET DYNAMIQUE POSITION AND ROTATION
  94078. //---------------------------------------------
  94079. setPosition: function (pos) {
  94080. this.newPosition.copy(pos).multiplyScalar(OIMO.INV_SCALE);
  94081. //this.newPosition.set(pos.x*OIMO.INV_SCALE,pos.y*OIMO.INV_SCALE,pos.z*OIMO.INV_SCALE);
  94082. this.controlPos = true;
  94083. },
  94084. setQuaternion: function (q) {
  94085. //if(this.type == this.BODY_STATIC)this.orientation.init(q.w,q.x,q.y,q.z);
  94086. this.newOrientation.set(q.x, q.y, q.z, q.w);
  94087. this.controlRot = true;
  94088. },
  94089. setRotation: function (rot) {
  94090. this.newOrientation = this.rotationVectToQuad(rot);
  94091. this.controlRot = true;
  94092. },
  94093. //---------------------------------------------
  94094. // RESET DYNAMIQUE POSITION AND ROTATION
  94095. //---------------------------------------------
  94096. resetPosition: function (x, y, z) {
  94097. this.linearVelocity.set(0, 0, 0);
  94098. this.angularVelocity.set(0, 0, 0);
  94099. this.position.set(x, y, z).multiplyScalar(OIMO.INV_SCALE);
  94100. //this.position.set( x*OIMO.INV_SCALE, y*OIMO.INV_SCALE, z*OIMO.INV_SCALE );
  94101. this.awake();
  94102. },
  94103. resetQuaternion: function (q) {
  94104. this.angularVelocity.set(0, 0, 0);
  94105. this.orientation = new OIMO.Quat(q.w, q.x, q.y, q.z);
  94106. this.awake();
  94107. },
  94108. resetRotation: function (x, y, z) {
  94109. this.angularVelocity.set(0, 0, 0);
  94110. this.orientation = this.rotationVectToQuad(new OIMO.Vec3(x, y, z));
  94111. this.awake();
  94112. },
  94113. //---------------------------------------------
  94114. // GET POSITION AND ROTATION
  94115. //---------------------------------------------
  94116. getPosition: function () {
  94117. return new OIMO.Vec3().scale(this.position, OIMO.WORLD_SCALE);
  94118. },
  94119. getRotation: function () {
  94120. return new OIMO.Euler().setFromRotationMatrix(this.rotation);
  94121. },
  94122. getQuaternion: function () {
  94123. return new OIMO.Quaternion().setFromRotationMatrix(this.rotation);
  94124. },
  94125. getMatrix: function () {
  94126. var m = this.matrix.elements;
  94127. var r, p;
  94128. if (!this.sleeping) {
  94129. // rotation matrix
  94130. r = this.rotation.elements;
  94131. m[0] = r[0]; m[1] = r[3]; m[2] = r[6]; m[3] = 0;
  94132. m[4] = r[1]; m[5] = r[4]; m[6] = r[7]; m[7] = 0;
  94133. m[8] = r[2]; m[9] = r[5]; m[10] = r[8]; m[11] = 0;
  94134. // position matrix
  94135. p = this.position;
  94136. m[12] = p.x * OIMO.WORLD_SCALE;
  94137. m[13] = p.y * OIMO.WORLD_SCALE;
  94138. m[14] = p.z * OIMO.WORLD_SCALE;
  94139. // sleep or not ?
  94140. m[15] = 0;
  94141. } else {
  94142. m[15] = 1;
  94143. }
  94144. return m;
  94145. }
  94146. };
  94147. /**
  94148. * The main class of body.
  94149. * is for simplify creation process and data access of rigidRody
  94150. * Rigid body has the shape of a single or multiple collision processing,
  94151. * all setting in object
  94152. *
  94153. * @author loth
  94154. */
  94155. OIMO.Body = function (Obj) {
  94156. var obj = Obj || {};
  94157. if (!obj.world) return;
  94158. if (obj.type === undefined) obj.type = "box";
  94159. this.name = obj.name || '';
  94160. // obsolete use world.add(obj)
  94161. this.body = obj.world.add(obj);
  94162. /*
  94163. // the world where i am
  94164. this.parent = obj.world;
  94165. // Yep my name
  94166. this.name = obj.name || '';
  94167. // I'm dynamique or not
  94168. var move = obj.move || false;
  94169. // I can sleep or not
  94170. var noSleep = obj.noSleep || false;
  94171. // My start position
  94172. var p = obj.pos || [0,0,0];
  94173. p = p.map(function(x) { return x * OIMO.INV_SCALE; });
  94174. // My size
  94175. var s = obj.size || [1,1,1];
  94176. s = s.map(function(x) { return x * OIMO.INV_SCALE; });
  94177. // My rotation in degre
  94178. var rot = obj.rot || [0,0,0];
  94179. rot = rot.map(function(x) { return x * OIMO.TO_RAD; });
  94180. var r = [];
  94181. for (var i=0; i<rot.length/3; i++){
  94182. var tmp = OIMO.EulerToAxis(rot[i+0], rot[i+1], rot[i+2]);
  94183. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  94184. }
  94185. // My physics setting
  94186. var sc = obj.sc || new OIMO.ShapeConfig();
  94187. if(obj.config){
  94188. // The density of the shape.
  94189. sc.density = obj.config[0] || 1;
  94190. // The coefficient of friction of the shape.
  94191. sc.friction = obj.config[1] || 0.4;
  94192. // The coefficient of restitution of the shape.
  94193. sc.restitution = obj.config[2] || 0.2;
  94194. // The bits of the collision groups to which the shape belongs.
  94195. sc.belongsTo = obj.config[3] || 1;
  94196. // The bits of the collision groups with which the shape collides.
  94197. sc.collidesWith = obj.config[4] || 0xffffffff;
  94198. }
  94199. if(obj.massPos){
  94200. obj.massPos = obj.massPos.map(function(x) { return x * OIMO.INV_SCALE; });
  94201. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  94202. }
  94203. if(obj.massRot){
  94204. obj.massRot = obj.massRot.map(function(x) { return x * OIMO.TO_RAD; });
  94205. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  94206. }
  94207. // My rigidbody
  94208. this.body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  94209. // My shapes
  94210. var shapes = [];
  94211. var type = obj.type || "box";
  94212. if( typeof type === 'string' ) type = [type];// single shape
  94213. var n, n2;
  94214. for(var i=0; i<type.length; i++){
  94215. n = i*3;
  94216. n2 = i*4;
  94217. switch(type[i]){
  94218. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n+0]); break;
  94219. case "cylinder": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break; // fake cylinder
  94220. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break;
  94221. }
  94222. this.body.addShape(shapes[i]);
  94223. if(i>0){
  94224. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  94225. shapes[i].relativePosition = new OIMO.Vec3( p[n+0], p[n+1], p[n+2] );
  94226. if(r[n2+0]) shapes[i].relativeRotation = [ r[n2+0], r[n2+1], r[n2+2], r[n2+3] ];
  94227. }
  94228. }
  94229. // I'm static or i move
  94230. if(move){
  94231. if(obj.massPos || obj.massRot)this.body.setupMass(0x1, false);
  94232. else this.body.setupMass(0x1, true);
  94233. if(noSleep) this.body.allowSleep = false;
  94234. else this.body.allowSleep = true;
  94235. } else {
  94236. this.body.setupMass(0x2);
  94237. }
  94238. this.body.name = this.name;
  94239. this.sleeping = this.body.sleeping;
  94240. // finaly add to physics world
  94241. this.parent.addRigidBody(this.body);*/
  94242. }
  94243. OIMO.Body.prototype = {
  94244. constructor: OIMO.Body,
  94245. // SET
  94246. setPosition: function (pos) {
  94247. this.body.setPosition(pos);
  94248. },
  94249. setQuaternion: function (q) {
  94250. this.body.setQuaternion(q);
  94251. },
  94252. setRotation: function (rot) {
  94253. this.body.setRotation(rot);
  94254. },
  94255. // GET
  94256. getPosition: function () {
  94257. return this.body.getPosition();
  94258. },
  94259. getRotation: function () {
  94260. return this.body.getRotation();
  94261. },
  94262. getQuaternion: function () {
  94263. return this.body.getQuaternion();
  94264. },
  94265. getMatrix: function () {
  94266. return this.body.getMatrix();
  94267. },
  94268. getSleep: function () {
  94269. return this.body.sleeping;
  94270. },
  94271. // RESET
  94272. resetPosition: function (x, y, z) {
  94273. this.body.resetPosition(x, y, z);
  94274. },
  94275. resetRotation: function (x, y, z) {
  94276. this.body.resetRotation(x, y, z);
  94277. },
  94278. // force wakeup
  94279. awake: function () {
  94280. this.body.awake();
  94281. },
  94282. // remove rigidbody
  94283. remove: function () {
  94284. this.body.dispose();
  94285. //this.parent.removeRigidBody(this.body);
  94286. },
  94287. // test if this object hit another
  94288. checkContact: function (name) {
  94289. this.body.checkContact(name);
  94290. //this.parent.checkContact(this.name, name);
  94291. }
  94292. }
  94293. /**
  94294. * The main class of link.
  94295. * is for simplify creation process and data access of Joint
  94296. * all setting in object
  94297. *
  94298. * @author loth
  94299. */
  94300. OIMO.Link = function (Obj) {
  94301. var obj = Obj || {};
  94302. if (!obj.world) return;
  94303. if (obj.type === undefined) obj.type = "jointHinge";
  94304. this.name = obj.name || '';
  94305. // obsolete use world.add(obj)
  94306. this.joint = obj.world.add(obj);
  94307. // the world where i am
  94308. /*this.parent = obj.world;
  94309. this.name = obj.name || '';
  94310. var type = obj.type || "jointHinge";
  94311. var axe1 = obj.axe1 || [1,0,0];
  94312. var axe2 = obj.axe2 || [1,0,0];
  94313. var pos1 = obj.pos1 || [0,0,0];
  94314. var pos2 = obj.pos2 || [0,0,0];
  94315. pos1 = pos1.map(function(x){ return x * OIMO.INV_SCALE; });
  94316. pos2 = pos2.map(function(x){ return x * OIMO.INV_SCALE; });
  94317. var min, max;
  94318. if(type==="jointDistance"){
  94319. min = obj.min || 0;
  94320. max = obj.max || 10;
  94321. min = min*OIMO.INV_SCALE;
  94322. max = max*OIMO.INV_SCALE;
  94323. }else{
  94324. min = obj.min || 57.29578;
  94325. max = obj.max || 0;
  94326. min = min*OIMO.TO_RAD;
  94327. max = max*OIMO.TO_RAD;
  94328. }
  94329. var limit = obj.limit || null;
  94330. var spring = obj.spring || null;
  94331. var motor = obj.motor || null;
  94332. // joint setting
  94333. var jc = new OIMO.JointConfig();
  94334. jc.allowCollision = obj.collision || false;;
  94335. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  94336. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  94337. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  94338. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  94339. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = obj.world.getByName(obj.body1);
  94340. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = obj.world.getByName(obj.body2);
  94341. jc.body1 = obj.body1;
  94342. jc.body2 = obj.body2;
  94343. switch(type){
  94344. case "jointDistance": this.joint = new OIMO.DistanceJoint(jc, min, max);
  94345. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);
  94346. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  94347. break;
  94348. case "jointHinge": this.joint = new OIMO.HingeJoint(jc, min, max);
  94349. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  94350. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  94351. break;
  94352. case "jointPrisme": this.joint = new OIMO.PrismaticJoint(jc, min, max); break;
  94353. case "jointSlide": this.joint = new OIMO.SliderJoint(jc, min, max); break;
  94354. case "jointBall": this.joint = new OIMO.BallAndSocketJoint(jc); break;
  94355. case "jointWheel": this.joint = new OIMO.WheelJoint(jc);
  94356. if(limit !== null) this.joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  94357. if(spring !== null) this.joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  94358. if(motor !== null) this.joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  94359. break;
  94360. }
  94361. this.joint.name = this.name;
  94362. // finaly add to physics world
  94363. this.parent.addJoint(this.joint);*/
  94364. }
  94365. OIMO.Link.prototype = {
  94366. constructor: OIMO.Link,
  94367. getPosition: function () {
  94368. // array of two vect3 [point1, point2]
  94369. return this.joint.getPosition();
  94370. },
  94371. getMatrix: function () {
  94372. return this.joint.getMatrix();
  94373. },
  94374. // remove joint
  94375. remove: function () {
  94376. this.joint.dispose();
  94377. //this.parent.removeJoint(this.joint);
  94378. },
  94379. // force wakeup linked body
  94380. awake: function () {
  94381. this.joint.awake();
  94382. }
  94383. }
  94384. /**
  94385. * The Dictionary class for testing
  94386. * @author lo-th
  94387. */
  94388. OIMO.Dictionary = function () {
  94389. this.data = {};
  94390. this.keys = [];
  94391. };
  94392. OIMO.Dictionary.prototype = {
  94393. constructor: OIMO.Dictionary,
  94394. set: function (value) {
  94395. var key = value.id;
  94396. if (!this.get[key]) this.keys.push(key);
  94397. this.data[key] = value;
  94398. },
  94399. get: function (id) {
  94400. return this.data[id];
  94401. },
  94402. del: function (value) {
  94403. var k = this.keys;
  94404. var n = k.indexOf(value.id);
  94405. if (n > -1) {
  94406. delete this.data[k[n]];
  94407. k.splice(n, 1);
  94408. }
  94409. },
  94410. reset: function () {
  94411. var data = this.data, keys = this.keys, key;
  94412. while (keys.length > 0) {
  94413. key = keys.pop();
  94414. delete data[key];
  94415. }
  94416. }
  94417. };
  94418. OIMO.Performance = function (world) {
  94419. this.parent = world;
  94420. this.infos = new OIMO_ARRAY_TYPE(13);
  94421. this.f = [0, 0, 0];
  94422. this.types = ['None', 'BruteForce', 'Sweep & Prune', 'Bounding Volume Tree'];
  94423. this.broadPhase = this.types[this.parent.broadPhase.types];
  94424. this.version = OIMO.REVISION;
  94425. this.fps = 0;
  94426. this.broadPhaseTime = 0;
  94427. this.narrowPhaseTime = 0;
  94428. this.solvingTime = 0;
  94429. //this.updatingTime = 0;
  94430. this.totalTime = 0;
  94431. };
  94432. OIMO.Performance.prototype = {
  94433. upfps: function () {
  94434. this.f[1] = Date.now();
  94435. 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]++;
  94436. },
  94437. updatingTime: function () {
  94438. return OIMO.fix(this.totalTime - (this.broadPhaseTime + this.narrowPhaseTime + this.solvingTime));
  94439. },
  94440. show: function () {
  94441. var info = [
  94442. "Oimo.js " + this.version + "<br>",
  94443. this.broadPhase + "<br><br>",
  94444. "FPS: " + this.fps + " fps<br><br>",
  94445. "rigidbody " + this.parent.numRigidBodies + "<br>",
  94446. "contact &nbsp;&nbsp;" + this.parent.numContacts + "<br>",
  94447. "ct-point &nbsp;" + this.parent.numContactPoints + "<br>",
  94448. "paircheck " + this.parent.broadPhase.numPairChecks + "<br>",
  94449. "island &nbsp;&nbsp;&nbsp;" + this.parent.numIslands + "<br><br>",
  94450. "Time in milliseconde<br><br>",
  94451. "broad-phase &nbsp;" + OIMO.fix(this.broadPhaseTime) + "<br>",
  94452. "narrow-phase " + OIMO.fix(this.narrowPhaseTime) + "<br>",
  94453. "solving &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.solvingTime) + "<br>",
  94454. "total &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.totalTime) + "<br>",
  94455. "updating &nbsp;&nbsp;&nbsp;&nbsp;" + this.updatingTime() + "<br>"
  94456. ].join("\n");
  94457. return info;
  94458. },
  94459. toArray: function () {
  94460. this.infos[0] = this.parent.broadPhase.types;
  94461. this.infos[1] = this.parent.numRigidBodies;
  94462. this.infos[2] = this.parent.numContacts;
  94463. this.infos[3] = this.parent.broadPhase.numPairChecks;
  94464. this.infos[4] = this.parent.numContactPoints;
  94465. this.infos[5] = this.parent.numIslands;
  94466. this.infos[6] = this.broadPhaseTime;
  94467. this.infos[7] = this.narrowPhaseTime;
  94468. this.infos[8] = this.solvingTime;
  94469. this.infos[9] = this.updatingTime();
  94470. this.infos[10] = this.totalTime;
  94471. this.infos[11] = this.fps;
  94472. return this.infos;
  94473. }
  94474. };
  94475. OIMO.Mat44 = function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  94476. this.elements = new OIMO_ARRAY_TYPE(16);
  94477. var te = this.elements;
  94478. te[0] = (n11 !== undefined) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  94479. te[1] = n21 || 0; te[5] = (n22 !== undefined) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  94480. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = (n33 !== undefined) ? n33 : 1; te[14] = n34 || 0;
  94481. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = (n44 !== undefined) ? n44 : 1;
  94482. };
  94483. OIMO.Mat44.prototype = {
  94484. constructor: OIMO.Mat44,
  94485. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  94486. var te = this.elements;
  94487. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  94488. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  94489. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  94490. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  94491. return this;
  94492. }/*,
  94493. extractRotation: function () {
  94494. var v1 = new THREE.Vector3();
  94495. return function ( m ) {
  94496. var te = this.elements;
  94497. var me = m.elements;
  94498. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  94499. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  94500. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  94501. te[ 0 ] = me[ 0 ] * scaleX;
  94502. te[ 1 ] = me[ 1 ] * scaleX;
  94503. te[ 2 ] = me[ 2 ] * scaleX;
  94504. te[ 4 ] = me[ 4 ] * scaleY;
  94505. te[ 5 ] = me[ 5 ] * scaleY;
  94506. te[ 6 ] = me[ 6 ] * scaleY;
  94507. te[ 8 ] = me[ 8 ] * scaleZ;
  94508. te[ 9 ] = me[ 9 ] * scaleZ;
  94509. te[ 10 ] = me[ 10 ] * scaleZ;
  94510. return this;
  94511. };
  94512. }() */
  94513. }
  94514. OIMO.Mat33 = function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  94515. this.elements = new OIMO_ARRAY_TYPE(9);
  94516. var te = this.elements;
  94517. this.init(
  94518. (e00 !== undefined) ? e00 : 1, e01 || 0, e02 || 0,
  94519. e10 || 0, (e11 !== undefined) ? e11 : 1, e12 || 0,
  94520. e20 || 0, e21 || 0, (e22 !== undefined) ? e22 : 1
  94521. );
  94522. };
  94523. OIMO.Mat33.prototype = {
  94524. constructor: OIMO.Mat33,
  94525. set: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  94526. var te = this.elements;
  94527. te[0] = e00; te[1] = e01; te[2] = e02;
  94528. te[3] = e10; te[4] = e11; te[5] = e12;
  94529. te[6] = e20; te[7] = e21; te[8] = e22;
  94530. return this;
  94531. },
  94532. init: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  94533. var te = this.elements;
  94534. te[0] = e00; te[1] = e01; te[2] = e02;
  94535. te[3] = e10; te[4] = e11; te[5] = e12;
  94536. te[6] = e20; te[7] = e21; te[8] = e22;
  94537. return this;
  94538. },
  94539. multiply: function (s) {
  94540. var te = this.elements;
  94541. te[0] *= s; te[1] *= s; te[2] *= s;
  94542. te[3] *= s; te[4] *= s; te[5] *= s;
  94543. te[6] *= s; te[7] *= s; te[8] *= s;
  94544. return this;
  94545. },
  94546. add: function (m1, m2) {
  94547. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  94548. te[0] = tem1[0] + tem2[0]; te[1] = tem1[1] + tem2[1]; te[2] = tem1[2] + tem2[2];
  94549. te[3] = tem1[3] + tem2[3]; te[4] = tem1[4] + tem2[4]; te[5] = tem1[5] + tem2[5];
  94550. te[6] = tem1[6] + tem2[6]; te[7] = tem1[7] + tem2[7]; te[8] = tem1[8] + tem2[8];
  94551. return this;
  94552. },
  94553. addEqual: function (m) {
  94554. var te = this.elements, tem = m.elements;
  94555. te[0] += tem[0]; te[1] += tem[1]; te[2] += tem[2];
  94556. te[3] += tem[3]; te[4] += tem[4]; te[5] += tem[5];
  94557. te[6] += tem[6]; te[7] += tem[7]; te[8] += tem[8];
  94558. return this;
  94559. },
  94560. sub: function (m1, m2) {
  94561. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  94562. te[0] = tem1[0] - tem2[0]; te[1] = tem1[1] - tem2[1]; te[2] = tem1[2] - tem2[2];
  94563. te[3] = tem1[3] - tem2[3]; te[4] = tem1[4] - tem2[4]; te[5] = tem1[5] - tem2[5];
  94564. te[6] = tem1[6] - tem2[6]; te[7] = tem1[7] - tem2[7]; te[8] = tem1[8] - tem2[8];
  94565. return this;
  94566. },
  94567. subEqual: function (m) {
  94568. var te = this.elements, tem = m.elements;
  94569. te[0] -= tem[0]; te[1] -= tem[1]; te[2] -= tem[2];
  94570. te[3] -= tem[3]; te[4] -= tem[4]; te[5] -= tem[5];
  94571. te[6] -= tem[6]; te[7] -= tem[7]; te[8] -= tem[8];
  94572. return this;
  94573. },
  94574. scale: function (m, s) {
  94575. var te = this.elements, tm = m.elements;
  94576. te[0] = tm[0] * s; te[1] = tm[1] * s; te[2] = tm[2] * s;
  94577. te[3] = tm[3] * s; te[4] = tm[4] * s; te[5] = tm[5] * s;
  94578. te[6] = tm[6] * s; te[7] = tm[7] * s; te[8] = tm[8] * s;
  94579. return this;
  94580. },
  94581. scaleEqual: function (s) {
  94582. var te = this.elements;
  94583. te[0] *= s; te[1] *= s; te[2] *= s;
  94584. te[3] *= s; te[4] *= s; te[5] *= s;
  94585. te[6] *= s; te[7] *= s; te[8] *= s;
  94586. return this;
  94587. },
  94588. mul: function (m1, m2) {
  94589. var te = this.elements, tm1 = m1.elements, tm2 = m2.elements,
  94590. a0 = tm1[0], a3 = tm1[3], a6 = tm1[6],
  94591. a1 = tm1[1], a4 = tm1[4], a7 = tm1[7],
  94592. a2 = tm1[2], a5 = tm1[5], a8 = tm1[8],
  94593. b0 = tm2[0], b3 = tm2[3], b6 = tm2[6],
  94594. b1 = tm2[1], b4 = tm2[4], b7 = tm2[7],
  94595. b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  94596. te[0] = a0 * b0 + a1 * b3 + a2 * b6;
  94597. te[1] = a0 * b1 + a1 * b4 + a2 * b7;
  94598. te[2] = a0 * b2 + a1 * b5 + a2 * b8;
  94599. te[3] = a3 * b0 + a4 * b3 + a5 * b6;
  94600. te[4] = a3 * b1 + a4 * b4 + a5 * b7;
  94601. te[5] = a3 * b2 + a4 * b5 + a5 * b8;
  94602. te[6] = a6 * b0 + a7 * b3 + a8 * b6;
  94603. te[7] = a6 * b1 + a7 * b4 + a8 * b7;
  94604. te[8] = a6 * b2 + a7 * b5 + a8 * b8;
  94605. return this;
  94606. },
  94607. mulScale: function (m, sx, sy, sz, Prepend) {
  94608. var prepend = Prepend || false;
  94609. var te = this.elements, tm = m.elements;
  94610. if (prepend) {
  94611. te[0] = sx * tm[0]; te[1] = sx * tm[1]; te[2] = sx * tm[2];
  94612. te[3] = sy * tm[3]; te[4] = sy * tm[4]; te[5] = sy * tm[5];
  94613. te[6] = sz * tm[6]; te[7] = sz * tm[7]; te[8] = sz * tm[8];
  94614. } else {
  94615. te[0] = tm[0] * sx; te[1] = tm[1] * sy; te[2] = tm[2] * sz;
  94616. te[3] = tm[3] * sx; te[4] = tm[4] * sy; te[5] = tm[5] * sz;
  94617. te[6] = tm[6] * sx; te[7] = tm[7] * sy; te[8] = tm[8] * sz;
  94618. }
  94619. return this;
  94620. },
  94621. mulRotate: function (m, rad, ax, ay, az, Prepend) {
  94622. var prepend = Prepend || false;
  94623. var s = OIMO.sin(rad);
  94624. var c = OIMO.cos(rad);
  94625. var c1 = 1 - c;
  94626. var r00 = ax * ax * c1 + c;
  94627. var r01 = ax * ay * c1 - az * s;
  94628. var r02 = ax * az * c1 + ay * s;
  94629. var r10 = ay * ax * c1 + az * s;
  94630. var r11 = ay * ay * c1 + c;
  94631. var r12 = ay * az * c1 - ax * s;
  94632. var r20 = az * ax * c1 - ay * s;
  94633. var r21 = az * ay * c1 + ax * s;
  94634. var r22 = az * az * c1 + c;
  94635. var tm = m.elements;
  94636. var a0 = tm[0], a3 = tm[3], a6 = tm[6];
  94637. var a1 = tm[1], a4 = tm[4], a7 = tm[7];
  94638. var a2 = tm[2], a5 = tm[5], a8 = tm[8];
  94639. var te = this.elements;
  94640. if (prepend) {
  94641. te[0] = r00 * a0 + r01 * a3 + r02 * a6;
  94642. te[1] = r00 * a1 + r01 * a4 + r02 * a7;
  94643. te[2] = r00 * a2 + r01 * a5 + r02 * a8;
  94644. te[3] = r10 * a0 + r11 * a3 + r12 * a6;
  94645. te[4] = r10 * a1 + r11 * a4 + r12 * a7;
  94646. te[5] = r10 * a2 + r11 * a5 + r12 * a8;
  94647. te[6] = r20 * a0 + r21 * a3 + r22 * a6;
  94648. te[7] = r20 * a1 + r21 * a4 + r22 * a7;
  94649. te[8] = r20 * a2 + r21 * a5 + r22 * a8;
  94650. } else {
  94651. te[0] = a0 * r00 + a1 * r10 + a2 * r20;
  94652. te[1] = a0 * r01 + a1 * r11 + a2 * r21;
  94653. te[2] = a0 * r02 + a1 * r12 + a2 * r22;
  94654. te[3] = a3 * r00 + a4 * r10 + a5 * r20;
  94655. te[4] = a3 * r01 + a4 * r11 + a5 * r21;
  94656. te[5] = a3 * r02 + a4 * r12 + a5 * r22;
  94657. te[6] = a6 * r00 + a7 * r10 + a8 * r20;
  94658. te[7] = a6 * r01 + a7 * r11 + a8 * r21;
  94659. te[8] = a6 * r02 + a7 * r12 + a8 * r22;
  94660. }
  94661. return this;
  94662. },
  94663. transpose: function (m) {
  94664. var te = this.elements, tm = m.elements;
  94665. te[0] = tm[0]; te[1] = tm[3]; te[2] = tm[6];
  94666. te[3] = tm[1]; te[4] = tm[4]; te[5] = tm[7];
  94667. te[6] = tm[2]; te[7] = tm[5]; te[8] = tm[8];
  94668. return this;
  94669. },
  94670. setQuat: function (q) {
  94671. var te = this.elements,
  94672. x2 = 2 * q.x, y2 = 2 * q.y, z2 = 2 * q.z,
  94673. xx = q.x * x2, yy = q.y * y2, zz = q.z * z2,
  94674. xy = q.x * y2, yz = q.y * z2, xz = q.x * z2,
  94675. sx = q.s * x2, sy = q.s * y2, sz = q.s * z2;
  94676. te[0] = 1 - yy - zz;
  94677. te[1] = xy - sz;
  94678. te[2] = xz + sy;
  94679. te[3] = xy + sz;
  94680. te[4] = 1 - xx - zz;
  94681. te[5] = yz - sx;
  94682. te[6] = xz - sy;
  94683. te[7] = yz + sx;
  94684. te[8] = 1 - xx - yy;
  94685. return this;
  94686. },
  94687. invert: function (m) {
  94688. var te = this.elements, tm = m.elements,
  94689. a0 = tm[0], a3 = tm[3], a6 = tm[6],
  94690. a1 = tm[1], a4 = tm[4], a7 = tm[7],
  94691. a2 = tm[2], a5 = tm[5], a8 = tm[8],
  94692. b01 = a4 * a8 - a7 * a5,
  94693. b11 = a7 * a2 - a1 * a8,
  94694. b21 = a1 * a5 - a4 * a2,
  94695. dt = a0 * (b01) + a3 * (b11) + a6 * (b21);
  94696. if (dt != 0) { dt = 1.0 / dt; }
  94697. te[0] = dt * b01;//(a4*a8 - a5*a7);
  94698. te[1] = dt * b11;//(a2*a7 - a1*a8);
  94699. te[2] = dt * b21;//(a1*a5 - a2*a4);
  94700. te[3] = dt * (a5 * a6 - a3 * a8);
  94701. te[4] = dt * (a0 * a8 - a2 * a6);
  94702. te[5] = dt * (a2 * a3 - a0 * a5);
  94703. te[6] = dt * (a3 * a7 - a4 * a6);
  94704. te[7] = dt * (a1 * a6 - a0 * a7);
  94705. te[8] = dt * (a0 * a4 - a1 * a3);
  94706. return this;
  94707. },
  94708. /*copy: function(m){
  94709. var te = this.elements, tem = m.elements;
  94710. te[0] = tem[0]; te[1] = tem[1]; te[2] = tem[2];
  94711. te[3] = tem[3]; te[4] = tem[4]; te[5] = tem[5];
  94712. te[6] = tem[6]; te[7] = tem[7]; te[8] = tem[8];
  94713. return this;
  94714. },*/
  94715. toEuler: function () { // not work !!
  94716. function clamp(x) {
  94717. return OIMO.min(OIMO.max(x, -1), 1);
  94718. }
  94719. var te = this.elements;
  94720. var m11 = te[0], m12 = te[3], m13 = te[6];
  94721. var m21 = te[1], m22 = te[4], m23 = te[7];
  94722. var m31 = te[2], m32 = te[5], m33 = te[8];
  94723. var p = new OIMO.Vec3();
  94724. var d = new OIMO.Quat();
  94725. var s;
  94726. p.y = OIMO.asin(clamp(m13));
  94727. if (OIMO.abs(m13) < 0.99999) {
  94728. p.x = OIMO.atan2(-m23, m33);
  94729. p.z = OIMO.atan2(-m12, m11);
  94730. } else {
  94731. p.x = OIMO.atan2(m32, m22);
  94732. p.z = 0;
  94733. }
  94734. return p;
  94735. },
  94736. /*clone: function(){
  94737. var te = this.elements;
  94738. return new OIMO.Mat33(
  94739. te[0], te[1], te[2],
  94740. te[3], te[4], te[5],
  94741. te[6], te[7], te[8]
  94742. );
  94743. },*/
  94744. toString: function () {
  94745. var te = this.elements;
  94746. var text =
  94747. "Mat33|" + te[0].toFixed(4) + ", " + te[1].toFixed(4) + ", " + te[2].toFixed(4) + "|\n" +
  94748. " |" + te[3].toFixed(4) + ", " + te[4].toFixed(4) + ", " + te[5].toFixed(4) + "|\n" +
  94749. " |" + te[6].toFixed(4) + ", " + te[7].toFixed(4) + ", " + te[8].toFixed(4) + "|";
  94750. return text;
  94751. },
  94752. // OK
  94753. multiplyScalar: function (s) {
  94754. var te = this.elements;
  94755. te[0] *= s; te[3] *= s; te[6] *= s;
  94756. te[1] *= s; te[4] *= s; te[7] *= s;
  94757. te[2] *= s; te[5] *= s; te[8] *= s;
  94758. return this;
  94759. },
  94760. identity: function () {
  94761. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  94762. return this;
  94763. },
  94764. clone: function () {
  94765. return new this.constructor().fromArray(this.elements);
  94766. },
  94767. copy: function (m) {
  94768. var me = m.elements;
  94769. this.set(
  94770. me[0], me[3], me[6],
  94771. me[1], me[4], me[7],
  94772. me[2], me[5], me[8]
  94773. );
  94774. return this;
  94775. },
  94776. fromArray: function (array) {
  94777. this.elements.set(array);
  94778. return this;
  94779. },
  94780. toArray: function () {
  94781. var te = this.elements;
  94782. return [
  94783. te[0], te[1], te[2],
  94784. te[3], te[4], te[5],
  94785. te[6], te[7], te[8]
  94786. ];
  94787. }
  94788. };
  94789. OIMO.Quat = function (s, x, y, z) {
  94790. this.s = (s !== undefined) ? s : 1;
  94791. this.x = x || 0;
  94792. this.y = y || 0;
  94793. this.z = z || 0;
  94794. };
  94795. OIMO.Quat.prototype = {
  94796. constructor: OIMO.Quat,
  94797. set: function (x, y, z, w) {
  94798. this.x = x;
  94799. this.y = y;
  94800. this.z = z;
  94801. this.s = w;
  94802. return this;
  94803. },
  94804. init: function (s, x, y, z) {
  94805. this.s = (s !== undefined) ? s : 1;
  94806. this.x = x || 0;
  94807. this.y = y || 0;
  94808. this.z = z || 0;
  94809. return this;
  94810. },
  94811. add: function (q1, q2) {
  94812. this.s = q1.s + q2.s;
  94813. this.x = q1.x + q2.x;
  94814. this.y = q1.y + q2.y;
  94815. this.z = q1.z + q2.z;
  94816. return this;
  94817. },
  94818. addTime: function (v, t) {
  94819. var x = v.x;
  94820. var y = v.y;
  94821. var z = v.z;
  94822. var qs = this.s;
  94823. var qx = this.x;
  94824. var qy = this.y;
  94825. var qz = this.z;
  94826. t *= 0.5;
  94827. var ns = (-x * qx - y * qy - z * qz) * t;
  94828. var nx = (x * qs + y * qz - z * qy) * t;
  94829. var ny = (-x * qz + y * qs + z * qx) * t;
  94830. var nz = (x * qy - y * qx + z * qs) * t;
  94831. qs += ns;
  94832. qx += nx;
  94833. qy += ny;
  94834. qz += nz;
  94835. var s = 1 / OIMO.sqrt(qs * qs + qx * qx + qy * qy + qz * qz);
  94836. this.s = qs * s;
  94837. this.x = qx * s;
  94838. this.y = qy * s;
  94839. this.z = qz * s;
  94840. return this;
  94841. },
  94842. sub: function (q1, q2) {
  94843. this.s = q1.s - q2.s;
  94844. this.x = q1.x - q2.x;
  94845. this.y = q1.y - q2.y;
  94846. this.z = q1.z - q2.z;
  94847. return this;
  94848. },
  94849. scale: function (q, s) {
  94850. this.s = q.s * s;
  94851. this.x = q.x * s;
  94852. this.y = q.y * s;
  94853. this.z = q.z * s;
  94854. return this;
  94855. },
  94856. mul: function (q1, q2) {
  94857. var ax = q1.x, ay = q1.y, az = q1.z, as = q1.s,
  94858. bx = q2.x, by = q2.y, bz = q2.z, bs = q2.s;
  94859. this.x = ax * bs + as * bx + ay * bz - az * by;
  94860. this.y = ay * bs + as * by + az * bx - ax * bz;
  94861. this.z = az * bs + as * bz + ax * by - ay * bx;
  94862. this.s = as * bs - ax * bx - ay * by - az * bz;
  94863. return this;
  94864. },
  94865. arc: function (v1, v2) {
  94866. var x1 = v1.x;
  94867. var y1 = v1.y;
  94868. var z1 = v1.z;
  94869. var x2 = v2.x;
  94870. var y2 = v2.y;
  94871. var z2 = v2.z;
  94872. var d = x1 * x2 + y1 * y2 + z1 * z2;
  94873. if (d == -1) {
  94874. x2 = y1 * x1 - z1 * z1;
  94875. y2 = -z1 * y1 - x1 * x1;
  94876. z2 = x1 * z1 + y1 * y1;
  94877. d = 1 / OIMO.sqrt(x2 * x2 + y2 * y2 + z2 * z2);
  94878. this.s = 0;
  94879. this.x = x2 * d;
  94880. this.y = y2 * d;
  94881. this.z = z2 * d;
  94882. return this;
  94883. }
  94884. var cx = y1 * z2 - z1 * y2;
  94885. var cy = z1 * x2 - x1 * z2;
  94886. var cz = x1 * y2 - y1 * x2;
  94887. this.s = OIMO.sqrt((1 + d) * 0.5);
  94888. d = 0.5 / this.s;
  94889. this.x = cx * d;
  94890. this.y = cy * d;
  94891. this.z = cz * d;
  94892. return this;
  94893. },
  94894. normalize: function (q) {
  94895. var len = OIMO.sqrt(q.s * q.s + q.x * q.x + q.y * q.y + q.z * q.z);
  94896. if (len > 0) { len = 1 / len; }
  94897. this.s = q.s * len;
  94898. this.x = q.x * len;
  94899. this.y = q.y * len;
  94900. this.z = q.z * len;
  94901. return this;
  94902. },
  94903. invert: function (q) {
  94904. this.s = q.s;
  94905. this.x = -q.x;
  94906. this.y = -q.y;
  94907. this.z = -q.z;
  94908. return this;
  94909. },
  94910. length: function () {
  94911. return OIMO.sqrt(this.s * this.s + this.x * this.x + this.y * this.y + this.z * this.z);
  94912. },
  94913. copy: function (q) {
  94914. this.s = q.s;
  94915. this.x = q.x;
  94916. this.y = q.y;
  94917. this.z = q.z;
  94918. return this;
  94919. },
  94920. testDiff: function (q) {
  94921. if (this.s !== q.s || this.x !== q.x || this.y !== q.y || this.z !== q.z) return true;
  94922. else return false;
  94923. },
  94924. clone: function (q) {
  94925. return new OIMO.Quat(this.s, this.x, this.y, this.z);
  94926. },
  94927. toString: function () {
  94928. return "Quat[" + this.s.toFixed(4) + ", (" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + ")]";
  94929. }
  94930. }
  94931. // for three easy export
  94932. OIMO.Quaternion = function (x, y, z, w) {
  94933. this.x = x || 0;
  94934. this.y = y || 0;
  94935. this.z = z || 0;
  94936. this.w = (w !== undefined) ? w : 1;
  94937. };
  94938. OIMO.Quaternion.prototype = {
  94939. constructor: OIMO.Quaternion,
  94940. setFromRotationMatrix: function (m) {
  94941. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  94942. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  94943. var te = m.elements,
  94944. m11 = te[0], m12 = te[1], m13 = te[2],
  94945. m21 = te[3], m22 = te[4], m23 = te[5],
  94946. m31 = te[6], m32 = te[7], m33 = te[8],
  94947. trace = m11 + m22 + m33,
  94948. s;
  94949. if (trace > 0) {
  94950. s = 0.5 / OIMO.sqrt(trace + 1.0);
  94951. this.w = 0.25 / s;
  94952. this.x = (m32 - m23) * s;
  94953. this.y = (m13 - m31) * s;
  94954. this.z = (m21 - m12) * s;
  94955. } else if (m11 > m22 && m11 > m33) {
  94956. s = 2.0 * OIMO.sqrt(1.0 + m11 - m22 - m33);
  94957. this.w = (m32 - m23) / s;
  94958. this.x = 0.25 * s;
  94959. this.y = (m12 + m21) / s;
  94960. this.z = (m13 + m31) / s;
  94961. } else if (m22 > m33) {
  94962. s = 2.0 * OIMO.sqrt(1.0 + m22 - m11 - m33);
  94963. this.w = (m13 - m31) / s;
  94964. this.x = (m12 + m21) / s;
  94965. this.y = 0.25 * s;
  94966. this.z = (m23 + m32) / s;
  94967. } else {
  94968. s = 2.0 * OIMO.sqrt(1.0 + m33 - m11 - m22);
  94969. this.w = (m21 - m12) / s;
  94970. this.x = (m13 + m31) / s;
  94971. this.y = (m23 + m32) / s;
  94972. this.z = 0.25 * s;
  94973. }
  94974. //this.onChangeCallback();
  94975. return this;
  94976. }
  94977. }
  94978. OIMO.Vec3 = function (x, y, z) {
  94979. this.x = x || 0;
  94980. this.y = y || 0;
  94981. this.z = z || 0;
  94982. };
  94983. OIMO.Vec3.prototype = {
  94984. constructor: OIMO.Vec3,
  94985. init: function (x, y, z) {
  94986. this.x = x || 0;
  94987. this.y = y || 0;
  94988. this.z = z || 0;
  94989. return this;
  94990. },
  94991. set: function (x, y, z) {
  94992. this.x = x;
  94993. this.y = y;
  94994. this.z = z;
  94995. return this;
  94996. },
  94997. add: function (v1, v2) {
  94998. this.x = v1.x + v2.x;
  94999. this.y = v1.y + v2.y;
  95000. this.z = v1.z + v2.z;
  95001. return this;
  95002. },
  95003. addEqual: function (v) {
  95004. this.x += v.x;
  95005. this.y += v.y;
  95006. this.z += v.z;
  95007. return this;
  95008. },
  95009. addTime: function (v, t) {
  95010. this.x += v.x * t;
  95011. this.y += v.y * t;
  95012. this.z += v.z * t;
  95013. return this;
  95014. },
  95015. sub: function (v1, v2) {
  95016. this.x = v1.x - v2.x;
  95017. this.y = v1.y - v2.y;
  95018. this.z = v1.z - v2.z;
  95019. return this;
  95020. },
  95021. subEqual: function (v) {
  95022. this.x -= v.x;
  95023. this.y -= v.y;
  95024. this.z -= v.z;
  95025. return this;
  95026. },
  95027. addScale: function (v, s) {
  95028. this.x += v.x * s;
  95029. this.y += v.y * s;
  95030. this.z += v.z * s;
  95031. return this;
  95032. },
  95033. scale: function (v, s) {
  95034. this.x = v.x * s;
  95035. this.y = v.y * s;
  95036. this.z = v.z * s;
  95037. return this;
  95038. },
  95039. scaleEqual: function (s) {
  95040. this.x *= s;
  95041. this.y *= s;
  95042. this.z *= s;
  95043. return this;
  95044. },
  95045. /*dot: function(v){
  95046. return this.x*v.x+this.y*v.y+this.z*v.z;
  95047. },*/
  95048. cross: function (v1, v2) {
  95049. var ax = v1.x, ay = v1.y, az = v1.z,
  95050. bx = v2.x, by = v2.y, bz = v2.z;
  95051. this.x = ay * bz - az * by;
  95052. this.y = az * bx - ax * bz;
  95053. this.z = ax * by - ay * bx;
  95054. return this;
  95055. },
  95056. mul: function (o, v, m) {
  95057. var te = m.elements;
  95058. this.x = o.x + v.x * te[0] + v.y * te[1] + v.z * te[2];
  95059. this.y = o.y + v.x * te[3] + v.y * te[4] + v.z * te[5];
  95060. this.z = o.z + v.x * te[6] + v.y * te[7] + v.z * te[8];
  95061. return this;
  95062. },
  95063. mulMat: function (m, v) {
  95064. var te = m.elements;
  95065. this.x = te[0] * v.x + te[1] * v.y + te[2] * v.z;
  95066. this.y = te[3] * v.x + te[4] * v.y + te[5] * v.z;
  95067. this.z = te[6] * v.x + te[7] * v.y + te[8] * v.z;
  95068. return this;
  95069. },
  95070. normalize: function (v) {
  95071. var x = v.x, y = v.y, z = v.z;
  95072. var l = x * x + y * y + z * z;
  95073. if (l > 0) {
  95074. l = 1 / OIMO.sqrt(l);
  95075. this.x = x * l;
  95076. this.y = y * l;
  95077. this.z = z * l;
  95078. }
  95079. return this;
  95080. },
  95081. /*norm: function(){
  95082. var x = this.x, y = this.y, z = this.z;
  95083. var l = x*x + y*y + z*z;
  95084. if (l > 0) {
  95085. l = 1 / OIMO.sqrt(l);
  95086. this.x = x*l;
  95087. this.y = y*l;
  95088. this.z = z*l;
  95089. }
  95090. return this;
  95091. },*/
  95092. invert: function (v) {
  95093. this.x = -v.x;
  95094. this.y = -v.y;
  95095. this.z = -v.z;
  95096. return this;
  95097. },
  95098. /*length: function(){
  95099. var x = this.x, y = this.y, z = this.z;
  95100. return OIMO.sqrt(x*x + y*y + z*z);
  95101. },*/
  95102. negate: function () {
  95103. this.x = -this.x;
  95104. this.y = -this.y;
  95105. this.z = -this.z;
  95106. return this;
  95107. },
  95108. dot: function (v) {
  95109. return this.x * v.x + this.y * v.y + this.z * v.z;
  95110. },
  95111. lengthSq: function () {
  95112. return this.x * this.x + this.y * this.y + this.z * this.z;
  95113. },
  95114. length: function () {
  95115. return OIMO.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  95116. },
  95117. /*len: function(){
  95118. var x = this.x, y = this.y, z = this.z;
  95119. return x*x + y*y + z*z;
  95120. },*/
  95121. copy: function (v) {
  95122. this.x = v.x;
  95123. this.y = v.y;
  95124. this.z = v.z;
  95125. return this;
  95126. },
  95127. applyQuaternion: function (q) {
  95128. var x = this.x;
  95129. var y = this.y;
  95130. var z = this.z;
  95131. var qx = q.x;
  95132. var qy = q.y;
  95133. var qz = q.z;
  95134. var qs = q.s;
  95135. // calculate quat * vector
  95136. var ix = qs * x + qy * z - qz * y;
  95137. var iy = qs * y + qz * x - qx * z;
  95138. var iz = qs * z + qx * y - qy * x;
  95139. var iw = -qx * x - qy * y - qz * z;
  95140. // calculate result * inverse quat
  95141. this.x = ix * qs + iw * -qx + iy * -qz - iz * -qy;
  95142. this.y = iy * qs + iw * -qy + iz * -qx - ix * -qz;
  95143. this.z = iz * qs + iw * -qz + ix * -qy - iy * -qx;
  95144. return this;
  95145. },
  95146. testZero: function () {
  95147. if (this.x !== 0 || this.y !== 0 || this.z !== 0) return true;
  95148. else return false;
  95149. },
  95150. testDiff: function (v) {
  95151. return ((v.x !== this.x) || (v.y !== this.y) || (v.z !== this.z));
  95152. //if(this.x!==v.x || this.y!==v.y || this.z!==v.z) return true;
  95153. //else return false;
  95154. },
  95155. equals: function (v) {
  95156. return ((v.x === this.x) && (v.y === this.y) && (v.z === this.z));
  95157. },
  95158. clone: function () {
  95159. return new this.constructor(this.x, this.y, this.z);
  95160. },
  95161. toString: function () {
  95162. return "Vec3[" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + "]";
  95163. },
  95164. multiplyScalar: function (scalar) {
  95165. if (isFinite(scalar)) {
  95166. this.x *= scalar;
  95167. this.y *= scalar;
  95168. this.z *= scalar;
  95169. } else {
  95170. this.x = 0;
  95171. this.y = 0;
  95172. this.z = 0;
  95173. }
  95174. return this;
  95175. },
  95176. divideScalar: function (scalar) {
  95177. return this.multiplyScalar(1 / scalar);
  95178. },
  95179. // TODO rename to normalize
  95180. norm: function () {
  95181. return this.divideScalar(this.length());
  95182. },
  95183. }
  95184. OIMO.Euler = function (x, y, z, order) {
  95185. this._x = x || 0;
  95186. this._y = y || 0;
  95187. this._z = z || 0;
  95188. this._order = order || OIMO.Euler.DefaultOrder;
  95189. };
  95190. OIMO.Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  95191. OIMO.Euler.DefaultOrder = 'XYZ';
  95192. OIMO.clamp = function (x, a, b) {
  95193. return (x < a) ? a : ((x > b) ? b : x);
  95194. }
  95195. OIMO.Euler.prototype = {
  95196. constructor: OIMO.Euler,
  95197. _x: 0, _y: 0, _z: 0, _order: OIMO.Euler.DefaultOrder,
  95198. get x() {
  95199. return this._x;
  95200. },
  95201. set x(value) {
  95202. this._x = value;
  95203. this.onChangeCallback();
  95204. },
  95205. get y() {
  95206. return this._y;
  95207. },
  95208. set y(value) {
  95209. this._y = value;
  95210. this.onChangeCallback();
  95211. },
  95212. get z() {
  95213. return this._z;
  95214. },
  95215. set z(value) {
  95216. this._z = value;
  95217. this.onChangeCallback();
  95218. },
  95219. get order() {
  95220. return this._order;
  95221. },
  95222. set order(value) {
  95223. this._order = value;
  95224. this.onChangeCallback();
  95225. },
  95226. set: function (x, y, z, order) {
  95227. this._x = x;
  95228. this._y = y;
  95229. this._z = z;
  95230. this._order = order || this._order;
  95231. this.onChangeCallback();
  95232. return this;
  95233. },
  95234. copy: function (euler) {
  95235. this._x = euler._x;
  95236. this._y = euler._y;
  95237. this._z = euler._z;
  95238. this._order = euler._order;
  95239. this.onChangeCallback();
  95240. return this;
  95241. },
  95242. setFromRotationMatrix: function (m, order) {
  95243. var clamp = OIMO.clamp;
  95244. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  95245. var te = m.elements;
  95246. /*var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  95247. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  95248. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];*/
  95249. var m11 = te[0], m12 = te[1], m13 = te[2],
  95250. m21 = te[3], m22 = te[4], m23 = te[5],
  95251. m31 = te[6], m32 = te[7], m33 = te[8];
  95252. order = order || this._order;
  95253. if (order === 'XYZ') {
  95254. this._y = OIMO.asin(clamp(m13, -1, 1));
  95255. if (OIMO.abs(m13) < 0.99999) {
  95256. this._x = OIMO.atan2(-m23, m33);
  95257. this._z = OIMO.atan2(-m12, m11);
  95258. } else {
  95259. this._x = OIMO.atan2(m32, m22);
  95260. this._z = 0;
  95261. }
  95262. } else if (order === 'YXZ') {
  95263. this._x = OIMO.asin(-clamp(m23, -1, 1));
  95264. if (OIMO.abs(m23) < 0.99999) {
  95265. this._y = OIMO.atan2(m13, m33);
  95266. this._z = OIMO.atan2(m21, m22);
  95267. } else {
  95268. this._y = OIMO.atan2(-m31, m11);
  95269. this._z = 0;
  95270. }
  95271. } else if (order === 'ZXY') {
  95272. this._x = OIMO.asin(clamp(m32, -1, 1));
  95273. if (OIMO.abs(m32) < 0.99999) {
  95274. this._y = OIMO.atan2(-m31, m33);
  95275. this._z = OIMO.atan2(-m12, m22);
  95276. } else {
  95277. this._y = 0;
  95278. this._z = OIMO.atan2(m21, m11);
  95279. }
  95280. } else if (order === 'ZYX') {
  95281. this._y = OIMO.asin(-clamp(m31, -1, 1));
  95282. if (OIMO.abs(m31) < 0.99999) {
  95283. this._x = OIMO.atan2(m32, m33);
  95284. this._z = OIMO.atan2(m21, m11);
  95285. } else {
  95286. this._x = 0;
  95287. this._z = OIMO.atan2(-m12, m22);
  95288. }
  95289. } else if (order === 'YZX') {
  95290. this._z = OIMO.asin(clamp(m21, -1, 1));
  95291. if (OIMO.abs(m21) < 0.99999) {
  95292. this._x = OIMO.atan2(-m23, m22);
  95293. this._y = OIMO.atan2(-m31, m11);
  95294. } else {
  95295. this._x = 0;
  95296. this._y = OIMO.atan2(m13, m33);
  95297. }
  95298. } else if (order === 'XZY') {
  95299. this._z = OIMO.asin(-clamp(m12, -1, 1));
  95300. if (OIMO.abs(m12) < 0.99999) {
  95301. this._x = OIMO.atan2(m32, m22);
  95302. this._y = OIMO.atan2(m13, m11);
  95303. } else {
  95304. this._x = OIMO.atan2(-m23, m33);
  95305. this._y = 0;
  95306. }
  95307. } else {
  95308. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order)
  95309. }
  95310. this._order = order;
  95311. this.onChangeCallback();
  95312. return this;
  95313. },
  95314. setFromQuaternion: function (q, order, update) {
  95315. var clamp = OIMO.clamp;
  95316. // q is assumed to be normalized
  95317. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  95318. var sqx = q.x * q.x;
  95319. var sqy = q.y * q.y;
  95320. var sqz = q.z * q.z;
  95321. var sqw = q.s * q.s;
  95322. order = order || this._order;
  95323. if (order === 'XYZ') {
  95324. this._x = OIMO.atan2(2 * (q.x * q.s - q.y * q.z), (sqw - sqx - sqy + sqz));
  95325. this._y = OIMO.asin(clamp(2 * (q.x * q.z + q.y * q.s), -1, 1));
  95326. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw + sqx - sqy - sqz));
  95327. } else if (order === 'YXZ') {
  95328. this._x = OIMO.asin(clamp(2 * (q.x * q.s - q.y * q.z), -1, 1));
  95329. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw - sqx - sqy + sqz));
  95330. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw - sqx + sqy - sqz));
  95331. } else if (order === 'ZXY') {
  95332. this._x = OIMO.asin(clamp(2 * (q.x * q.s + q.y * q.z), -1, 1));
  95333. this._y = OIMO.atan2(2 * (q.y * q.s - q.z * q.x), (sqw - sqx - sqy + sqz));
  95334. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw - sqx + sqy - sqz));
  95335. } else if (order === 'ZYX') {
  95336. this._x = OIMO.atan2(2 * (q.x * q.s + q.z * q.y), (sqw - sqx - sqy + sqz));
  95337. this._y = OIMO.asin(clamp(2 * (q.y * q.s - q.x * q.z), -1, 1));
  95338. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw + sqx - sqy - sqz));
  95339. } else if (order === 'YZX') {
  95340. this._x = OIMO.atan2(2 * (q.x * q.s - q.z * q.y), (sqw - sqx + sqy - sqz));
  95341. this._y = OIMO.atan2(2 * (q.y * q.s - q.x * q.z), (sqw + sqx - sqy - sqz));
  95342. this._z = OIMO.asin(clamp(2 * (q.x * q.y + q.z * q.s), -1, 1));
  95343. } else if (order === 'XZY') {
  95344. this._x = OIMO.atan2(2 * (q.x * q.s + q.y * q.z), (sqw - sqx + sqy - sqz));
  95345. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw + sqx - sqy - sqz));
  95346. this._z = OIMO.asin(clamp(2 * (q.z * q.s - q.x * q.y), -1, 1));
  95347. } else {
  95348. console.warn('OIMO.Euler: .setFromQuaternion() given unsupported order: ' + order)
  95349. }
  95350. this._order = order;
  95351. if (update !== false) this.onChangeCallback();
  95352. return this;
  95353. },
  95354. reorder: function () {
  95355. // WARNING: this discards revolution information -bhouston
  95356. var q = new OIMO.Quat();
  95357. return function (newOrder) {
  95358. q.setFromEuler(this);
  95359. this.setFromQuaternion(q, newOrder);
  95360. };
  95361. }(),
  95362. equals: function (euler) {
  95363. return (euler._x === this._x) && (euler._y === this._y) && (euler._z === this._z) && (euler._order === this._order);
  95364. },
  95365. fromArray: function (array) {
  95366. this._x = array[0];
  95367. this._y = array[1];
  95368. this._z = array[2];
  95369. if (array[3] !== undefined) this._order = array[3];
  95370. this.onChangeCallback();
  95371. return this;
  95372. },
  95373. toArray: function () {
  95374. return [this._x, this._y, this._z, this._order];
  95375. },
  95376. onChange: function (callback) {
  95377. this.onChangeCallback = callback;
  95378. return this;
  95379. },
  95380. onChangeCallback: function () { },
  95381. clone: function () {
  95382. return new OIMO.Euler(this._x, this._y, this._z, this._order);
  95383. }
  95384. };
  95385. OIMO.EulerToAxis = function (ox, oy, oz) {// angles in radians
  95386. var c1 = OIMO.cos(oy * 0.5);//heading
  95387. var s1 = OIMO.sin(oy * 0.5);
  95388. var c2 = OIMO.cos(oz * 0.5);//altitude
  95389. var s2 = OIMO.sin(oz * 0.5);
  95390. var c3 = OIMO.cos(ox * 0.5);//bank
  95391. var s3 = OIMO.sin(ox * 0.5);
  95392. var c1c2 = c1 * c2;
  95393. var s1s2 = s1 * s2;
  95394. var w = c1c2 * c3 - s1s2 * s3;
  95395. var x = c1c2 * s3 + s1s2 * c3;
  95396. var y = s1 * c2 * c3 + c1 * s2 * s3;
  95397. var z = c1 * s2 * c3 - s1 * c2 * s3;
  95398. var angle = 2 * OIMO.acos(w);
  95399. var norm = x * x + y * y + z * z;
  95400. if (norm < 0.001) {
  95401. x = 1;
  95402. y = z = 0;
  95403. } else {
  95404. norm = OIMO.sqrt(norm);
  95405. x /= norm;
  95406. y /= norm;
  95407. z /= norm;
  95408. }
  95409. return [angle, x, y, z];
  95410. }
  95411. OIMO.EulerToMatrix = function (ox, oy, oz) {// angles in radians
  95412. var ch = OIMO.cos(oy);//heading
  95413. var sh = OIMO.sin(oy);
  95414. var ca = OIMO.cos(oz);//altitude
  95415. var sa = OIMO.sin(oz);
  95416. var cb = OIMO.cos(ox);//bank
  95417. var sb = OIMO.sin(ox);
  95418. var mtx = new OIMO.Mat33();
  95419. var te = mtx.elements;
  95420. te[0] = ch * ca;
  95421. te[1] = sh * sb - ch * sa * cb;
  95422. te[2] = ch * sa * sb + sh * cb;
  95423. te[3] = sa;
  95424. te[4] = ca * cb;
  95425. te[5] = -ca * sb;
  95426. te[6] = -sh * ca;
  95427. te[7] = sh * sa * cb + ch * sb;
  95428. te[8] = -sh * sa * sb + ch * cb;
  95429. return mtx;
  95430. }
  95431. OIMO.MatrixToEuler = function (mtx) {// angles in radians
  95432. var te = mtx.elements;
  95433. var x, y, z;
  95434. if (te[3] > 0.998) { // singularity at north pole
  95435. y = OIMO.atan2(te[2], te[8]);
  95436. z = OIMO.PI / 2;
  95437. x = 0;
  95438. } else if (te[3] < -0.998) { // singularity at south pole
  95439. y = OIMO.atan2(te[2], te[8]);
  95440. z = -OIMO.PI / 2;
  95441. x = 0;
  95442. } else {
  95443. y = OIMO.atan2(-te[6], te[0]);
  95444. x = OIMO.atan2(-te[5], te[4]);
  95445. z = OIMO.asin(te[3]);
  95446. }
  95447. return [x, y, z];
  95448. }
  95449. OIMO.unwrapDegrees = function (r) {
  95450. r = r % 360;
  95451. if (r > 180) r -= 360;
  95452. if (r < -180) r += 360;
  95453. return r;
  95454. }
  95455. OIMO.unwrapRadian = function (r) {
  95456. r = r % OIMO.TwoPI;
  95457. if (r > OIMO.PI) r -= OIMO.TwoPI;
  95458. if (r < -OIMO.PI) r += OIMO.TwoPI;
  95459. return r;
  95460. }
  95461. OIMO.Distance3d = function (p1, p2) {
  95462. var xd = p2[0] - p1[0];
  95463. var yd = p2[1] - p1[1];
  95464. var zd = p2[2] - p1[2];
  95465. return OIMO.sqrt(xd * xd + yd * yd + zd * zd);
  95466. }
  95467. /**
  95468. * The base class of all type of the constraints.
  95469. * @author saharan
  95470. */
  95471. OIMO.Constraint = function () {
  95472. // The parent world of the constraint.
  95473. this.parent = null;
  95474. // The first body of the constraint.
  95475. this.body1 = null;
  95476. // The second body of the constraint.
  95477. this.body2 = null;
  95478. // Internal
  95479. this.addedToIsland = false;
  95480. }
  95481. OIMO.Constraint.prototype = {
  95482. constructor: OIMO.Constraint,
  95483. /**
  95484. * Prepare for solving the constraint.
  95485. * @param timeStep
  95486. * @param invTimeStep
  95487. */
  95488. preSolve: function (timeStep, invTimeStep) {
  95489. OIMO.Error("Constraint", "Inheritance error.");
  95490. },
  95491. /**
  95492. * Solve the constraint.
  95493. * This is usually called iteratively.
  95494. */
  95495. solve: function () {
  95496. OIMO.Error("Constraint", "Inheritance error.");
  95497. },
  95498. /**
  95499. * Do the post-processing.
  95500. */
  95501. postSolve: function () {
  95502. OIMO.Error("Constraint", "Inheritance error.");
  95503. }
  95504. }
  95505. /**
  95506. * Joints are used to constrain the motion between two rigid bodies.
  95507. * @author saharan
  95508. * @author lo-th
  95509. */
  95510. OIMO.Joint = function (config) {
  95511. OIMO.Constraint.call(this);
  95512. // joint name
  95513. this.name = "";
  95514. // The type of the joint.
  95515. this.type = OIMO.JOINT_NULL;
  95516. // The previous joint in the world.
  95517. this.prev = null;
  95518. // The next joint in the world.
  95519. this.next = null;
  95520. this.body1 = config.body1;
  95521. this.body2 = config.body2;
  95522. // The anchor point on the first rigid body in local coordinate system.
  95523. this.localAnchorPoint1 = new OIMO.Vec3().copy(config.localAnchorPoint1);
  95524. // The anchor point on the second rigid body in local coordinate system.
  95525. this.localAnchorPoint2 = new OIMO.Vec3().copy(config.localAnchorPoint2);
  95526. // The anchor point on the first rigid body in world coordinate system relative to the body's origin.
  95527. this.relativeAnchorPoint1 = new OIMO.Vec3();
  95528. // The anchor point on the second rigid body in world coordinate system relative to the body's origin.
  95529. this.relativeAnchorPoint2 = new OIMO.Vec3();
  95530. // The anchor point on the first rigid body in world coordinate system.
  95531. this.anchorPoint1 = new OIMO.Vec3();
  95532. // The anchor point on the second rigid body in world coordinate system.
  95533. this.anchorPoint2 = new OIMO.Vec3();
  95534. // Whether allow collision between connected rigid bodies or not.
  95535. this.allowCollision = config.allowCollision;
  95536. this.b1Link = new OIMO.JointLink(this);
  95537. this.b2Link = new OIMO.JointLink(this);
  95538. this.matrix = new OIMO.Mat44();
  95539. };
  95540. OIMO.Joint.prototype = Object.create(OIMO.Constraint.prototype);
  95541. OIMO.Joint.prototype.constructor = OIMO.Joint;
  95542. // Update all the anchor points.
  95543. OIMO.Joint.prototype.updateAnchorPoints = function () {
  95544. this.relativeAnchorPoint1.mulMat(this.body1.rotation, this.localAnchorPoint1);
  95545. this.relativeAnchorPoint2.mulMat(this.body2.rotation, this.localAnchorPoint2);
  95546. this.anchorPoint1.add(this.relativeAnchorPoint1, this.body1.position);
  95547. this.anchorPoint2.add(this.relativeAnchorPoint2, this.body2.position);
  95548. };
  95549. // Attach the joint from the bodies.
  95550. OIMO.Joint.prototype.attach = function () {
  95551. this.b1Link.body = this.body2;
  95552. this.b2Link.body = this.body1;
  95553. if (this.body1.jointLink != null) (this.b1Link.next = this.body1.jointLink).prev = this.b1Link;
  95554. else this.b1Link.next = null;
  95555. this.body1.jointLink = this.b1Link;
  95556. this.body1.numJoints++;
  95557. if (this.body2.jointLink != null) (this.b2Link.next = this.body2.jointLink).prev = this.b2Link;
  95558. else this.b2Link.next = null;
  95559. this.body2.jointLink = this.b2Link;
  95560. this.body2.numJoints++;
  95561. };
  95562. // Detach the joint from the bodies.
  95563. OIMO.Joint.prototype.detach = function () {
  95564. var prev = this.b1Link.prev;
  95565. var next = this.b1Link.next;
  95566. if (prev != null) prev.next = next;
  95567. if (next != null) next.prev = prev;
  95568. if (this.body1.jointLink == this.b1Link) this.body1.jointLink = next;
  95569. this.b1Link.prev = null;
  95570. this.b1Link.next = null;
  95571. this.b1Link.body = null;
  95572. this.body1.numJoints--;
  95573. prev = this.b2Link.prev;
  95574. next = this.b2Link.next;
  95575. if (prev != null) prev.next = next;
  95576. if (next != null) next.prev = prev;
  95577. if (this.body2.jointLink == this.b2Link) this.body2.jointLink = next;
  95578. this.b2Link.prev = null;
  95579. this.b2Link.next = null;
  95580. this.b2Link.body = null;
  95581. this.body2.numJoints--;
  95582. this.b1Link.body = null;
  95583. this.b2Link.body = null;
  95584. };
  95585. // Awake the bodies.
  95586. OIMO.Joint.prototype.awake = function () {
  95587. this.body1.awake();
  95588. this.body2.awake();
  95589. };
  95590. // calculation function
  95591. OIMO.Joint.prototype.preSolve = function (timeStep, invTimeStep) {
  95592. };
  95593. OIMO.Joint.prototype.solve = function () {
  95594. };
  95595. OIMO.Joint.prototype.postSolve = function () {
  95596. };
  95597. // Delete process
  95598. OIMO.Joint.prototype.remove = function () {
  95599. this.dispose();
  95600. };
  95601. OIMO.Joint.prototype.dispose = function () {
  95602. this.parent.removeJoint(this);
  95603. };
  95604. // Three js add
  95605. OIMO.Joint.prototype.getPosition = function () {
  95606. var p1 = new OIMO.Vec3().scale(this.anchorPoint1, OIMO.WORLD_SCALE);
  95607. var p2 = new OIMO.Vec3().scale(this.anchorPoint2, OIMO.WORLD_SCALE);
  95608. return [p1, p2];
  95609. };
  95610. OIMO.Joint.prototype.getMatrix = function () {
  95611. var m = this.matrix.elements;
  95612. var p1 = this.anchorPoint1;
  95613. var p2 = this.anchorPoint2;
  95614. m[0] = p1.x * OIMO.WORLD_SCALE;
  95615. m[1] = p1.y * OIMO.WORLD_SCALE;
  95616. m[2] = p1.z * OIMO.WORLD_SCALE;
  95617. m[3] = 0;
  95618. m[4] = p2.x * OIMO.WORLD_SCALE;
  95619. m[5] = p2.y * OIMO.WORLD_SCALE;
  95620. m[6] = p2.z * OIMO.WORLD_SCALE;
  95621. m[7] = 0;
  95622. return m;
  95623. };
  95624. /**
  95625. * A joint configuration holds all configuration data for constructing a joint.
  95626. * Joint configurations can be reused safely.
  95627. * @author saharan
  95628. */
  95629. OIMO.JointConfig = function () {
  95630. // The first rigid body of the joint.
  95631. this.body1 = null;
  95632. // The second rigid body of the joint.
  95633. this.body2 = null;
  95634. // The anchor point on the first rigid body in local coordinate system.
  95635. this.localAnchorPoint1 = new OIMO.Vec3();
  95636. // The anchor point on the second rigid body in local coordinate system.
  95637. this.localAnchorPoint2 = new OIMO.Vec3();
  95638. // The axis in the first body's coordinate system.
  95639. // his property is available in some joints.
  95640. this.localAxis1 = new OIMO.Vec3();
  95641. // The axis in the second body's coordinate system.
  95642. // This property is available in some joints.
  95643. this.localAxis2 = new OIMO.Vec3();
  95644. // Whether allow collision between connected rigid bodies or not.
  95645. this.allowCollision = false;
  95646. };
  95647. /**
  95648. * A link list of joints.
  95649. * @author saharan
  95650. */
  95651. OIMO.JointLink = function (joint) {
  95652. // The previous joint link.
  95653. this.prev = null;
  95654. // The next joint link.
  95655. this.next = null;
  95656. // The other rigid body connected to the joint.
  95657. this.body = null;
  95658. // The joint of the link.
  95659. this.joint = joint;
  95660. };
  95661. /**
  95662. * An information of limit and motor.
  95663. * @author saharan
  95664. */
  95665. OIMO.LimitMotor = function (axis, fixed) {
  95666. fixed = fixed || false;
  95667. // The axis of the constraint.
  95668. this.axis = axis;
  95669. // The current angle for rotational constraints.
  95670. this.angle = 0;
  95671. // The lower limit. Set lower > upper to disable
  95672. this.lowerLimit = fixed ? 0 : 1;
  95673. //if(fixed)this.lowerLimit = 0;
  95674. //else this.lowerLimit = 1;
  95675. // The upper limit. Set lower > upper to disable.
  95676. this.upperLimit = 0;
  95677. // The target motor speed.
  95678. this.motorSpeed = 0;
  95679. // The maximum motor force or torque. Set 0 to disable.
  95680. this.maxMotorForce = 0;
  95681. // The frequency of the spring. Set 0 to disable.
  95682. this.frequency = 0;
  95683. // The damping ratio of the spring. Set 0 for no damping, 1 for critical damping.
  95684. this.dampingRatio = 0;
  95685. };
  95686. OIMO.LimitMotor.prototype = {
  95687. constructor: OIMO.LimitMotor,
  95688. /**
  95689. * Set limit data into this constraint.
  95690. * @param lowerLimit
  95691. * @param upperLimit
  95692. */
  95693. setLimit: function (lowerLimit, upperLimit) {
  95694. this.lowerLimit = lowerLimit;
  95695. this.upperLimit = upperLimit;
  95696. },
  95697. /**
  95698. * Set motor data into this constraint.
  95699. * @param motorSpeed
  95700. * @param maxMotorForce
  95701. */
  95702. setMotor: function (motorSpeed, maxMotorForce) {
  95703. this.motorSpeed = motorSpeed;
  95704. this.maxMotorForce = maxMotorForce;
  95705. },
  95706. /**
  95707. * Set spring data into this constraint.
  95708. * @param frequency
  95709. * @param dampingRatio
  95710. */
  95711. setSpring: function (frequency, dampingRatio) {
  95712. this.frequency = frequency;
  95713. this.dampingRatio = dampingRatio;
  95714. }
  95715. };
  95716. /**
  95717. * A ball-and-socket joint limits relative translation on two anchor points on rigid bodies.
  95718. * @author saharan
  95719. * @author lo-th
  95720. */
  95721. OIMO.BallAndSocketJoint = function (config) {
  95722. OIMO.Joint.call(this, config);
  95723. this.type = OIMO.JOINT_BALL_AND_SOCKET;
  95724. this.lc = new OIMO.LinearConstraint(this);
  95725. };
  95726. OIMO.BallAndSocketJoint.prototype = Object.create(OIMO.Joint.prototype);
  95727. OIMO.BallAndSocketJoint.prototype.constructor = OIMO.BallAndSocketJoint;
  95728. OIMO.BallAndSocketJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95729. this.updateAnchorPoints();
  95730. this.lc.preSolve(timeStep, invTimeStep);
  95731. };
  95732. OIMO.BallAndSocketJoint.prototype.solve = function () {
  95733. this.lc.solve();
  95734. };
  95735. OIMO.BallAndSocketJoint.prototype.postSolve = function () {
  95736. };
  95737. /**
  95738. * A distance joint limits the distance between two anchor points on rigid bodies.
  95739. * @author saharan
  95740. * @author lo-th
  95741. */
  95742. OIMO.DistanceJoint = function (config, minDistance, maxDistance) {
  95743. OIMO.Joint.call(this, config);
  95744. this.type = OIMO.JOINT_DISTANCE;
  95745. this.normal = new OIMO.Vec3();
  95746. this.nr = new OIMO.Vec3();
  95747. // The limit and motor information of the joint.
  95748. this.limitMotor = new OIMO.LimitMotor(this.normal, true);
  95749. this.limitMotor.lowerLimit = minDistance;
  95750. this.limitMotor.upperLimit = maxDistance;
  95751. this.t = new OIMO.TranslationalConstraint(this, this.limitMotor);
  95752. };
  95753. OIMO.DistanceJoint.prototype = Object.create(OIMO.Joint.prototype);
  95754. OIMO.DistanceJoint.prototype.constructor = OIMO.DistanceJoint;
  95755. OIMO.DistanceJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95756. this.updateAnchorPoints();
  95757. //var nr = this.nr;
  95758. this.nr.sub(this.anchorPoint2, this.anchorPoint1);
  95759. //var len = OIMO.sqrt( nr.x*nr.x + nr.y*nr.y + nr.z*nr.z );
  95760. //if(len>0) len = 1/len;
  95761. //this.normal.scale( nr, len );
  95762. this.normal.normalize(this.nr);
  95763. this.t.preSolve(timeStep, invTimeStep);
  95764. };
  95765. OIMO.DistanceJoint.prototype.solve = function () {
  95766. this.t.solve();
  95767. };
  95768. OIMO.DistanceJoint.prototype.postSolve = function () {
  95769. };
  95770. /**
  95771. * A hinge joint allows only for relative rotation of rigid bodies along the axis.
  95772. * @author saharan
  95773. * @author lo-th
  95774. */
  95775. OIMO.HingeJoint = function (config, lowerAngleLimit, upperAngleLimit) {
  95776. OIMO.Joint.call(this, config);
  95777. this.type = OIMO.JOINT_HINGE;
  95778. // The axis in the first body's coordinate system.
  95779. this.localAxis1 = config.localAxis1.clone().norm();
  95780. // The axis in the second body's coordinate system.
  95781. this.localAxis2 = config.localAxis2.clone().norm();
  95782. // make angle axis 1
  95783. this.localAngle1 = new OIMO.Vec3(
  95784. this.localAxis1.y * this.localAxis1.x - this.localAxis1.z * this.localAxis1.z,
  95785. -this.localAxis1.z * this.localAxis1.y - this.localAxis1.x * this.localAxis1.x,
  95786. this.localAxis1.x * this.localAxis1.z + this.localAxis1.y * this.localAxis1.y
  95787. ).norm();
  95788. // make angle axis 2
  95789. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  95790. this.localAngle2 = new OIMO.Vec3().mulMat(arc, this.localAngle1);
  95791. this.nor = new OIMO.Vec3();
  95792. this.tan = new OIMO.Vec3();
  95793. this.bin = new OIMO.Vec3();
  95794. this.ax1 = new OIMO.Vec3();
  95795. this.ax2 = new OIMO.Vec3();
  95796. this.an1 = new OIMO.Vec3();
  95797. this.an2 = new OIMO.Vec3();
  95798. // The rotational limit and motor information of the joint.
  95799. this.limitMotor = new OIMO.LimitMotor(this.nor, false);
  95800. this.limitMotor.lowerLimit = lowerAngleLimit;
  95801. this.limitMotor.upperLimit = upperAngleLimit;
  95802. this.lc = new OIMO.LinearConstraint(this);
  95803. this.r3 = new OIMO.Rotational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95804. };
  95805. OIMO.HingeJoint.prototype = Object.create(OIMO.Joint.prototype);
  95806. OIMO.HingeJoint.prototype.constructor = OIMO.HingeJoint;
  95807. OIMO.HingeJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95808. var tmp1X, tmp1Y, tmp1Z, limite;//, nx, ny, nz, tx, ty, tz, bx, by, bz;
  95809. this.updateAnchorPoints();
  95810. this.ax1.mulMat(this.body1.rotation, this.localAxis1);
  95811. this.ax2.mulMat(this.body2.rotation, this.localAxis2);
  95812. this.an1.mulMat(this.body1.rotation, this.localAngle1);
  95813. this.an2.mulMat(this.body2.rotation, this.localAngle2);
  95814. this.nor.set(
  95815. this.ax1.x * this.body2.inverseMass + this.ax2.x * this.body1.inverseMass,
  95816. this.ax1.y * this.body2.inverseMass + this.ax2.y * this.body1.inverseMass,
  95817. this.ax1.z * this.body2.inverseMass + this.ax2.z * this.body1.inverseMass
  95818. ).norm();
  95819. this.tan.set(
  95820. this.nor.y * this.nor.x - this.nor.z * this.nor.z,
  95821. -this.nor.z * this.nor.y - this.nor.x * this.nor.x,
  95822. this.nor.x * this.nor.z + this.nor.y * this.nor.y
  95823. ).norm();
  95824. this.bin.set(
  95825. this.nor.y * this.tan.z - this.nor.z * this.tan.y,
  95826. this.nor.z * this.tan.x - this.nor.x * this.tan.z,
  95827. this.nor.x * this.tan.y - this.nor.y * this.tan.x
  95828. );
  95829. // calculate hinge angle
  95830. limite = this.acosClamp(this.an1.x * this.an2.x + this.an1.y * this.an2.y + this.an1.z * this.an2.z)
  95831. if (
  95832. this.nor.x * (this.an1.y * this.an2.z - this.an1.z * this.an2.y) +
  95833. this.nor.y * (this.an1.z * this.an2.x - this.an1.x * this.an2.z) +
  95834. this.nor.z * (this.an1.x * this.an2.y - this.an1.y * this.an2.x) < 0
  95835. ) {
  95836. this.limitMotor.angle = -limite;
  95837. } else {
  95838. this.limitMotor.angle = limite;
  95839. }
  95840. tmp1X = this.ax1.y * this.ax2.z - this.ax1.z * this.ax2.y;
  95841. tmp1Y = this.ax1.z * this.ax2.x - this.ax1.x * this.ax2.z;
  95842. tmp1Z = this.ax1.x * this.ax2.y - this.ax1.y * this.ax2.x;
  95843. this.r3.limitMotor2.angle = this.tan.x * tmp1X + this.tan.y * tmp1Y + this.tan.z * tmp1Z;
  95844. this.r3.limitMotor3.angle = this.bin.x * tmp1X + this.bin.y * tmp1Y + this.bin.z * tmp1Z;
  95845. this.r3.preSolve(timeStep, invTimeStep);
  95846. this.lc.preSolve(timeStep, invTimeStep);
  95847. };
  95848. OIMO.HingeJoint.prototype.solve = function () {
  95849. this.r3.solve();
  95850. this.lc.solve();
  95851. };
  95852. OIMO.HingeJoint.prototype.postSolve = function () {
  95853. };
  95854. OIMO.HingeJoint.prototype.acosClamp = function (cos) {
  95855. if (cos > 1) return 0;
  95856. else if (cos < -1) return OIMO.PI;
  95857. else return OIMO.acos(cos);
  95858. };
  95859. /**
  95860. * A prismatic joint allows only for relative translation of rigid bodies along the axis.
  95861. * @author saharan
  95862. * @author lo-th
  95863. */
  95864. OIMO.PrismaticJoint = function (config, lowerTranslation, upperTranslation) {
  95865. OIMO.Joint.call(this, config);
  95866. this.type = OIMO.JOINT_PRISMATIC;
  95867. // The axis in the first body's coordinate system.
  95868. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  95869. // The axis in the second body's coordinate system.
  95870. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  95871. this.localAxis1X = this.localAxis1.x;
  95872. this.localAxis1Y = this.localAxis1.y;
  95873. this.localAxis1Z = this.localAxis1.z;
  95874. this.localAxis2X = this.localAxis2.x;
  95875. this.localAxis2Y = this.localAxis2.y;
  95876. this.localAxis2Z = this.localAxis2.z;
  95877. this.nor = new OIMO.Vec3();
  95878. this.tan = new OIMO.Vec3();
  95879. this.bin = new OIMO.Vec3();
  95880. this.ac = new OIMO.AngularConstraint(this, new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  95881. // The translational limit and motor information of the joint.
  95882. this.limitMotor = new OIMO.LimitMotor(this.nor, true);
  95883. this.limitMotor.lowerLimit = lowerTranslation;
  95884. this.limitMotor.upperLimit = upperTranslation;
  95885. this.t3 = new OIMO.Translational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95886. };
  95887. OIMO.PrismaticJoint.prototype = Object.create(OIMO.Joint.prototype);
  95888. OIMO.PrismaticJoint.prototype.constructor = OIMO.PrismaticJoint;
  95889. OIMO.PrismaticJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95890. var tmpM;
  95891. var tmp1X;
  95892. var tmp1Y;
  95893. var tmp1Z;
  95894. this.updateAnchorPoints();
  95895. tmpM = this.body1.rotation.elements;
  95896. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  95897. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  95898. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  95899. tmpM = this.body2.rotation.elements;
  95900. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  95901. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  95902. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  95903. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  95904. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  95905. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  95906. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  95907. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95908. nx *= tmp1X;
  95909. ny *= tmp1X;
  95910. nz *= tmp1X;
  95911. var tx = ny * nx - nz * nz;
  95912. var ty = -nz * ny - nx * nx;
  95913. var tz = nx * nz + ny * ny;
  95914. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  95915. tx *= tmp1X;
  95916. ty *= tmp1X;
  95917. tz *= tmp1X;
  95918. var bx = ny * tz - nz * ty;
  95919. var by = nz * tx - nx * tz;
  95920. var bz = nx * ty - ny * tx;
  95921. this.nor.init(nx, ny, nz);
  95922. this.tan.init(tx, ty, tz);
  95923. this.bin.init(bx, by, bz);
  95924. this.ac.preSolve(timeStep, invTimeStep);
  95925. this.t3.preSolve(timeStep, invTimeStep);
  95926. };
  95927. OIMO.PrismaticJoint.prototype.solve = function () {
  95928. this.ac.solve();
  95929. this.t3.solve();
  95930. };
  95931. OIMO.PrismaticJoint.prototype.postSolve = function () {
  95932. };
  95933. /**
  95934. * A slider joint allows for relative translation and relative rotation between two rigid bodies along the axis.
  95935. * @author saharan
  95936. * @author lo-th
  95937. */
  95938. OIMO.SliderJoint = function (config, lowerTranslation, upperTranslation) {
  95939. OIMO.Joint.call(this, config);
  95940. this.type = OIMO.JOINT_SLIDER;
  95941. // The first axis in local coordinate system.
  95942. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  95943. // The second axis in local coordinate system.
  95944. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  95945. var len;
  95946. this.localAxis1X = this.localAxis1.x;
  95947. this.localAxis1Y = this.localAxis1.y;
  95948. this.localAxis1Z = this.localAxis1.z;
  95949. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  95950. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  95951. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  95952. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  95953. this.localAngAxis1X *= len;
  95954. this.localAngAxis1Y *= len;
  95955. this.localAngAxis1Z *= len;
  95956. this.localAxis2X = this.localAxis2.x;
  95957. this.localAxis2Y = this.localAxis2.y;
  95958. this.localAxis2Z = this.localAxis2.z;
  95959. // make angle axis 2
  95960. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  95961. var tarc = arc.elements;
  95962. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  95963. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  95964. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  95965. this.nor = new OIMO.Vec3();
  95966. this.tan = new OIMO.Vec3();
  95967. this.bin = new OIMO.Vec3();
  95968. // The limit and motor for the rotation
  95969. this.rotationalLimitMotor = new OIMO.LimitMotor(this.nor, false);
  95970. this.r3 = new OIMO.Rotational3Constraint(this, this.rotationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95971. // The limit and motor for the translation.
  95972. this.translationalLimitMotor = new OIMO.LimitMotor(this.nor, true);
  95973. this.translationalLimitMotor.lowerLimit = lowerTranslation;
  95974. this.translationalLimitMotor.upperLimit = upperTranslation;
  95975. this.t3 = new OIMO.Translational3Constraint(this, this.translationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95976. };
  95977. OIMO.SliderJoint.prototype = Object.create(OIMO.Joint.prototype);
  95978. OIMO.SliderJoint.prototype.constructor = OIMO.SliderJoint;
  95979. OIMO.SliderJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95980. var tmpM;
  95981. var tmp1X;
  95982. var tmp1Y;
  95983. var tmp1Z;
  95984. this.updateAnchorPoints();
  95985. tmpM = this.body1.rotation.elements;
  95986. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  95987. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  95988. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  95989. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  95990. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  95991. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  95992. tmpM = this.body2.rotation.elements;
  95993. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  95994. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  95995. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  95996. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  95997. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  95998. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  95999. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  96000. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  96001. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  96002. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  96003. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  96004. nx *= tmp1X;
  96005. ny *= tmp1X;
  96006. nz *= tmp1X;
  96007. var tx = ny * nx - nz * nz;
  96008. var ty = -nz * ny - nx * nx;
  96009. var tz = nx * nz + ny * ny;
  96010. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  96011. tx *= tmp1X;
  96012. ty *= tmp1X;
  96013. tz *= tmp1X;
  96014. var bx = ny * tz - nz * ty;
  96015. var by = nz * tx - nx * tz;
  96016. var bz = nx * ty - ny * tx;
  96017. this.nor.init(nx, ny, nz);
  96018. this.tan.init(tx, ty, tz);
  96019. this.bin.init(bx, by, bz);
  96020. // ----------------------------------------------
  96021. // calculate hinge angle
  96022. // ----------------------------------------------
  96023. if (
  96024. nx * (angAxis1Y * angAxis2Z - angAxis1Z * angAxis2Y) +
  96025. ny * (angAxis1Z * angAxis2X - angAxis1X * angAxis2Z) +
  96026. nz * (angAxis1X * angAxis2Y - angAxis1Y * angAxis2X) < 0
  96027. ) {
  96028. this.rotationalLimitMotor.angle = -this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  96029. } else {
  96030. this.rotationalLimitMotor.angle = this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  96031. }
  96032. // angular error
  96033. tmp1X = axis1Y * axis2Z - axis1Z * axis2Y;
  96034. tmp1Y = axis1Z * axis2X - axis1X * axis2Z;
  96035. tmp1Z = axis1X * axis2Y - axis1Y * axis2X;
  96036. this.r3.limitMotor2.angle = tx * tmp1X + ty * tmp1Y + tz * tmp1Z;
  96037. this.r3.limitMotor3.angle = bx * tmp1X + by * tmp1Y + bz * tmp1Z;
  96038. this.r3.preSolve(timeStep, invTimeStep);
  96039. this.t3.preSolve(timeStep, invTimeStep);
  96040. };
  96041. OIMO.SliderJoint.prototype.solve = function () {
  96042. this.r3.solve();
  96043. this.t3.solve();
  96044. };
  96045. OIMO.SliderJoint.prototype.postSolve = function () {
  96046. };
  96047. OIMO.SliderJoint.prototype.acosClamp = function (cos) {
  96048. if (cos > 1) return 0;
  96049. else if (cos < -1) return OIMO.PI;
  96050. else return OIMO.acos(cos);
  96051. };
  96052. /**
  96053. * A wheel joint allows for relative rotation between two rigid bodies along two axes.
  96054. * The wheel joint also allows for relative translation for the suspension.
  96055. * @author saharan
  96056. * @author lo-th
  96057. */
  96058. OIMO.WheelJoint = function (config) {
  96059. OIMO.Joint.call(this, config);
  96060. this.type = OIMO.JOINT_WHEEL;
  96061. // The first axis in local coordinate system.
  96062. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  96063. // The second axis in local coordinate system.
  96064. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  96065. var len;
  96066. this.localAxis1X = this.localAxis1.x;
  96067. this.localAxis1Y = this.localAxis1.y;
  96068. this.localAxis1Z = this.localAxis1.z;
  96069. this.localAxis2X = this.localAxis2.x;
  96070. this.localAxis2Y = this.localAxis2.y;
  96071. this.localAxis2Z = this.localAxis2.z;
  96072. var dot = this.localAxis1X * this.localAxis2X + this.localAxis1Y * this.localAxis2Y + this.localAxis1Z * this.localAxis2Z;
  96073. if (dot > -1 && dot < 1) {
  96074. this.localAngAxis1X = this.localAxis2X - dot * this.localAxis1X;
  96075. this.localAngAxis1Y = this.localAxis2Y - dot * this.localAxis1Y;
  96076. this.localAngAxis1Z = this.localAxis2Z - dot * this.localAxis1Z;
  96077. this.localAngAxis2X = this.localAxis1X - dot * this.localAxis2X;
  96078. this.localAngAxis2Y = this.localAxis1Y - dot * this.localAxis2Y;
  96079. this.localAngAxis2Z = this.localAxis1Z - dot * this.localAxis2Z;
  96080. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  96081. this.localAngAxis1X *= len;
  96082. this.localAngAxis1Y *= len;
  96083. this.localAngAxis1Z *= len;
  96084. len = 1 / OIMO.sqrt(this.localAngAxis2X * this.localAngAxis2X + this.localAngAxis2Y * this.localAngAxis2Y + this.localAngAxis2Z * this.localAngAxis2Z);
  96085. this.localAngAxis2X *= len;
  96086. this.localAngAxis2Y *= len;
  96087. this.localAngAxis2Z *= len;
  96088. } else {
  96089. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  96090. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  96091. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  96092. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  96093. this.localAngAxis1X *= len;
  96094. this.localAngAxis1Y *= len;
  96095. this.localAngAxis1Z *= len;
  96096. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  96097. var tarc = arc.elements;
  96098. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  96099. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  96100. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  96101. }
  96102. this.nor = new OIMO.Vec3();
  96103. this.tan = new OIMO.Vec3();
  96104. this.bin = new OIMO.Vec3();
  96105. // The translational limit and motor information of the joint.
  96106. this.translationalLimitMotor = new OIMO.LimitMotor(this.tan, true);
  96107. this.translationalLimitMotor.frequency = 8;
  96108. this.translationalLimitMotor.dampingRatio = 1;
  96109. // The first rotational limit and motor information of the joint.
  96110. this.rotationalLimitMotor1 = new OIMO.LimitMotor(this.tan, false);
  96111. // The second rotational limit and motor information of the joint.
  96112. this.rotationalLimitMotor2 = new OIMO.LimitMotor(this.bin, false);
  96113. this.t3 = new OIMO.Translational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.translationalLimitMotor, new OIMO.LimitMotor(this.bin, true));
  96114. this.t3.weight = 1;
  96115. this.r3 = new OIMO.Rotational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.rotationalLimitMotor1, this.rotationalLimitMotor2);
  96116. };
  96117. OIMO.WheelJoint.prototype = Object.create(OIMO.Joint.prototype);
  96118. OIMO.WheelJoint.prototype.constructor = OIMO.WheelJoint;
  96119. OIMO.WheelJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  96120. var tmpM;
  96121. var tmp1X;
  96122. var tmp1Y;
  96123. var tmp1Z;
  96124. this.updateAnchorPoints();
  96125. tmpM = this.body1.rotation.elements;
  96126. var x1 = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  96127. var y1 = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  96128. var z1 = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  96129. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  96130. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  96131. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  96132. tmpM = this.body2.rotation.elements;
  96133. var x2 = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  96134. var y2 = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  96135. var z2 = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  96136. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  96137. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  96138. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  96139. this.r3.limitMotor1.angle = x1 * x2 + y1 * y2 + z1 * z2;
  96140. if (x1 * (angAxis1Y * z2 - angAxis1Z * y2) + y1 * (angAxis1Z * x2 - angAxis1X * z2) + z1 * (angAxis1X * y2 - angAxis1Y * x2) < 0) {
  96141. this.rotationalLimitMotor1.angle = -this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  96142. } else {
  96143. this.rotationalLimitMotor1.angle = this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  96144. }
  96145. if (x2 * (angAxis2Y * z1 - angAxis2Z * y1) + y2 * (angAxis2Z * x1 - angAxis2X * z1) + z2 * (angAxis2X * y1 - angAxis2Y * x1) < 0) {
  96146. this.rotationalLimitMotor2.angle = this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  96147. } else {
  96148. this.rotationalLimitMotor2.angle = -this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  96149. }
  96150. var nx = y2 * z1 - z2 * y1;
  96151. var ny = z2 * x1 - x2 * z1;
  96152. var nz = x2 * y1 - y2 * x1;
  96153. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  96154. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  96155. nx *= tmp1X;
  96156. ny *= tmp1X;
  96157. nz *= tmp1X;
  96158. var tx = ny * z2 - nz * y2;
  96159. var ty = nz * x2 - nx * z2;
  96160. var tz = nx * y2 - ny * x2;
  96161. tmp1X = OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  96162. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  96163. tx *= tmp1X;
  96164. ty *= tmp1X;
  96165. tz *= tmp1X;
  96166. var bx = y1 * nz - z1 * ny;
  96167. var by = z1 * nx - x1 * nz;
  96168. var bz = x1 * ny - y1 * nx;
  96169. tmp1X = OIMO.sqrt(bx * bx + by * by + bz * bz);
  96170. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  96171. bx *= tmp1X;
  96172. by *= tmp1X;
  96173. bz *= tmp1X;
  96174. this.nor.init(nx, ny, nz);
  96175. this.tan.init(tx, ty, tz);
  96176. this.bin.init(bx, by, bz);
  96177. this.r3.preSolve(timeStep, invTimeStep);
  96178. this.t3.preSolve(timeStep, invTimeStep);
  96179. };
  96180. OIMO.WheelJoint.prototype.solve = function () {
  96181. this.r3.solve();
  96182. this.t3.solve();
  96183. };
  96184. OIMO.WheelJoint.prototype.postSolve = function () {
  96185. };
  96186. OIMO.WheelJoint.prototype.acosClamp = function (cos) {
  96187. if (cos > 1) return 0;
  96188. else if (cos < -1) return OIMO.PI;
  96189. else return OIMO.acos(cos);
  96190. };
  96191. /**
  96192. * An angular constraint for all axes for various joints.
  96193. * @author saharan
  96194. */
  96195. OIMO.AngularConstraint = function (joint, targetOrientation) {
  96196. this.joint = joint;
  96197. this.targetOrientation = new OIMO.Quat().invert(targetOrientation);
  96198. this.relativeOrientation = new OIMO.Quat();
  96199. this.ii1 = null;
  96200. this.ii2 = null;
  96201. this.dd = null;
  96202. this.vel = new OIMO.Vec3();
  96203. this.imp = new OIMO.Vec3();
  96204. this.rn0 = new OIMO.Vec3();
  96205. this.rn1 = new OIMO.Vec3();
  96206. this.rn2 = new OIMO.Vec3();
  96207. this.b1 = joint.body1;
  96208. this.b2 = joint.body2;
  96209. this.a1 = this.b1.angularVelocity;
  96210. this.a2 = this.b2.angularVelocity;
  96211. this.i1 = this.b1.inverseInertia;
  96212. this.i2 = this.b2.inverseInertia;
  96213. };
  96214. OIMO.AngularConstraint.prototype = {
  96215. constructor: OIMO.AngularConstraint,
  96216. preSolve: function (timeStep, invTimeStep) {
  96217. var inv, len, v, vv;
  96218. this.ii1 = this.i1.clone();
  96219. this.ii2 = this.i2.clone();
  96220. v = new OIMO.Mat33().add(this.ii1, this.ii2).elements;
  96221. 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]));
  96222. this.dd = new OIMO.Mat33(
  96223. v[4] * v[8] - v[5] * v[7], v[2] * v[7] - v[1] * v[8], v[1] * v[5] - v[2] * v[4],
  96224. v[5] * v[6] - v[3] * v[8], v[0] * v[8] - v[2] * v[6], v[2] * v[3] - v[0] * v[5],
  96225. v[3] * v[7] - v[4] * v[6], v[1] * v[6] - v[0] * v[7], v[0] * v[4] - v[1] * v[3]
  96226. ).multiply(inv);
  96227. this.relativeOrientation.invert(this.b1.orientation);
  96228. this.relativeOrientation.mul(this.targetOrientation, this.relativeOrientation);
  96229. this.relativeOrientation.mul(this.b2.orientation, this.relativeOrientation);
  96230. inv = this.relativeOrientation.s * 2;
  96231. this.vel.scale(this.relativeOrientation, inv);
  96232. len = this.vel.length();
  96233. if (len > 0.02) {
  96234. len = (0.02 - len) / len * invTimeStep * 0.05;
  96235. this.vel.scaleEqual(len);
  96236. } else {
  96237. this.vel.init();
  96238. }
  96239. this.rn1.mulMat(this.ii1, this.imp);
  96240. this.rn2.mulMat(this.ii2, this.imp);
  96241. this.a1.addEqual(this.rn1);
  96242. this.a2.subEqual(this.rn2);
  96243. },
  96244. solve: function () {
  96245. var r = this.a2.clone().subEqual(this.a1).subEqual(this.vel);
  96246. this.rn0.mulMat(this.dd, r);
  96247. this.rn1.mulMat(this.ii1, this.rn0);
  96248. this.rn2.mulMat(this.ii2, this.rn0);
  96249. this.imp.addEqual(this.rn0);
  96250. this.a1.addEqual(this.rn1);
  96251. this.a2.subEqual(this.rn2);
  96252. }
  96253. };
  96254. /**
  96255. * A linear constraint for all axes for various joints.
  96256. * @author saharan
  96257. */
  96258. OIMO.LinearConstraint = function (joint) {
  96259. this.m1 = NaN;
  96260. this.m2 = NaN;
  96261. this.ii1 = null;
  96262. this.ii2 = null;
  96263. this.dd = null;
  96264. this.r1x = NaN;
  96265. this.r1y = NaN;
  96266. this.r1z = NaN;
  96267. this.r2x = NaN;
  96268. this.r2y = NaN;
  96269. this.r2z = NaN;
  96270. this.ax1x = NaN;
  96271. this.ax1y = NaN;
  96272. this.ax1z = NaN;
  96273. this.ay1x = NaN;
  96274. this.ay1y = NaN;
  96275. this.ay1z = NaN;
  96276. this.az1x = NaN;
  96277. this.az1y = NaN;
  96278. this.az1z = NaN;
  96279. this.ax2x = NaN;
  96280. this.ax2y = NaN;
  96281. this.ax2z = NaN;
  96282. this.ay2x = NaN;
  96283. this.ay2y = NaN;
  96284. this.ay2z = NaN;
  96285. this.az2x = NaN;
  96286. this.az2y = NaN;
  96287. this.az2z = NaN;
  96288. this.vel = NaN;
  96289. this.velx = NaN;
  96290. this.vely = NaN;
  96291. this.velz = NaN;
  96292. this.joint = joint;
  96293. this.r1 = joint.relativeAnchorPoint1;
  96294. this.r2 = joint.relativeAnchorPoint2;
  96295. this.p1 = joint.anchorPoint1;
  96296. this.p2 = joint.anchorPoint2;
  96297. this.b1 = joint.body1;
  96298. this.b2 = joint.body2;
  96299. this.l1 = this.b1.linearVelocity;
  96300. this.l2 = this.b2.linearVelocity;
  96301. this.a1 = this.b1.angularVelocity;
  96302. this.a2 = this.b2.angularVelocity;
  96303. this.i1 = this.b1.inverseInertia;
  96304. this.i2 = this.b2.inverseInertia;
  96305. this.impx = 0;
  96306. this.impy = 0;
  96307. this.impz = 0;
  96308. }
  96309. OIMO.LinearConstraint.prototype = {
  96310. constructor: OIMO.LinearConstraint,
  96311. preSolve: function (timeStep, invTimeStep) {
  96312. this.r1x = this.r1.x;
  96313. this.r1y = this.r1.y;
  96314. this.r1z = this.r1.z;
  96315. this.r2x = this.r2.x;
  96316. this.r2y = this.r2.y;
  96317. this.r2z = this.r2.z;
  96318. this.m1 = this.b1.inverseMass;
  96319. this.m2 = this.b2.inverseMass;
  96320. this.ii1 = this.i1.clone();
  96321. this.ii2 = this.i2.clone();
  96322. var ii1 = this.ii1.elements;
  96323. var ii2 = this.ii2.elements;
  96324. this.ax1x = this.r1z * ii1[1] + -this.r1y * ii1[2];
  96325. this.ax1y = this.r1z * ii1[4] + -this.r1y * ii1[5];
  96326. this.ax1z = this.r1z * ii1[7] + -this.r1y * ii1[8];
  96327. this.ay1x = -this.r1z * ii1[0] + this.r1x * ii1[2];
  96328. this.ay1y = -this.r1z * ii1[3] + this.r1x * ii1[5];
  96329. this.ay1z = -this.r1z * ii1[6] + this.r1x * ii1[8];
  96330. this.az1x = this.r1y * ii1[0] + -this.r1x * ii1[1];
  96331. this.az1y = this.r1y * ii1[3] + -this.r1x * ii1[4];
  96332. this.az1z = this.r1y * ii1[6] + -this.r1x * ii1[7];
  96333. this.ax2x = this.r2z * ii2[1] + -this.r2y * ii2[2];
  96334. this.ax2y = this.r2z * ii2[4] + -this.r2y * ii2[5];
  96335. this.ax2z = this.r2z * ii2[7] + -this.r2y * ii2[8];
  96336. this.ay2x = -this.r2z * ii2[0] + this.r2x * ii2[2];
  96337. this.ay2y = -this.r2z * ii2[3] + this.r2x * ii2[5];
  96338. this.ay2z = -this.r2z * ii2[6] + this.r2x * ii2[8];
  96339. this.az2x = this.r2y * ii2[0] + -this.r2x * ii2[1];
  96340. this.az2y = this.r2y * ii2[3] + -this.r2x * ii2[4];
  96341. this.az2z = this.r2y * ii2[6] + -this.r2x * ii2[7];
  96342. // calculate point-to-point mass matrix
  96343. // from impulse equation
  96344. //
  96345. // M = ([/m] - [r^][/I][r^]) ^ -1
  96346. //
  96347. // where
  96348. //
  96349. // [/m] = |1/m, 0, 0|
  96350. // |0, 1/m, 0|
  96351. // |0, 0, 1/m|
  96352. //
  96353. // [r^] = |0, -rz, ry|
  96354. // |rz, 0, -rx|
  96355. // |-ry, rx, 0|
  96356. //
  96357. // [/I] = Inverted moment inertia
  96358. var rxx = this.m1 + this.m2;
  96359. var kk = new OIMO.Mat33(rxx, 0, 0, 0, rxx, 0, 0, 0, rxx);
  96360. var k = kk.elements;
  96361. k[0] += ii1[4] * this.r1z * this.r1z - (ii1[7] + ii1[5]) * this.r1y * this.r1z + ii1[8] * this.r1y * this.r1y;
  96362. k[1] += (ii1[6] * this.r1y + ii1[5] * this.r1x) * this.r1z - ii1[3] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  96363. k[2] += (ii1[3] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[6] * this.r1y * this.r1y + ii1[7] * this.r1x * this.r1y;
  96364. k[3] += (ii1[2] * this.r1y + ii1[7] * this.r1x) * this.r1z - ii1[1] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  96365. k[4] += ii1[0] * this.r1z * this.r1z - (ii1[6] + ii1[2]) * this.r1x * this.r1z + ii1[8] * this.r1x * this.r1x;
  96366. k[5] += (ii1[1] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[7] * this.r1x * this.r1x + ii1[6] * this.r1x * this.r1y;
  96367. k[6] += (ii1[1] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[2] * this.r1y * this.r1y + ii1[5] * this.r1x * this.r1y;
  96368. k[7] += (ii1[3] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[5] * this.r1x * this.r1x + ii1[2] * this.r1x * this.r1y;
  96369. k[8] += ii1[0] * this.r1y * this.r1y - (ii1[3] + ii1[1]) * this.r1x * this.r1y + ii1[4] * this.r1x * this.r1x;
  96370. k[0] += ii2[4] * this.r2z * this.r2z - (ii2[7] + ii2[5]) * this.r2y * this.r2z + ii2[8] * this.r2y * this.r2y;
  96371. k[1] += (ii2[6] * this.r2y + ii2[5] * this.r2x) * this.r2z - ii2[3] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  96372. k[2] += (ii2[3] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[6] * this.r2y * this.r2y + ii2[7] * this.r2x * this.r2y;
  96373. k[3] += (ii2[2] * this.r2y + ii2[7] * this.r2x) * this.r2z - ii2[1] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  96374. k[4] += ii2[0] * this.r2z * this.r2z - (ii2[6] + ii2[2]) * this.r2x * this.r2z + ii2[8] * this.r2x * this.r2x;
  96375. k[5] += (ii2[1] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[7] * this.r2x * this.r2x + ii2[6] * this.r2x * this.r2y;
  96376. k[6] += (ii2[1] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[2] * this.r2y * this.r2y + ii2[5] * this.r2x * this.r2y;
  96377. k[7] += (ii2[3] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[5] * this.r2x * this.r2x + ii2[2] * this.r2x * this.r2y;
  96378. k[8] += ii2[0] * this.r2y * this.r2y - (ii2[3] + ii2[1]) * this.r2x * this.r2y + ii2[4] * this.r2x * this.r2x;
  96379. 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]));
  96380. this.dd = new OIMO.Mat33(
  96381. k[4] * k[8] - k[5] * k[7], k[2] * k[7] - k[1] * k[8], k[1] * k[5] - k[2] * k[4],
  96382. k[5] * k[6] - k[3] * k[8], k[0] * k[8] - k[2] * k[6], k[2] * k[3] - k[0] * k[5],
  96383. k[3] * k[7] - k[4] * k[6], k[1] * k[6] - k[0] * k[7], k[0] * k[4] - k[1] * k[3]
  96384. ).multiply(inv);
  96385. this.velx = this.p2.x - this.p1.x;
  96386. this.vely = this.p2.y - this.p1.y;
  96387. this.velz = this.p2.z - this.p1.z;
  96388. var len = OIMO.sqrt(this.velx * this.velx + this.vely * this.vely + this.velz * this.velz);
  96389. if (len > 0.005) {
  96390. len = (0.005 - len) / len * invTimeStep * 0.05;
  96391. this.velx *= len;
  96392. this.vely *= len;
  96393. this.velz *= len;
  96394. } else {
  96395. this.velx = 0;
  96396. this.vely = 0;
  96397. this.velz = 0;
  96398. }
  96399. this.impx *= 0.95;
  96400. this.impy *= 0.95;
  96401. this.impz *= 0.95;
  96402. this.l1.x += this.impx * this.m1;
  96403. this.l1.y += this.impy * this.m1;
  96404. this.l1.z += this.impz * this.m1;
  96405. this.a1.x += this.impx * this.ax1x + this.impy * this.ay1x + this.impz * this.az1x;
  96406. this.a1.y += this.impx * this.ax1y + this.impy * this.ay1y + this.impz * this.az1y;
  96407. this.a1.z += this.impx * this.ax1z + this.impy * this.ay1z + this.impz * this.az1z;
  96408. this.l2.x -= this.impx * this.m2;
  96409. this.l2.y -= this.impy * this.m2;
  96410. this.l2.z -= this.impz * this.m2;
  96411. this.a2.x -= this.impx * this.ax2x + this.impy * this.ay2x + this.impz * this.az2x;
  96412. this.a2.y -= this.impx * this.ax2y + this.impy * this.ay2y + this.impz * this.az2y;
  96413. this.a2.z -= this.impx * this.ax2z + this.impy * this.ay2z + this.impz * this.az2z;
  96414. },
  96415. solve: function () {
  96416. var d = this.dd.elements;
  96417. 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;
  96418. 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;
  96419. 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;
  96420. var nimpx = rvx * d[0] + rvy * d[1] + rvz * d[2];
  96421. var nimpy = rvx * d[3] + rvy * d[4] + rvz * d[5];
  96422. var nimpz = rvx * d[6] + rvy * d[7] + rvz * d[8];
  96423. this.impx += nimpx;
  96424. this.impy += nimpy;
  96425. this.impz += nimpz;
  96426. this.l1.x += nimpx * this.m1;
  96427. this.l1.y += nimpy * this.m1;
  96428. this.l1.z += nimpz * this.m1;
  96429. this.a1.x += nimpx * this.ax1x + nimpy * this.ay1x + nimpz * this.az1x;
  96430. this.a1.y += nimpx * this.ax1y + nimpy * this.ay1y + nimpz * this.az1y;
  96431. this.a1.z += nimpx * this.ax1z + nimpy * this.ay1z + nimpz * this.az1z;
  96432. this.l2.x -= nimpx * this.m2;
  96433. this.l2.y -= nimpy * this.m2;
  96434. this.l2.z -= nimpz * this.m2;
  96435. this.a2.x -= nimpx * this.ax2x + nimpy * this.ay2x + nimpz * this.az2x;
  96436. this.a2.y -= nimpx * this.ax2y + nimpy * this.ay2y + nimpz * this.az2y;
  96437. this.a2.z -= nimpx * this.ax2z + nimpy * this.ay2z + nimpz * this.az2z;
  96438. }
  96439. }
  96440. /**
  96441. * A three-axis rotational constraint for various joints.
  96442. * @author saharan
  96443. */
  96444. OIMO.Rotational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  96445. this.cfm1 = NaN;
  96446. this.cfm2 = NaN;
  96447. this.cfm3 = NaN;
  96448. this.i1e00 = NaN;
  96449. this.i1e01 = NaN;
  96450. this.i1e02 = NaN;
  96451. this.i1e10 = NaN;
  96452. this.i1e11 = NaN;
  96453. this.i1e12 = NaN;
  96454. this.i1e20 = NaN;
  96455. this.i1e21 = NaN;
  96456. this.i1e22 = NaN;
  96457. this.i2e00 = NaN;
  96458. this.i2e01 = NaN;
  96459. this.i2e02 = NaN;
  96460. this.i2e10 = NaN;
  96461. this.i2e11 = NaN;
  96462. this.i2e12 = NaN;
  96463. this.i2e20 = NaN;
  96464. this.i2e21 = NaN;
  96465. this.i2e22 = NaN;
  96466. this.ax1 = NaN;
  96467. this.ay1 = NaN;
  96468. this.az1 = NaN;
  96469. this.ax2 = NaN;
  96470. this.ay2 = NaN;
  96471. this.az2 = NaN;
  96472. this.ax3 = NaN;
  96473. this.ay3 = NaN;
  96474. this.az3 = NaN;
  96475. this.a1x1 = NaN; // jacoians
  96476. this.a1y1 = NaN;
  96477. this.a1z1 = NaN;
  96478. this.a2x1 = NaN;
  96479. this.a2y1 = NaN;
  96480. this.a2z1 = NaN;
  96481. this.a1x2 = NaN;
  96482. this.a1y2 = NaN;
  96483. this.a1z2 = NaN;
  96484. this.a2x2 = NaN;
  96485. this.a2y2 = NaN;
  96486. this.a2z2 = NaN;
  96487. this.a1x3 = NaN;
  96488. this.a1y3 = NaN;
  96489. this.a1z3 = NaN;
  96490. this.a2x3 = NaN;
  96491. this.a2y3 = NaN;
  96492. this.a2z3 = NaN;
  96493. this.lowerLimit1 = NaN;
  96494. this.upperLimit1 = NaN;
  96495. this.limitVelocity1 = NaN;
  96496. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  96497. this.enableMotor1 = false;
  96498. this.motorSpeed1 = NaN;
  96499. this.maxMotorForce1 = NaN;
  96500. this.maxMotorImpulse1 = NaN;
  96501. this.lowerLimit2 = NaN;
  96502. this.upperLimit2 = NaN;
  96503. this.limitVelocity2 = NaN;
  96504. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  96505. this.enableMotor2 = false;
  96506. this.motorSpeed2 = NaN;
  96507. this.maxMotorForce2 = NaN;
  96508. this.maxMotorImpulse2 = NaN;
  96509. this.lowerLimit3 = NaN;
  96510. this.upperLimit3 = NaN;
  96511. this.limitVelocity3 = NaN;
  96512. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  96513. this.enableMotor3 = false;
  96514. this.motorSpeed3 = NaN;
  96515. this.maxMotorForce3 = NaN;
  96516. this.maxMotorImpulse3 = NaN;
  96517. this.k00 = NaN; // K = J*M*JT
  96518. this.k01 = NaN;
  96519. this.k02 = NaN;
  96520. this.k10 = NaN;
  96521. this.k11 = NaN;
  96522. this.k12 = NaN;
  96523. this.k20 = NaN;
  96524. this.k21 = NaN;
  96525. this.k22 = NaN;
  96526. this.kv00 = NaN; // diagonals without CFMs
  96527. this.kv11 = NaN;
  96528. this.kv22 = NaN;
  96529. this.dv00 = NaN; // ...inverted
  96530. this.dv11 = NaN;
  96531. this.dv22 = NaN;
  96532. this.d00 = NaN; // K^-1
  96533. this.d01 = NaN;
  96534. this.d02 = NaN;
  96535. this.d10 = NaN;
  96536. this.d11 = NaN;
  96537. this.d12 = NaN;
  96538. this.d20 = NaN;
  96539. this.d21 = NaN;
  96540. this.d22 = NaN;
  96541. this.limitMotor1 = limitMotor1;
  96542. this.limitMotor2 = limitMotor2;
  96543. this.limitMotor3 = limitMotor3;
  96544. this.b1 = joint.body1;
  96545. this.b2 = joint.body2;
  96546. this.a1 = this.b1.angularVelocity;
  96547. this.a2 = this.b2.angularVelocity;
  96548. this.i1 = this.b1.inverseInertia;
  96549. this.i2 = this.b2.inverseInertia;
  96550. this.limitImpulse1 = 0;
  96551. this.motorImpulse1 = 0;
  96552. this.limitImpulse2 = 0;
  96553. this.motorImpulse2 = 0;
  96554. this.limitImpulse3 = 0;
  96555. this.motorImpulse3 = 0;
  96556. }
  96557. OIMO.Rotational3Constraint.prototype = {
  96558. constructor: OIMO.Rotational3Constraint,
  96559. preSolve: function (timeStep, invTimeStep) {
  96560. this.ax1 = this.limitMotor1.axis.x;
  96561. this.ay1 = this.limitMotor1.axis.y;
  96562. this.az1 = this.limitMotor1.axis.z;
  96563. this.ax2 = this.limitMotor2.axis.x;
  96564. this.ay2 = this.limitMotor2.axis.y;
  96565. this.az2 = this.limitMotor2.axis.z;
  96566. this.ax3 = this.limitMotor3.axis.x;
  96567. this.ay3 = this.limitMotor3.axis.y;
  96568. this.az3 = this.limitMotor3.axis.z;
  96569. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  96570. this.upperLimit1 = this.limitMotor1.upperLimit;
  96571. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  96572. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  96573. this.enableMotor1 = this.maxMotorForce1 > 0;
  96574. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  96575. this.upperLimit2 = this.limitMotor2.upperLimit;
  96576. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  96577. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  96578. this.enableMotor2 = this.maxMotorForce2 > 0;
  96579. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  96580. this.upperLimit3 = this.limitMotor3.upperLimit;
  96581. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  96582. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  96583. this.enableMotor3 = this.maxMotorForce3 > 0;
  96584. var ti1 = this.i1.elements;
  96585. var ti2 = this.i2.elements;
  96586. this.i1e00 = ti1[0];
  96587. this.i1e01 = ti1[1];
  96588. this.i1e02 = ti1[2];
  96589. this.i1e10 = ti1[3];
  96590. this.i1e11 = ti1[4];
  96591. this.i1e12 = ti1[5];
  96592. this.i1e20 = ti1[6];
  96593. this.i1e21 = ti1[7];
  96594. this.i1e22 = ti1[8];
  96595. this.i2e00 = ti2[0];
  96596. this.i2e01 = ti2[1];
  96597. this.i2e02 = ti2[2];
  96598. this.i2e10 = ti2[3];
  96599. this.i2e11 = ti2[4];
  96600. this.i2e12 = ti2[5];
  96601. this.i2e20 = ti2[6];
  96602. this.i2e21 = ti2[7];
  96603. this.i2e22 = ti2[8];
  96604. var frequency1 = this.limitMotor1.frequency;
  96605. var frequency2 = this.limitMotor2.frequency;
  96606. var frequency3 = this.limitMotor3.frequency;
  96607. var enableSpring1 = frequency1 > 0;
  96608. var enableSpring2 = frequency2 > 0;
  96609. var enableSpring3 = frequency3 > 0;
  96610. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  96611. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  96612. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  96613. var angle1 = this.limitMotor1.angle;
  96614. if (enableLimit1) {
  96615. if (this.lowerLimit1 == this.upperLimit1) {
  96616. if (this.limitState1 != 0) {
  96617. this.limitState1 = 0;
  96618. this.limitImpulse1 = 0;
  96619. }
  96620. this.limitVelocity1 = this.lowerLimit1 - angle1;
  96621. } else if (angle1 < this.lowerLimit1) {
  96622. if (this.limitState1 != -1) {
  96623. this.limitState1 = -1;
  96624. this.limitImpulse1 = 0;
  96625. }
  96626. this.limitVelocity1 = this.lowerLimit1 - angle1;
  96627. } else if (angle1 > this.upperLimit1) {
  96628. if (this.limitState1 != 1) {
  96629. this.limitState1 = 1;
  96630. this.limitImpulse1 = 0;
  96631. }
  96632. this.limitVelocity1 = this.upperLimit1 - angle1;
  96633. } else {
  96634. this.limitState1 = 2;
  96635. this.limitImpulse1 = 0;
  96636. this.limitVelocity1 = 0;
  96637. }
  96638. if (!enableSpring1) {
  96639. if (this.limitVelocity1 > 0.02) this.limitVelocity1 -= 0.02;
  96640. else if (this.limitVelocity1 < -0.02) this.limitVelocity1 += 0.02;
  96641. else this.limitVelocity1 = 0;
  96642. }
  96643. } else {
  96644. this.limitState1 = 2;
  96645. this.limitImpulse1 = 0;
  96646. }
  96647. var angle2 = this.limitMotor2.angle;
  96648. if (enableLimit2) {
  96649. if (this.lowerLimit2 == this.upperLimit2) {
  96650. if (this.limitState2 != 0) {
  96651. this.limitState2 = 0;
  96652. this.limitImpulse2 = 0;
  96653. }
  96654. this.limitVelocity2 = this.lowerLimit2 - angle2;
  96655. } else if (angle2 < this.lowerLimit2) {
  96656. if (this.limitState2 != -1) {
  96657. this.limitState2 = -1;
  96658. this.limitImpulse2 = 0;
  96659. }
  96660. this.limitVelocity2 = this.lowerLimit2 - angle2;
  96661. } else if (angle2 > this.upperLimit2) {
  96662. if (this.limitState2 != 1) {
  96663. this.limitState2 = 1;
  96664. this.limitImpulse2 = 0;
  96665. }
  96666. this.limitVelocity2 = this.upperLimit2 - angle2;
  96667. } else {
  96668. this.limitState2 = 2;
  96669. this.limitImpulse2 = 0;
  96670. this.limitVelocity2 = 0;
  96671. }
  96672. if (!enableSpring2) {
  96673. if (this.limitVelocity2 > 0.02) this.limitVelocity2 -= 0.02;
  96674. else if (this.limitVelocity2 < -0.02) this.limitVelocity2 += 0.02;
  96675. else this.limitVelocity2 = 0;
  96676. }
  96677. } else {
  96678. this.limitState2 = 2;
  96679. this.limitImpulse2 = 0;
  96680. }
  96681. var angle3 = this.limitMotor3.angle;
  96682. if (enableLimit3) {
  96683. if (this.lowerLimit3 == this.upperLimit3) {
  96684. if (this.limitState3 != 0) {
  96685. this.limitState3 = 0;
  96686. this.limitImpulse3 = 0;
  96687. }
  96688. this.limitVelocity3 = this.lowerLimit3 - angle3;
  96689. } else if (angle3 < this.lowerLimit3) {
  96690. if (this.limitState3 != -1) {
  96691. this.limitState3 = -1;
  96692. this.limitImpulse3 = 0;
  96693. }
  96694. this.limitVelocity3 = this.lowerLimit3 - angle3;
  96695. } else if (angle3 > this.upperLimit3) {
  96696. if (this.limitState3 != 1) {
  96697. this.limitState3 = 1;
  96698. this.limitImpulse3 = 0;
  96699. }
  96700. this.limitVelocity3 = this.upperLimit3 - angle3;
  96701. } else {
  96702. this.limitState3 = 2;
  96703. this.limitImpulse3 = 0;
  96704. this.limitVelocity3 = 0;
  96705. }
  96706. if (!enableSpring3) {
  96707. if (this.limitVelocity3 > 0.02) this.limitVelocity3 -= 0.02;
  96708. else if (this.limitVelocity3 < -0.02) this.limitVelocity3 += 0.02;
  96709. else this.limitVelocity3 = 0;
  96710. }
  96711. } else {
  96712. this.limitState3 = 2;
  96713. this.limitImpulse3 = 0;
  96714. }
  96715. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  96716. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  96717. } else {
  96718. this.motorImpulse1 = 0;
  96719. this.maxMotorImpulse1 = 0;
  96720. }
  96721. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  96722. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  96723. } else {
  96724. this.motorImpulse2 = 0;
  96725. this.maxMotorImpulse2 = 0;
  96726. }
  96727. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  96728. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  96729. } else {
  96730. this.motorImpulse3 = 0;
  96731. this.maxMotorImpulse3 = 0;
  96732. }
  96733. // build jacobians
  96734. this.a1x1 = this.ax1 * this.i1e00 + this.ay1 * this.i1e01 + this.az1 * this.i1e02;
  96735. this.a1y1 = this.ax1 * this.i1e10 + this.ay1 * this.i1e11 + this.az1 * this.i1e12;
  96736. this.a1z1 = this.ax1 * this.i1e20 + this.ay1 * this.i1e21 + this.az1 * this.i1e22;
  96737. this.a2x1 = this.ax1 * this.i2e00 + this.ay1 * this.i2e01 + this.az1 * this.i2e02;
  96738. this.a2y1 = this.ax1 * this.i2e10 + this.ay1 * this.i2e11 + this.az1 * this.i2e12;
  96739. this.a2z1 = this.ax1 * this.i2e20 + this.ay1 * this.i2e21 + this.az1 * this.i2e22;
  96740. this.a1x2 = this.ax2 * this.i1e00 + this.ay2 * this.i1e01 + this.az2 * this.i1e02;
  96741. this.a1y2 = this.ax2 * this.i1e10 + this.ay2 * this.i1e11 + this.az2 * this.i1e12;
  96742. this.a1z2 = this.ax2 * this.i1e20 + this.ay2 * this.i1e21 + this.az2 * this.i1e22;
  96743. this.a2x2 = this.ax2 * this.i2e00 + this.ay2 * this.i2e01 + this.az2 * this.i2e02;
  96744. this.a2y2 = this.ax2 * this.i2e10 + this.ay2 * this.i2e11 + this.az2 * this.i2e12;
  96745. this.a2z2 = this.ax2 * this.i2e20 + this.ay2 * this.i2e21 + this.az2 * this.i2e22;
  96746. this.a1x3 = this.ax3 * this.i1e00 + this.ay3 * this.i1e01 + this.az3 * this.i1e02;
  96747. this.a1y3 = this.ax3 * this.i1e10 + this.ay3 * this.i1e11 + this.az3 * this.i1e12;
  96748. this.a1z3 = this.ax3 * this.i1e20 + this.ay3 * this.i1e21 + this.az3 * this.i1e22;
  96749. this.a2x3 = this.ax3 * this.i2e00 + this.ay3 * this.i2e01 + this.az3 * this.i2e02;
  96750. this.a2y3 = this.ax3 * this.i2e10 + this.ay3 * this.i2e11 + this.az3 * this.i2e12;
  96751. this.a2z3 = this.ax3 * this.i2e20 + this.ay3 * this.i2e21 + this.az3 * this.i2e22;
  96752. // build an impulse matrix
  96753. this.k00 = this.ax1 * (this.a1x1 + this.a2x1) + this.ay1 * (this.a1y1 + this.a2y1) + this.az1 * (this.a1z1 + this.a2z1);
  96754. this.k01 = this.ax1 * (this.a1x2 + this.a2x2) + this.ay1 * (this.a1y2 + this.a2y2) + this.az1 * (this.a1z2 + this.a2z2);
  96755. this.k02 = this.ax1 * (this.a1x3 + this.a2x3) + this.ay1 * (this.a1y3 + this.a2y3) + this.az1 * (this.a1z3 + this.a2z3);
  96756. this.k10 = this.ax2 * (this.a1x1 + this.a2x1) + this.ay2 * (this.a1y1 + this.a2y1) + this.az2 * (this.a1z1 + this.a2z1);
  96757. this.k11 = this.ax2 * (this.a1x2 + this.a2x2) + this.ay2 * (this.a1y2 + this.a2y2) + this.az2 * (this.a1z2 + this.a2z2);
  96758. this.k12 = this.ax2 * (this.a1x3 + this.a2x3) + this.ay2 * (this.a1y3 + this.a2y3) + this.az2 * (this.a1z3 + this.a2z3);
  96759. this.k20 = this.ax3 * (this.a1x1 + this.a2x1) + this.ay3 * (this.a1y1 + this.a2y1) + this.az3 * (this.a1z1 + this.a2z1);
  96760. this.k21 = this.ax3 * (this.a1x2 + this.a2x2) + this.ay3 * (this.a1y2 + this.a2y2) + this.az3 * (this.a1z2 + this.a2z2);
  96761. this.k22 = this.ax3 * (this.a1x3 + this.a2x3) + this.ay3 * (this.a1y3 + this.a2y3) + this.az3 * (this.a1z3 + this.a2z3);
  96762. this.kv00 = this.k00;
  96763. this.kv11 = this.k11;
  96764. this.kv22 = this.k22;
  96765. this.dv00 = 1 / this.kv00;
  96766. this.dv11 = 1 / this.kv11;
  96767. this.dv22 = 1 / this.kv22;
  96768. if (enableSpring1 && this.limitState1 != 2) {
  96769. var omega = 6.2831853 * frequency1;
  96770. var k = omega * omega * timeStep;
  96771. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  96772. this.cfm1 = this.kv00 * dmp;
  96773. this.limitVelocity1 *= k * dmp;
  96774. } else {
  96775. this.cfm1 = 0;
  96776. this.limitVelocity1 *= invTimeStep * 0.05;
  96777. }
  96778. if (enableSpring2 && this.limitState2 != 2) {
  96779. omega = 6.2831853 * frequency2;
  96780. k = omega * omega * timeStep;
  96781. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  96782. this.cfm2 = this.kv11 * dmp;
  96783. this.limitVelocity2 *= k * dmp;
  96784. } else {
  96785. this.cfm2 = 0;
  96786. this.limitVelocity2 *= invTimeStep * 0.05;
  96787. }
  96788. if (enableSpring3 && this.limitState3 != 2) {
  96789. omega = 6.2831853 * frequency3;
  96790. k = omega * omega * timeStep;
  96791. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  96792. this.cfm3 = this.kv22 * dmp;
  96793. this.limitVelocity3 *= k * dmp;
  96794. } else {
  96795. this.cfm3 = 0;
  96796. this.limitVelocity3 *= invTimeStep * 0.05;
  96797. }
  96798. this.k00 += this.cfm1;
  96799. this.k11 += this.cfm2;
  96800. this.k22 += this.cfm3;
  96801. var inv = 1 / (
  96802. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  96803. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  96804. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  96805. );
  96806. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  96807. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  96808. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  96809. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  96810. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  96811. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  96812. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  96813. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  96814. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  96815. this.limitImpulse1 *= 0.95;
  96816. this.motorImpulse1 *= 0.95;
  96817. this.limitImpulse2 *= 0.95;
  96818. this.motorImpulse2 *= 0.95;
  96819. this.limitImpulse3 *= 0.95;
  96820. this.motorImpulse3 *= 0.95;
  96821. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  96822. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  96823. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  96824. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  96825. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  96826. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  96827. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  96828. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  96829. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  96830. },
  96831. solve_: function () {
  96832. var rvx = this.a2.x - this.a1.x;
  96833. var rvy = this.a2.y - this.a1.y;
  96834. var rvz = this.a2.z - this.a1.z;
  96835. this.limitVelocity3 = 30;
  96836. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1 - this.limitVelocity1;
  96837. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2 - this.limitVelocity2;
  96838. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3 - this.limitVelocity3;
  96839. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  96840. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  96841. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  96842. this.limitImpulse1 += dLimitImpulse1;
  96843. this.limitImpulse2 += dLimitImpulse2;
  96844. this.limitImpulse3 += dLimitImpulse3;
  96845. this.a1.x += dLimitImpulse1 * this.a1x1 + dLimitImpulse2 * this.a1x2 + dLimitImpulse3 * this.a1x3;
  96846. this.a1.y += dLimitImpulse1 * this.a1y1 + dLimitImpulse2 * this.a1y2 + dLimitImpulse3 * this.a1y3;
  96847. this.a1.z += dLimitImpulse1 * this.a1z1 + dLimitImpulse2 * this.a1z2 + dLimitImpulse3 * this.a1z3;
  96848. this.a2.x -= dLimitImpulse1 * this.a2x1 + dLimitImpulse2 * this.a2x2 + dLimitImpulse3 * this.a2x3;
  96849. this.a2.y -= dLimitImpulse1 * this.a2y1 + dLimitImpulse2 * this.a2y2 + dLimitImpulse3 * this.a2y3;
  96850. this.a2.z -= dLimitImpulse1 * this.a2z1 + dLimitImpulse2 * this.a2z2 + dLimitImpulse3 * this.a2z3;
  96851. },
  96852. solve: function () {
  96853. var rvx = this.a2.x - this.a1.x;
  96854. var rvy = this.a2.y - this.a1.y;
  96855. var rvz = this.a2.z - this.a1.z;
  96856. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  96857. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  96858. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  96859. var oldMotorImpulse1 = this.motorImpulse1;
  96860. var oldMotorImpulse2 = this.motorImpulse2;
  96861. var oldMotorImpulse3 = this.motorImpulse3;
  96862. var dMotorImpulse1 = 0;
  96863. var dMotorImpulse2 = 0;
  96864. var dMotorImpulse3 = 0;
  96865. if (this.enableMotor1) {
  96866. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  96867. this.motorImpulse1 += dMotorImpulse1;
  96868. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  96869. this.motorImpulse1 = this.maxMotorImpulse1;
  96870. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  96871. this.motorImpulse1 = -this.maxMotorImpulse1;
  96872. }
  96873. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  96874. }
  96875. if (this.enableMotor2) {
  96876. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  96877. this.motorImpulse2 += dMotorImpulse2;
  96878. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  96879. this.motorImpulse2 = this.maxMotorImpulse2;
  96880. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  96881. this.motorImpulse2 = -this.maxMotorImpulse2;
  96882. }
  96883. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  96884. }
  96885. if (this.enableMotor3) {
  96886. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  96887. this.motorImpulse3 += dMotorImpulse3;
  96888. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  96889. this.motorImpulse3 = this.maxMotorImpulse3;
  96890. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  96891. this.motorImpulse3 = -this.maxMotorImpulse3;
  96892. }
  96893. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  96894. }
  96895. // apply motor impulse to relative velocity
  96896. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  96897. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  96898. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  96899. // subtract target velocity and applied impulse
  96900. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  96901. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  96902. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  96903. var oldLimitImpulse1 = this.limitImpulse1;
  96904. var oldLimitImpulse2 = this.limitImpulse2;
  96905. var oldLimitImpulse3 = this.limitImpulse3;
  96906. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  96907. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  96908. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  96909. this.limitImpulse1 += dLimitImpulse1;
  96910. this.limitImpulse2 += dLimitImpulse2;
  96911. this.limitImpulse3 += dLimitImpulse3;
  96912. // clamp
  96913. var clampState = 0;
  96914. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  96915. dLimitImpulse1 = -oldLimitImpulse1;
  96916. rvn2 += dLimitImpulse1 * this.k10;
  96917. rvn3 += dLimitImpulse1 * this.k20;
  96918. clampState |= 1;
  96919. }
  96920. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  96921. dLimitImpulse2 = -oldLimitImpulse2;
  96922. rvn1 += dLimitImpulse2 * this.k01;
  96923. rvn3 += dLimitImpulse2 * this.k21;
  96924. clampState |= 2;
  96925. }
  96926. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  96927. dLimitImpulse3 = -oldLimitImpulse3;
  96928. rvn1 += dLimitImpulse3 * this.k02;
  96929. rvn2 += dLimitImpulse3 * this.k12;
  96930. clampState |= 4;
  96931. }
  96932. // update un-clamped impulse
  96933. // TODO: isolate division
  96934. var det;
  96935. switch (clampState) {
  96936. case 1: // update 2 3
  96937. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  96938. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  96939. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  96940. break;
  96941. case 2: // update 1 3
  96942. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  96943. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  96944. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  96945. break;
  96946. case 3: // update 3
  96947. dLimitImpulse3 = rvn3 / this.k22;
  96948. break;
  96949. case 4: // update 1 2
  96950. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  96951. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  96952. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  96953. break;
  96954. case 5: // update 2
  96955. dLimitImpulse2 = rvn2 / this.k11;
  96956. break;
  96957. case 6: // update 1
  96958. dLimitImpulse1 = rvn1 / this.k00;
  96959. break;
  96960. }
  96961. this.limitImpulse1 = dLimitImpulse1 + oldLimitImpulse1;
  96962. this.limitImpulse2 = dLimitImpulse2 + oldLimitImpulse2;
  96963. this.limitImpulse3 = dLimitImpulse3 + oldLimitImpulse3;
  96964. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  96965. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  96966. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  96967. // apply impulse
  96968. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  96969. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  96970. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  96971. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  96972. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  96973. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  96974. rvx = this.a2.x - this.a1.x;
  96975. rvy = this.a2.y - this.a1.y;
  96976. rvz = this.a2.z - this.a1.z;
  96977. rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  96978. }
  96979. }
  96980. /**
  96981. * A rotational constraint for various joints.
  96982. * @author saharan
  96983. */
  96984. OIMO.RotationalConstraint = function (joint, limitMotor) {
  96985. this.cfm = NaN;
  96986. this.i1e00 = NaN;
  96987. this.i1e01 = NaN;
  96988. this.i1e02 = NaN;
  96989. this.i1e10 = NaN;
  96990. this.i1e11 = NaN;
  96991. this.i1e12 = NaN;
  96992. this.i1e20 = NaN;
  96993. this.i1e21 = NaN;
  96994. this.i1e22 = NaN;
  96995. this.i2e00 = NaN;
  96996. this.i2e01 = NaN;
  96997. this.i2e02 = NaN;
  96998. this.i2e10 = NaN;
  96999. this.i2e11 = NaN;
  97000. this.i2e12 = NaN;
  97001. this.i2e20 = NaN;
  97002. this.i2e21 = NaN;
  97003. this.i2e22 = NaN;
  97004. this.motorDenom = NaN;
  97005. this.invMotorDenom = NaN;
  97006. this.invDenom = NaN;
  97007. this.ax = NaN;
  97008. this.ay = NaN;
  97009. this.az = NaN;
  97010. this.a1x = NaN;
  97011. this.a1y = NaN;
  97012. this.a1z = NaN;
  97013. this.a2x = NaN;
  97014. this.a2y = NaN;
  97015. this.a2z = NaN;
  97016. this.enableLimit = false;
  97017. this.lowerLimit = NaN;
  97018. this.upperLimit = NaN;
  97019. this.limitVelocity = NaN;
  97020. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  97021. this.enableMotor = false;
  97022. this.motorSpeed = NaN;
  97023. this.maxMotorForce = NaN;
  97024. this.maxMotorImpulse = NaN;
  97025. this.limitMotor = limitMotor;
  97026. this.b1 = joint.body1;
  97027. this.b2 = joint.body2;
  97028. this.a1 = this.b1.angularVelocity;
  97029. this.a2 = this.b2.angularVelocity;
  97030. this.i1 = this.b1.inverseInertia;
  97031. this.i2 = this.b2.inverseInertia;
  97032. this.limitImpulse = 0;
  97033. this.motorImpulse = 0;
  97034. }
  97035. OIMO.RotationalConstraint.prototype = {
  97036. constructor: OIMO.RotationalConstraint,
  97037. preSolve: function (timeStep, invTimeStep) {
  97038. this.ax = this.limitMotor.axis.x;
  97039. this.ay = this.limitMotor.axis.y;
  97040. this.az = this.limitMotor.axis.z;
  97041. this.lowerLimit = this.limitMotor.lowerLimit;
  97042. this.upperLimit = this.limitMotor.upperLimit;
  97043. this.motorSpeed = this.limitMotor.motorSpeed;
  97044. this.maxMotorForce = this.limitMotor.maxMotorForce;
  97045. this.enableMotor = this.maxMotorForce > 0;
  97046. var ti1 = this.i1.elements;
  97047. var ti2 = this.i2.elements;
  97048. this.i1e00 = ti1[0];
  97049. this.i1e01 = ti1[1];
  97050. this.i1e02 = ti1[2];
  97051. this.i1e10 = ti1[3];
  97052. this.i1e11 = ti1[4];
  97053. this.i1e12 = ti1[5];
  97054. this.i1e20 = ti1[6];
  97055. this.i1e21 = ti1[7];
  97056. this.i1e22 = ti1[8];
  97057. this.i2e00 = ti2[0];
  97058. this.i2e01 = ti2[1];
  97059. this.i2e02 = ti2[2];
  97060. this.i2e10 = ti2[3];
  97061. this.i2e11 = ti2[4];
  97062. this.i2e12 = ti2[5];
  97063. this.i2e20 = ti2[6];
  97064. this.i2e21 = ti2[7];
  97065. this.i2e22 = ti2[8];
  97066. var frequency = this.limitMotor.frequency;
  97067. var enableSpring = frequency > 0;
  97068. var enableLimit = this.lowerLimit <= this.upperLimit;
  97069. var angle = this.limitMotor.angle;
  97070. if (enableLimit) {
  97071. if (this.lowerLimit == this.upperLimit) {
  97072. if (this.limitState != 0) {
  97073. this.limitState = 0;
  97074. this.limitImpulse = 0;
  97075. }
  97076. this.limitVelocity = this.lowerLimit - angle;
  97077. } else if (angle < this.lowerLimit) {
  97078. if (this.limitState != -1) {
  97079. this.limitState = -1;
  97080. this.limitImpulse = 0;
  97081. }
  97082. this.limitVelocity = this.lowerLimit - angle;
  97083. } else if (angle > this.upperLimit) {
  97084. if (this.limitState != 1) {
  97085. this.limitState = 1;
  97086. this.limitImpulse = 0;
  97087. }
  97088. this.limitVelocity = this.upperLimit - angle;
  97089. } else {
  97090. this.limitState = 2;
  97091. this.limitImpulse = 0;
  97092. this.limitVelocity = 0;
  97093. }
  97094. if (!enableSpring) {
  97095. if (this.limitVelocity > 0.02) this.limitVelocity -= 0.02;
  97096. else if (this.limitVelocity < -0.02) this.limitVelocity += 0.02;
  97097. else this.limitVelocity = 0;
  97098. }
  97099. } else {
  97100. this.limitState = 2;
  97101. this.limitImpulse = 0;
  97102. }
  97103. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  97104. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  97105. } else {
  97106. this.motorImpulse = 0;
  97107. this.maxMotorImpulse = 0;
  97108. }
  97109. this.a1x = this.ax * this.i1e00 + this.ay * this.i1e01 + this.az * this.i1e02;
  97110. this.a1y = this.ax * this.i1e10 + this.ay * this.i1e11 + this.az * this.i1e12;
  97111. this.a1z = this.ax * this.i1e20 + this.ay * this.i1e21 + this.az * this.i1e22;
  97112. this.a2x = this.ax * this.i2e00 + this.ay * this.i2e01 + this.az * this.i2e02;
  97113. this.a2y = this.ax * this.i2e10 + this.ay * this.i2e11 + this.az * this.i2e12;
  97114. this.a2z = this.ax * this.i2e20 + this.ay * this.i2e21 + this.az * this.i2e22;
  97115. this.motorDenom = this.ax * (this.a1x + this.a2x) + this.ay * (this.a1y + this.a2y) + this.az * (this.a1z + this.a2z);
  97116. this.invMotorDenom = 1 / this.motorDenom;
  97117. if (enableSpring && this.limitState != 2) {
  97118. var omega = 6.2831853 * frequency;
  97119. var k = omega * omega * timeStep;
  97120. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  97121. this.cfm = this.motorDenom * dmp;
  97122. this.limitVelocity *= k * dmp;
  97123. } else {
  97124. this.cfm = 0;
  97125. this.limitVelocity *= invTimeStep * 0.05;
  97126. }
  97127. this.invDenom = 1 / (this.motorDenom + this.cfm);
  97128. this.limitImpulse *= 0.95;
  97129. this.motorImpulse *= 0.95;
  97130. var totalImpulse = this.limitImpulse + this.motorImpulse;
  97131. this.a1.x += totalImpulse * this.a1x;
  97132. this.a1.y += totalImpulse * this.a1y;
  97133. this.a1.z += totalImpulse * this.a1z;
  97134. this.a2.x -= totalImpulse * this.a2x;
  97135. this.a2.y -= totalImpulse * this.a2y;
  97136. this.a2.z -= totalImpulse * this.a2z;
  97137. },
  97138. solve: function () {
  97139. 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);
  97140. // motor part
  97141. var newMotorImpulse;
  97142. if (this.enableMotor) {
  97143. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  97144. var oldMotorImpulse = this.motorImpulse;
  97145. this.motorImpulse += newMotorImpulse;
  97146. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  97147. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  97148. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  97149. rvn -= newMotorImpulse * this.motorDenom;
  97150. } else newMotorImpulse = 0;
  97151. // limit part
  97152. var newLimitImpulse;
  97153. if (this.limitState != 2) {
  97154. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  97155. var oldLimitImpulse = this.limitImpulse;
  97156. this.limitImpulse += newLimitImpulse;
  97157. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  97158. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  97159. } else newLimitImpulse = 0;
  97160. var totalImpulse = newLimitImpulse + newMotorImpulse;
  97161. this.a1.x += totalImpulse * this.a1x;
  97162. this.a1.y += totalImpulse * this.a1y;
  97163. this.a1.z += totalImpulse * this.a1z;
  97164. this.a2.x -= totalImpulse * this.a2x;
  97165. this.a2.y -= totalImpulse * this.a2y;
  97166. this.a2.z -= totalImpulse * this.a2z;
  97167. }
  97168. }
  97169. /**
  97170. * A three-axis translational constraint for various joints.
  97171. * @author saharan
  97172. */
  97173. OIMO.Translational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  97174. this.m1 = NaN;
  97175. this.m2 = NaN;
  97176. this.i1e00 = NaN;
  97177. this.i1e01 = NaN;
  97178. this.i1e02 = NaN;
  97179. this.i1e10 = NaN;
  97180. this.i1e11 = NaN;
  97181. this.i1e12 = NaN;
  97182. this.i1e20 = NaN;
  97183. this.i1e21 = NaN;
  97184. this.i1e22 = NaN;
  97185. this.i2e00 = NaN;
  97186. this.i2e01 = NaN;
  97187. this.i2e02 = NaN;
  97188. this.i2e10 = NaN;
  97189. this.i2e11 = NaN;
  97190. this.i2e12 = NaN;
  97191. this.i2e20 = NaN;
  97192. this.i2e21 = NaN;
  97193. this.i2e22 = NaN;
  97194. this.ax1 = NaN;
  97195. this.ay1 = NaN;
  97196. this.az1 = NaN;
  97197. this.ax2 = NaN;
  97198. this.ay2 = NaN;
  97199. this.az2 = NaN;
  97200. this.ax3 = NaN;
  97201. this.ay3 = NaN;
  97202. this.az3 = NaN;
  97203. this.r1x = NaN;
  97204. this.r1y = NaN;
  97205. this.r1z = NaN;
  97206. this.r2x = NaN;
  97207. this.r2y = NaN;
  97208. this.r2z = NaN;
  97209. this.t1x1 = NaN;// jacobians
  97210. this.t1y1 = NaN;
  97211. this.t1z1 = NaN;
  97212. this.t2x1 = NaN;
  97213. this.t2y1 = NaN;
  97214. this.t2z1 = NaN;
  97215. this.l1x1 = NaN;
  97216. this.l1y1 = NaN;
  97217. this.l1z1 = NaN;
  97218. this.l2x1 = NaN;
  97219. this.l2y1 = NaN;
  97220. this.l2z1 = NaN;
  97221. this.a1x1 = NaN;
  97222. this.a1y1 = NaN;
  97223. this.a1z1 = NaN;
  97224. this.a2x1 = NaN;
  97225. this.a2y1 = NaN;
  97226. this.a2z1 = NaN;
  97227. this.t1x2 = NaN;
  97228. this.t1y2 = NaN;
  97229. this.t1z2 = NaN;
  97230. this.t2x2 = NaN;
  97231. this.t2y2 = NaN;
  97232. this.t2z2 = NaN;
  97233. this.l1x2 = NaN;
  97234. this.l1y2 = NaN;
  97235. this.l1z2 = NaN;
  97236. this.l2x2 = NaN;
  97237. this.l2y2 = NaN;
  97238. this.l2z2 = NaN;
  97239. this.a1x2 = NaN;
  97240. this.a1y2 = NaN;
  97241. this.a1z2 = NaN;
  97242. this.a2x2 = NaN;
  97243. this.a2y2 = NaN;
  97244. this.a2z2 = NaN;
  97245. this.t1x3 = NaN;
  97246. this.t1y3 = NaN;
  97247. this.t1z3 = NaN;
  97248. this.t2x3 = NaN;
  97249. this.t2y3 = NaN;
  97250. this.t2z3 = NaN;
  97251. this.l1x3 = NaN;
  97252. this.l1y3 = NaN;
  97253. this.l1z3 = NaN;
  97254. this.l2x3 = NaN;
  97255. this.l2y3 = NaN;
  97256. this.l2z3 = NaN;
  97257. this.a1x3 = NaN;
  97258. this.a1y3 = NaN;
  97259. this.a1z3 = NaN;
  97260. this.a2x3 = NaN;
  97261. this.a2y3 = NaN;
  97262. this.a2z3 = NaN;
  97263. this.lowerLimit1 = NaN;
  97264. this.upperLimit1 = NaN;
  97265. this.limitVelocity1 = NaN;
  97266. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  97267. this.enableMotor1 = false;
  97268. this.motorSpeed1 = NaN;
  97269. this.maxMotorForce1 = NaN;
  97270. this.maxMotorImpulse1 = NaN;
  97271. this.lowerLimit2 = NaN;
  97272. this.upperLimit2 = NaN;
  97273. this.limitVelocity2 = NaN;
  97274. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  97275. this.enableMotor2 = false;
  97276. this.motorSpeed2 = NaN;
  97277. this.maxMotorForce2 = NaN;
  97278. this.maxMotorImpulse2 = NaN;
  97279. this.lowerLimit3 = NaN;
  97280. this.upperLimit3 = NaN;
  97281. this.limitVelocity3 = NaN;
  97282. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  97283. this.enableMotor3 = false;
  97284. this.motorSpeed3 = NaN;
  97285. this.maxMotorForce3 = NaN;
  97286. this.maxMotorImpulse3 = NaN;
  97287. this.k00 = NaN; // K = J*M*JT
  97288. this.k01 = NaN;
  97289. this.k02 = NaN;
  97290. this.k10 = NaN;
  97291. this.k11 = NaN;
  97292. this.k12 = NaN;
  97293. this.k20 = NaN;
  97294. this.k21 = NaN;
  97295. this.k22 = NaN;
  97296. this.kv00 = NaN; // diagonals without CFMs
  97297. this.kv11 = NaN;
  97298. this.kv22 = NaN;
  97299. this.dv00 = NaN; // ...inverted
  97300. this.dv11 = NaN;
  97301. this.dv22 = NaN;
  97302. this.d00 = NaN; // K^-1
  97303. this.d01 = NaN;
  97304. this.d02 = NaN;
  97305. this.d10 = NaN;
  97306. this.d11 = NaN;
  97307. this.d12 = NaN;
  97308. this.d20 = NaN;
  97309. this.d21 = NaN;
  97310. this.d22 = NaN;
  97311. this.limitMotor1 = limitMotor1;
  97312. this.limitMotor2 = limitMotor2;
  97313. this.limitMotor3 = limitMotor3;
  97314. this.b1 = joint.body1;
  97315. this.b2 = joint.body2;
  97316. this.p1 = joint.anchorPoint1;
  97317. this.p2 = joint.anchorPoint2;
  97318. this.r1 = joint.relativeAnchorPoint1;
  97319. this.r2 = joint.relativeAnchorPoint2;
  97320. this.l1 = this.b1.linearVelocity;
  97321. this.l2 = this.b2.linearVelocity;
  97322. this.a1 = this.b1.angularVelocity;
  97323. this.a2 = this.b2.angularVelocity;
  97324. this.i1 = this.b1.inverseInertia;
  97325. this.i2 = this.b2.inverseInertia;
  97326. this.limitImpulse1 = 0;
  97327. this.motorImpulse1 = 0;
  97328. this.limitImpulse2 = 0;
  97329. this.motorImpulse2 = 0;
  97330. this.limitImpulse3 = 0;
  97331. this.motorImpulse3 = 0;
  97332. this.cfm1 = 0;// Constraint Force Mixing
  97333. this.cfm2 = 0;
  97334. this.cfm3 = 0;
  97335. this.weight = -1;
  97336. }
  97337. OIMO.Translational3Constraint.prototype = {
  97338. constructor: OIMO.Translational3Constraint,
  97339. preSolve: function (timeStep, invTimeStep) {
  97340. this.ax1 = this.limitMotor1.axis.x;
  97341. this.ay1 = this.limitMotor1.axis.y;
  97342. this.az1 = this.limitMotor1.axis.z;
  97343. this.ax2 = this.limitMotor2.axis.x;
  97344. this.ay2 = this.limitMotor2.axis.y;
  97345. this.az2 = this.limitMotor2.axis.z;
  97346. this.ax3 = this.limitMotor3.axis.x;
  97347. this.ay3 = this.limitMotor3.axis.y;
  97348. this.az3 = this.limitMotor3.axis.z;
  97349. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  97350. this.upperLimit1 = this.limitMotor1.upperLimit;
  97351. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  97352. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  97353. this.enableMotor1 = this.maxMotorForce1 > 0;
  97354. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  97355. this.upperLimit2 = this.limitMotor2.upperLimit;
  97356. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  97357. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  97358. this.enableMotor2 = this.maxMotorForce2 > 0;
  97359. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  97360. this.upperLimit3 = this.limitMotor3.upperLimit;
  97361. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  97362. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  97363. this.enableMotor3 = this.maxMotorForce3 > 0;
  97364. this.m1 = this.b1.inverseMass;
  97365. this.m2 = this.b2.inverseMass;
  97366. var ti1 = this.i1.elements;
  97367. var ti2 = this.i2.elements;
  97368. this.i1e00 = ti1[0];
  97369. this.i1e01 = ti1[1];
  97370. this.i1e02 = ti1[2];
  97371. this.i1e10 = ti1[3];
  97372. this.i1e11 = ti1[4];
  97373. this.i1e12 = ti1[5];
  97374. this.i1e20 = ti1[6];
  97375. this.i1e21 = ti1[7];
  97376. this.i1e22 = ti1[8];
  97377. this.i2e00 = ti2[0];
  97378. this.i2e01 = ti2[1];
  97379. this.i2e02 = ti2[2];
  97380. this.i2e10 = ti2[3];
  97381. this.i2e11 = ti2[4];
  97382. this.i2e12 = ti2[5];
  97383. this.i2e20 = ti2[6];
  97384. this.i2e21 = ti2[7];
  97385. this.i2e22 = ti2[8];
  97386. var dx = this.p2.x - this.p1.x;
  97387. var dy = this.p2.y - this.p1.y;
  97388. var dz = this.p2.z - this.p1.z;
  97389. var d1 = dx * this.ax1 + dy * this.ay1 + dz * this.az1;
  97390. var d2 = dx * this.ax2 + dy * this.ay2 + dz * this.az2;
  97391. var d3 = dx * this.ax3 + dy * this.ay3 + dz * this.az3;
  97392. var frequency1 = this.limitMotor1.frequency;
  97393. var frequency2 = this.limitMotor2.frequency;
  97394. var frequency3 = this.limitMotor3.frequency;
  97395. var enableSpring1 = frequency1 > 0;
  97396. var enableSpring2 = frequency2 > 0;
  97397. var enableSpring3 = frequency3 > 0;
  97398. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  97399. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  97400. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  97401. // for stability
  97402. if (enableSpring1 && d1 > 20 || d1 < -20) {
  97403. enableSpring1 = false;
  97404. }
  97405. if (enableSpring2 && d2 > 20 || d2 < -20) {
  97406. enableSpring2 = false;
  97407. }
  97408. if (enableSpring3 && d3 > 20 || d3 < -20) {
  97409. enableSpring3 = false;
  97410. }
  97411. if (enableLimit1) {
  97412. if (this.lowerLimit1 == this.upperLimit1) {
  97413. if (this.limitState1 != 0) {
  97414. this.limitState1 = 0;
  97415. this.limitImpulse1 = 0;
  97416. }
  97417. this.limitVelocity1 = this.lowerLimit1 - d1;
  97418. if (!enableSpring1) d1 = this.lowerLimit1;
  97419. } else if (d1 < this.lowerLimit1) {
  97420. if (this.limitState1 != -1) {
  97421. this.limitState1 = -1;
  97422. this.limitImpulse1 = 0;
  97423. }
  97424. this.limitVelocity1 = this.lowerLimit1 - d1;
  97425. if (!enableSpring1) d1 = this.lowerLimit1;
  97426. } else if (d1 > this.upperLimit1) {
  97427. if (this.limitState1 != 1) {
  97428. this.limitState1 = 1;
  97429. this.limitImpulse1 = 0;
  97430. }
  97431. this.limitVelocity1 = this.upperLimit1 - d1;
  97432. if (!enableSpring1) d1 = this.upperLimit1;
  97433. } else {
  97434. this.limitState1 = 2;
  97435. this.limitImpulse1 = 0;
  97436. this.limitVelocity1 = 0;
  97437. }
  97438. if (!enableSpring1) {
  97439. if (this.limitVelocity1 > 0.005) this.limitVelocity1 -= 0.005;
  97440. else if (this.limitVelocity1 < -0.005) this.limitVelocity1 += 0.005;
  97441. else this.limitVelocity1 = 0;
  97442. }
  97443. } else {
  97444. this.limitState1 = 2;
  97445. this.limitImpulse1 = 0;
  97446. }
  97447. if (enableLimit2) {
  97448. if (this.lowerLimit2 == this.upperLimit2) {
  97449. if (this.limitState2 != 0) {
  97450. this.limitState2 = 0;
  97451. this.limitImpulse2 = 0;
  97452. }
  97453. this.limitVelocity2 = this.lowerLimit2 - d2;
  97454. if (!enableSpring2) d2 = this.lowerLimit2;
  97455. } else if (d2 < this.lowerLimit2) {
  97456. if (this.limitState2 != -1) {
  97457. this.limitState2 = -1;
  97458. this.limitImpulse2 = 0;
  97459. }
  97460. this.limitVelocity2 = this.lowerLimit2 - d2;
  97461. if (!enableSpring2) d2 = this.lowerLimit2;
  97462. } else if (d2 > this.upperLimit2) {
  97463. if (this.limitState2 != 1) {
  97464. this.limitState2 = 1;
  97465. this.limitImpulse2 = 0;
  97466. }
  97467. this.limitVelocity2 = this.upperLimit2 - d2;
  97468. if (!enableSpring2) d2 = this.upperLimit2;
  97469. } else {
  97470. this.limitState2 = 2;
  97471. this.limitImpulse2 = 0;
  97472. this.limitVelocity2 = 0;
  97473. }
  97474. if (!enableSpring2) {
  97475. if (this.limitVelocity2 > 0.005) this.limitVelocity2 -= 0.005;
  97476. else if (this.limitVelocity2 < -0.005) this.limitVelocity2 += 0.005;
  97477. else this.limitVelocity2 = 0;
  97478. }
  97479. } else {
  97480. this.limitState2 = 2;
  97481. this.limitImpulse2 = 0;
  97482. }
  97483. if (enableLimit3) {
  97484. if (this.lowerLimit3 == this.upperLimit3) {
  97485. if (this.limitState3 != 0) {
  97486. this.limitState3 = 0;
  97487. this.limitImpulse3 = 0;
  97488. }
  97489. this.limitVelocity3 = this.lowerLimit3 - d3;
  97490. if (!enableSpring3) d3 = this.lowerLimit3;
  97491. } else if (d3 < this.lowerLimit3) {
  97492. if (this.limitState3 != -1) {
  97493. this.limitState3 = -1;
  97494. this.limitImpulse3 = 0;
  97495. }
  97496. this.limitVelocity3 = this.lowerLimit3 - d3;
  97497. if (!enableSpring3) d3 = this.lowerLimit3;
  97498. } else if (d3 > this.upperLimit3) {
  97499. if (this.limitState3 != 1) {
  97500. this.limitState3 = 1;
  97501. this.limitImpulse3 = 0;
  97502. }
  97503. this.limitVelocity3 = this.upperLimit3 - d3;
  97504. if (!enableSpring3) d3 = this.upperLimit3;
  97505. } else {
  97506. this.limitState3 = 2;
  97507. this.limitImpulse3 = 0;
  97508. this.limitVelocity3 = 0;
  97509. }
  97510. if (!enableSpring3) {
  97511. if (this.limitVelocity3 > 0.005) this.limitVelocity3 -= 0.005;
  97512. else if (this.limitVelocity3 < -0.005) this.limitVelocity3 += 0.005;
  97513. else this.limitVelocity3 = 0;
  97514. }
  97515. } else {
  97516. this.limitState3 = 2;
  97517. this.limitImpulse3 = 0;
  97518. }
  97519. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  97520. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  97521. } else {
  97522. this.motorImpulse1 = 0;
  97523. this.maxMotorImpulse1 = 0;
  97524. }
  97525. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  97526. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  97527. } else {
  97528. this.motorImpulse2 = 0;
  97529. this.maxMotorImpulse2 = 0;
  97530. }
  97531. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  97532. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  97533. } else {
  97534. this.motorImpulse3 = 0;
  97535. this.maxMotorImpulse3 = 0;
  97536. }
  97537. var rdx = d1 * this.ax1 + d2 * this.ax2 + d3 * this.ax2;
  97538. var rdy = d1 * this.ay1 + d2 * this.ay2 + d3 * this.ay2;
  97539. var rdz = d1 * this.az1 + d2 * this.az2 + d3 * this.az2;
  97540. var w1 = this.m2 / (this.m1 + this.m2);
  97541. if (this.weight >= 0) w1 = this.weight; // use given weight
  97542. var w2 = 1 - w1;
  97543. this.r1x = this.r1.x + rdx * w1;
  97544. this.r1y = this.r1.y + rdy * w1;
  97545. this.r1z = this.r1.z + rdz * w1;
  97546. this.r2x = this.r2.x - rdx * w2;
  97547. this.r2y = this.r2.y - rdy * w2;
  97548. this.r2z = this.r2.z - rdz * w2;
  97549. // build jacobians
  97550. this.t1x1 = this.r1y * this.az1 - this.r1z * this.ay1;
  97551. this.t1y1 = this.r1z * this.ax1 - this.r1x * this.az1;
  97552. this.t1z1 = this.r1x * this.ay1 - this.r1y * this.ax1;
  97553. this.t2x1 = this.r2y * this.az1 - this.r2z * this.ay1;
  97554. this.t2y1 = this.r2z * this.ax1 - this.r2x * this.az1;
  97555. this.t2z1 = this.r2x * this.ay1 - this.r2y * this.ax1;
  97556. this.l1x1 = this.ax1 * this.m1;
  97557. this.l1y1 = this.ay1 * this.m1;
  97558. this.l1z1 = this.az1 * this.m1;
  97559. this.l2x1 = this.ax1 * this.m2;
  97560. this.l2y1 = this.ay1 * this.m2;
  97561. this.l2z1 = this.az1 * this.m2;
  97562. this.a1x1 = this.t1x1 * this.i1e00 + this.t1y1 * this.i1e01 + this.t1z1 * this.i1e02;
  97563. this.a1y1 = this.t1x1 * this.i1e10 + this.t1y1 * this.i1e11 + this.t1z1 * this.i1e12;
  97564. this.a1z1 = this.t1x1 * this.i1e20 + this.t1y1 * this.i1e21 + this.t1z1 * this.i1e22;
  97565. this.a2x1 = this.t2x1 * this.i2e00 + this.t2y1 * this.i2e01 + this.t2z1 * this.i2e02;
  97566. this.a2y1 = this.t2x1 * this.i2e10 + this.t2y1 * this.i2e11 + this.t2z1 * this.i2e12;
  97567. this.a2z1 = this.t2x1 * this.i2e20 + this.t2y1 * this.i2e21 + this.t2z1 * this.i2e22;
  97568. this.t1x2 = this.r1y * this.az2 - this.r1z * this.ay2;
  97569. this.t1y2 = this.r1z * this.ax2 - this.r1x * this.az2;
  97570. this.t1z2 = this.r1x * this.ay2 - this.r1y * this.ax2;
  97571. this.t2x2 = this.r2y * this.az2 - this.r2z * this.ay2;
  97572. this.t2y2 = this.r2z * this.ax2 - this.r2x * this.az2;
  97573. this.t2z2 = this.r2x * this.ay2 - this.r2y * this.ax2;
  97574. this.l1x2 = this.ax2 * this.m1;
  97575. this.l1y2 = this.ay2 * this.m1;
  97576. this.l1z2 = this.az2 * this.m1;
  97577. this.l2x2 = this.ax2 * this.m2;
  97578. this.l2y2 = this.ay2 * this.m2;
  97579. this.l2z2 = this.az2 * this.m2;
  97580. this.a1x2 = this.t1x2 * this.i1e00 + this.t1y2 * this.i1e01 + this.t1z2 * this.i1e02;
  97581. this.a1y2 = this.t1x2 * this.i1e10 + this.t1y2 * this.i1e11 + this.t1z2 * this.i1e12;
  97582. this.a1z2 = this.t1x2 * this.i1e20 + this.t1y2 * this.i1e21 + this.t1z2 * this.i1e22;
  97583. this.a2x2 = this.t2x2 * this.i2e00 + this.t2y2 * this.i2e01 + this.t2z2 * this.i2e02;
  97584. this.a2y2 = this.t2x2 * this.i2e10 + this.t2y2 * this.i2e11 + this.t2z2 * this.i2e12;
  97585. this.a2z2 = this.t2x2 * this.i2e20 + this.t2y2 * this.i2e21 + this.t2z2 * this.i2e22;
  97586. this.t1x3 = this.r1y * this.az3 - this.r1z * this.ay3;
  97587. this.t1y3 = this.r1z * this.ax3 - this.r1x * this.az3;
  97588. this.t1z3 = this.r1x * this.ay3 - this.r1y * this.ax3;
  97589. this.t2x3 = this.r2y * this.az3 - this.r2z * this.ay3;
  97590. this.t2y3 = this.r2z * this.ax3 - this.r2x * this.az3;
  97591. this.t2z3 = this.r2x * this.ay3 - this.r2y * this.ax3;
  97592. this.l1x3 = this.ax3 * this.m1;
  97593. this.l1y3 = this.ay3 * this.m1;
  97594. this.l1z3 = this.az3 * this.m1;
  97595. this.l2x3 = this.ax3 * this.m2;
  97596. this.l2y3 = this.ay3 * this.m2;
  97597. this.l2z3 = this.az3 * this.m2;
  97598. this.a1x3 = this.t1x3 * this.i1e00 + this.t1y3 * this.i1e01 + this.t1z3 * this.i1e02;
  97599. this.a1y3 = this.t1x3 * this.i1e10 + this.t1y3 * this.i1e11 + this.t1z3 * this.i1e12;
  97600. this.a1z3 = this.t1x3 * this.i1e20 + this.t1y3 * this.i1e21 + this.t1z3 * this.i1e22;
  97601. this.a2x3 = this.t2x3 * this.i2e00 + this.t2y3 * this.i2e01 + this.t2z3 * this.i2e02;
  97602. this.a2y3 = this.t2x3 * this.i2e10 + this.t2y3 * this.i2e11 + this.t2z3 * this.i2e12;
  97603. this.a2z3 = this.t2x3 * this.i2e20 + this.t2y3 * this.i2e21 + this.t2z3 * this.i2e22;
  97604. // build an impulse matrix
  97605. var m12 = this.m1 + this.m2;
  97606. this.k00 = (this.ax1 * this.ax1 + this.ay1 * this.ay1 + this.az1 * this.az1) * m12;
  97607. this.k01 = (this.ax1 * this.ax2 + this.ay1 * this.ay2 + this.az1 * this.az2) * m12;
  97608. this.k02 = (this.ax1 * this.ax3 + this.ay1 * this.ay3 + this.az1 * this.az3) * m12;
  97609. this.k10 = (this.ax2 * this.ax1 + this.ay2 * this.ay1 + this.az2 * this.az1) * m12;
  97610. this.k11 = (this.ax2 * this.ax2 + this.ay2 * this.ay2 + this.az2 * this.az2) * m12;
  97611. this.k12 = (this.ax2 * this.ax3 + this.ay2 * this.ay3 + this.az2 * this.az3) * m12;
  97612. this.k20 = (this.ax3 * this.ax1 + this.ay3 * this.ay1 + this.az3 * this.az1) * m12;
  97613. this.k21 = (this.ax3 * this.ax2 + this.ay3 * this.ay2 + this.az3 * this.az2) * m12;
  97614. this.k22 = (this.ax3 * this.ax3 + this.ay3 * this.ay3 + this.az3 * this.az3) * m12;
  97615. this.k00 += this.t1x1 * this.a1x1 + this.t1y1 * this.a1y1 + this.t1z1 * this.a1z1;
  97616. this.k01 += this.t1x1 * this.a1x2 + this.t1y1 * this.a1y2 + this.t1z1 * this.a1z2;
  97617. this.k02 += this.t1x1 * this.a1x3 + this.t1y1 * this.a1y3 + this.t1z1 * this.a1z3;
  97618. this.k10 += this.t1x2 * this.a1x1 + this.t1y2 * this.a1y1 + this.t1z2 * this.a1z1;
  97619. this.k11 += this.t1x2 * this.a1x2 + this.t1y2 * this.a1y2 + this.t1z2 * this.a1z2;
  97620. this.k12 += this.t1x2 * this.a1x3 + this.t1y2 * this.a1y3 + this.t1z2 * this.a1z3;
  97621. this.k20 += this.t1x3 * this.a1x1 + this.t1y3 * this.a1y1 + this.t1z3 * this.a1z1;
  97622. this.k21 += this.t1x3 * this.a1x2 + this.t1y3 * this.a1y2 + this.t1z3 * this.a1z2;
  97623. this.k22 += this.t1x3 * this.a1x3 + this.t1y3 * this.a1y3 + this.t1z3 * this.a1z3;
  97624. this.k00 += this.t2x1 * this.a2x1 + this.t2y1 * this.a2y1 + this.t2z1 * this.a2z1;
  97625. this.k01 += this.t2x1 * this.a2x2 + this.t2y1 * this.a2y2 + this.t2z1 * this.a2z2;
  97626. this.k02 += this.t2x1 * this.a2x3 + this.t2y1 * this.a2y3 + this.t2z1 * this.a2z3;
  97627. this.k10 += this.t2x2 * this.a2x1 + this.t2y2 * this.a2y1 + this.t2z2 * this.a2z1;
  97628. this.k11 += this.t2x2 * this.a2x2 + this.t2y2 * this.a2y2 + this.t2z2 * this.a2z2;
  97629. this.k12 += this.t2x2 * this.a2x3 + this.t2y2 * this.a2y3 + this.t2z2 * this.a2z3;
  97630. this.k20 += this.t2x3 * this.a2x1 + this.t2y3 * this.a2y1 + this.t2z3 * this.a2z1;
  97631. this.k21 += this.t2x3 * this.a2x2 + this.t2y3 * this.a2y2 + this.t2z3 * this.a2z2;
  97632. this.k22 += this.t2x3 * this.a2x3 + this.t2y3 * this.a2y3 + this.t2z3 * this.a2z3;
  97633. this.kv00 = this.k00;
  97634. this.kv11 = this.k11;
  97635. this.kv22 = this.k22;
  97636. this.dv00 = 1 / this.kv00;
  97637. this.dv11 = 1 / this.kv11;
  97638. this.dv22 = 1 / this.kv22;
  97639. if (enableSpring1 && this.limitState1 != 2) {
  97640. var omega = 6.2831853 * frequency1;
  97641. var k = omega * omega * timeStep;
  97642. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  97643. this.cfm1 = this.kv00 * dmp;
  97644. this.limitVelocity1 *= k * dmp;
  97645. } else {
  97646. this.cfm1 = 0;
  97647. this.limitVelocity1 *= invTimeStep * 0.05;
  97648. }
  97649. if (enableSpring2 && this.limitState2 != 2) {
  97650. omega = 6.2831853 * frequency2;
  97651. k = omega * omega * timeStep;
  97652. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  97653. this.cfm2 = this.kv11 * dmp;
  97654. this.limitVelocity2 *= k * dmp;
  97655. } else {
  97656. this.cfm2 = 0;
  97657. this.limitVelocity2 *= invTimeStep * 0.05;
  97658. }
  97659. if (enableSpring3 && this.limitState3 != 2) {
  97660. omega = 6.2831853 * frequency3;
  97661. k = omega * omega * timeStep;
  97662. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  97663. this.cfm3 = this.kv22 * dmp;
  97664. this.limitVelocity3 *= k * dmp;
  97665. } else {
  97666. this.cfm3 = 0;
  97667. this.limitVelocity3 *= invTimeStep * 0.05;
  97668. }
  97669. this.k00 += this.cfm1;
  97670. this.k11 += this.cfm2;
  97671. this.k22 += this.cfm3;
  97672. var inv = 1 / (
  97673. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  97674. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  97675. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  97676. );
  97677. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  97678. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  97679. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  97680. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  97681. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  97682. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  97683. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  97684. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  97685. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  97686. // warm starting
  97687. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  97688. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  97689. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  97690. this.l1.x += totalImpulse1 * this.l1x1 + totalImpulse2 * this.l1x2 + totalImpulse3 * this.l1x3;
  97691. this.l1.y += totalImpulse1 * this.l1y1 + totalImpulse2 * this.l1y2 + totalImpulse3 * this.l1y3;
  97692. this.l1.z += totalImpulse1 * this.l1z1 + totalImpulse2 * this.l1z2 + totalImpulse3 * this.l1z3;
  97693. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  97694. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  97695. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  97696. this.l2.x -= totalImpulse1 * this.l2x1 + totalImpulse2 * this.l2x2 + totalImpulse3 * this.l2x3;
  97697. this.l2.y -= totalImpulse1 * this.l2y1 + totalImpulse2 * this.l2y2 + totalImpulse3 * this.l2y3;
  97698. this.l2.z -= totalImpulse1 * this.l2z1 + totalImpulse2 * this.l2z2 + totalImpulse3 * this.l2z3;
  97699. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  97700. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  97701. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  97702. },
  97703. solve: function () {
  97704. 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;
  97705. 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;
  97706. 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;
  97707. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  97708. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  97709. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  97710. var oldMotorImpulse1 = this.motorImpulse1;
  97711. var oldMotorImpulse2 = this.motorImpulse2;
  97712. var oldMotorImpulse3 = this.motorImpulse3;
  97713. var dMotorImpulse1 = 0;
  97714. var dMotorImpulse2 = 0;
  97715. var dMotorImpulse3 = 0;
  97716. if (this.enableMotor1) {
  97717. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  97718. this.motorImpulse1 += dMotorImpulse1;
  97719. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  97720. this.motorImpulse1 = this.maxMotorImpulse1;
  97721. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  97722. this.motorImpulse1 = -this.maxMotorImpulse1;
  97723. }
  97724. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  97725. }
  97726. if (this.enableMotor2) {
  97727. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  97728. this.motorImpulse2 += dMotorImpulse2;
  97729. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  97730. this.motorImpulse2 = this.maxMotorImpulse2;
  97731. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  97732. this.motorImpulse2 = -this.maxMotorImpulse2;
  97733. }
  97734. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  97735. }
  97736. if (this.enableMotor3) {
  97737. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  97738. this.motorImpulse3 += dMotorImpulse3;
  97739. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  97740. this.motorImpulse3 = this.maxMotorImpulse3;
  97741. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  97742. this.motorImpulse3 = -this.maxMotorImpulse3;
  97743. }
  97744. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  97745. }
  97746. // apply motor impulse to relative velocity
  97747. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  97748. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  97749. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  97750. // subtract target velocity and applied impulse
  97751. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  97752. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  97753. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  97754. var oldLimitImpulse1 = this.limitImpulse1;
  97755. var oldLimitImpulse2 = this.limitImpulse2;
  97756. var oldLimitImpulse3 = this.limitImpulse3;
  97757. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  97758. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  97759. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  97760. this.limitImpulse1 += dLimitImpulse1;
  97761. this.limitImpulse2 += dLimitImpulse2;
  97762. this.limitImpulse3 += dLimitImpulse3;
  97763. // clamp
  97764. var clampState = 0;
  97765. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  97766. dLimitImpulse1 = -oldLimitImpulse1;
  97767. rvn2 += dLimitImpulse1 * this.k10;
  97768. rvn3 += dLimitImpulse1 * this.k20;
  97769. clampState |= 1;
  97770. }
  97771. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  97772. dLimitImpulse2 = -oldLimitImpulse2;
  97773. rvn1 += dLimitImpulse2 * this.k01;
  97774. rvn3 += dLimitImpulse2 * this.k21;
  97775. clampState |= 2;
  97776. }
  97777. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  97778. dLimitImpulse3 = -oldLimitImpulse3;
  97779. rvn1 += dLimitImpulse3 * this.k02;
  97780. rvn2 += dLimitImpulse3 * this.k12;
  97781. clampState |= 4;
  97782. }
  97783. // update un-clamped impulse
  97784. // TODO: isolate division
  97785. var det;
  97786. switch (clampState) {
  97787. case 1:// update 2 3
  97788. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  97789. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  97790. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  97791. break;
  97792. case 2:// update 1 3
  97793. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  97794. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  97795. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  97796. break;
  97797. case 3:// update 3
  97798. dLimitImpulse3 = rvn3 / this.k22;
  97799. break;
  97800. case 4:// update 1 2
  97801. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  97802. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  97803. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  97804. break;
  97805. case 5:// update 2
  97806. dLimitImpulse2 = rvn2 / this.k11;
  97807. break;
  97808. case 6:// update 1
  97809. dLimitImpulse1 = rvn1 / this.k00;
  97810. break;
  97811. }
  97812. this.limitImpulse1 = oldLimitImpulse1 + dLimitImpulse1;
  97813. this.limitImpulse2 = oldLimitImpulse2 + dLimitImpulse2;
  97814. this.limitImpulse3 = oldLimitImpulse3 + dLimitImpulse3;
  97815. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  97816. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  97817. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  97818. // apply impulse
  97819. this.l1.x += dImpulse1 * this.l1x1 + dImpulse2 * this.l1x2 + dImpulse3 * this.l1x3;
  97820. this.l1.y += dImpulse1 * this.l1y1 + dImpulse2 * this.l1y2 + dImpulse3 * this.l1y3;
  97821. this.l1.z += dImpulse1 * this.l1z1 + dImpulse2 * this.l1z2 + dImpulse3 * this.l1z3;
  97822. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  97823. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  97824. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  97825. this.l2.x -= dImpulse1 * this.l2x1 + dImpulse2 * this.l2x2 + dImpulse3 * this.l2x3;
  97826. this.l2.y -= dImpulse1 * this.l2y1 + dImpulse2 * this.l2y2 + dImpulse3 * this.l2y3;
  97827. this.l2.z -= dImpulse1 * this.l2z1 + dImpulse2 * this.l2z2 + dImpulse3 * this.l2z3;
  97828. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  97829. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  97830. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  97831. }
  97832. }
  97833. /**
  97834. * A translational constraint for various joints.
  97835. * @author saharan
  97836. */
  97837. OIMO.TranslationalConstraint = function (joint, limitMotor) {
  97838. this.cfm = NaN;
  97839. this.m1 = NaN;
  97840. this.m2 = NaN;
  97841. this.i1e00 = NaN;
  97842. this.i1e01 = NaN;
  97843. this.i1e02 = NaN;
  97844. this.i1e10 = NaN;
  97845. this.i1e11 = NaN;
  97846. this.i1e12 = NaN;
  97847. this.i1e20 = NaN;
  97848. this.i1e21 = NaN;
  97849. this.i1e22 = NaN;
  97850. this.i2e00 = NaN;
  97851. this.i2e01 = NaN;
  97852. this.i2e02 = NaN;
  97853. this.i2e10 = NaN;
  97854. this.i2e11 = NaN;
  97855. this.i2e12 = NaN;
  97856. this.i2e20 = NaN;
  97857. this.i2e21 = NaN;
  97858. this.i2e22 = NaN;
  97859. this.motorDenom = NaN;
  97860. this.invMotorDenom = NaN;
  97861. this.invDenom = NaN;
  97862. this.ax = NaN;
  97863. this.ay = NaN;
  97864. this.az = NaN;
  97865. this.r1x = NaN;
  97866. this.r1y = NaN;
  97867. this.r1z = NaN;
  97868. this.r2x = NaN;
  97869. this.r2y = NaN;
  97870. this.r2z = NaN;
  97871. this.t1x = NaN;
  97872. this.t1y = NaN;
  97873. this.t1z = NaN;
  97874. this.t2x = NaN;
  97875. this.t2y = NaN;
  97876. this.t2z = NaN;
  97877. this.l1x = NaN;
  97878. this.l1y = NaN;
  97879. this.l1z = NaN;
  97880. this.l2x = NaN;
  97881. this.l2y = NaN;
  97882. this.l2z = NaN;
  97883. this.a1x = NaN;
  97884. this.a1y = NaN;
  97885. this.a1z = NaN;
  97886. this.a2x = NaN;
  97887. this.a2y = NaN;
  97888. this.a2z = NaN;
  97889. this.lowerLimit = NaN;
  97890. this.upperLimit = NaN;
  97891. this.limitVelocity = NaN;
  97892. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  97893. this.enableMotor = false;
  97894. this.motorSpeed = NaN;
  97895. this.maxMotorForce = NaN;
  97896. this.maxMotorImpulse = NaN;
  97897. this.limitMotor = limitMotor;
  97898. this.b1 = joint.body1;
  97899. this.b2 = joint.body2;
  97900. this.p1 = joint.anchorPoint1;
  97901. this.p2 = joint.anchorPoint2;
  97902. this.r1 = joint.relativeAnchorPoint1;
  97903. this.r2 = joint.relativeAnchorPoint2;
  97904. this.l1 = this.b1.linearVelocity;
  97905. this.l2 = this.b2.linearVelocity;
  97906. this.a1 = this.b1.angularVelocity;
  97907. this.a2 = this.b2.angularVelocity;
  97908. this.i1 = this.b1.inverseInertia;
  97909. this.i2 = this.b2.inverseInertia;
  97910. this.limitImpulse = 0;
  97911. this.motorImpulse = 0;
  97912. }
  97913. OIMO.TranslationalConstraint.prototype = {
  97914. constructor: OIMO.TranslationalConstraint,
  97915. preSolve: function (timeStep, invTimeStep) {
  97916. this.ax = this.limitMotor.axis.x;
  97917. this.ay = this.limitMotor.axis.y;
  97918. this.az = this.limitMotor.axis.z;
  97919. this.lowerLimit = this.limitMotor.lowerLimit;
  97920. this.upperLimit = this.limitMotor.upperLimit;
  97921. this.motorSpeed = this.limitMotor.motorSpeed;
  97922. this.maxMotorForce = this.limitMotor.maxMotorForce;
  97923. this.enableMotor = this.maxMotorForce > 0;
  97924. this.m1 = this.b1.inverseMass;
  97925. this.m2 = this.b2.inverseMass;
  97926. var ti1 = this.i1.elements;
  97927. var ti2 = this.i2.elements;
  97928. this.i1e00 = ti1[0];
  97929. this.i1e01 = ti1[1];
  97930. this.i1e02 = ti1[2];
  97931. this.i1e10 = ti1[3];
  97932. this.i1e11 = ti1[4];
  97933. this.i1e12 = ti1[5];
  97934. this.i1e20 = ti1[6];
  97935. this.i1e21 = ti1[7];
  97936. this.i1e22 = ti1[8];
  97937. this.i2e00 = ti2[0];
  97938. this.i2e01 = ti2[1];
  97939. this.i2e02 = ti2[2];
  97940. this.i2e10 = ti2[3];
  97941. this.i2e11 = ti2[4];
  97942. this.i2e12 = ti2[5];
  97943. this.i2e20 = ti2[6];
  97944. this.i2e21 = ti2[7];
  97945. this.i2e22 = ti2[8];
  97946. var dx = this.p2.x - this.p1.x;
  97947. var dy = this.p2.y - this.p1.y;
  97948. var dz = this.p2.z - this.p1.z;
  97949. var d = dx * this.ax + dy * this.ay + dz * this.az;
  97950. var frequency = this.limitMotor.frequency;
  97951. var enableSpring = frequency > 0;
  97952. var enableLimit = this.lowerLimit <= this.upperLimit;
  97953. if (enableSpring && d > 20 || d < -20) {
  97954. enableSpring = false;
  97955. }
  97956. if (enableLimit) {
  97957. if (this.lowerLimit == this.upperLimit) {
  97958. if (this.limitState != 0) {
  97959. this.limitState = 0;
  97960. this.limitImpulse = 0;
  97961. }
  97962. this.limitVelocity = this.lowerLimit - d;
  97963. if (!enableSpring) d = this.lowerLimit;
  97964. } else if (d < this.lowerLimit) {
  97965. if (this.limitState != -1) {
  97966. this.limitState = -1;
  97967. this.limitImpulse = 0;
  97968. }
  97969. this.limitVelocity = this.lowerLimit - d;
  97970. if (!enableSpring) d = this.lowerLimit;
  97971. } else if (d > this.upperLimit) {
  97972. if (this.limitState != 1) {
  97973. this.limitState = 1;
  97974. this.limitImpulse = 0;
  97975. }
  97976. this.limitVelocity = this.upperLimit - d;
  97977. if (!enableSpring) d = this.upperLimit;
  97978. } else {
  97979. this.limitState = 2;
  97980. this.limitImpulse = 0;
  97981. this.limitVelocity = 0;
  97982. }
  97983. if (!enableSpring) {
  97984. if (this.limitVelocity > 0.005) this.limitVelocity -= 0.005;
  97985. else if (this.limitVelocity < -0.005) this.limitVelocity += 0.005;
  97986. else this.limitVelocity = 0;
  97987. }
  97988. } else {
  97989. this.limitState = 2;
  97990. this.limitImpulse = 0;
  97991. }
  97992. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  97993. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  97994. } else {
  97995. this.motorImpulse = 0;
  97996. this.maxMotorImpulse = 0;
  97997. }
  97998. var rdx = d * this.ax;
  97999. var rdy = d * this.ay;
  98000. var rdz = d * this.az;
  98001. var w1 = this.m1 / (this.m1 + this.m2);
  98002. var w2 = 1 - w1;
  98003. this.r1x = this.r1.x + rdx * w1;
  98004. this.r1y = this.r1.y + rdy * w1;
  98005. this.r1z = this.r1.z + rdz * w1;
  98006. this.r2x = this.r2.x - rdx * w2;
  98007. this.r2y = this.r2.y - rdy * w2;
  98008. this.r2z = this.r2.z - rdz * w2;
  98009. this.t1x = this.r1y * this.az - this.r1z * this.ay;
  98010. this.t1y = this.r1z * this.ax - this.r1x * this.az;
  98011. this.t1z = this.r1x * this.ay - this.r1y * this.ax;
  98012. this.t2x = this.r2y * this.az - this.r2z * this.ay;
  98013. this.t2y = this.r2z * this.ax - this.r2x * this.az;
  98014. this.t2z = this.r2x * this.ay - this.r2y * this.ax;
  98015. this.l1x = this.ax * this.m1;
  98016. this.l1y = this.ay * this.m1;
  98017. this.l1z = this.az * this.m1;
  98018. this.l2x = this.ax * this.m2;
  98019. this.l2y = this.ay * this.m2;
  98020. this.l2z = this.az * this.m2;
  98021. this.a1x = this.t1x * this.i1e00 + this.t1y * this.i1e01 + this.t1z * this.i1e02;
  98022. this.a1y = this.t1x * this.i1e10 + this.t1y * this.i1e11 + this.t1z * this.i1e12;
  98023. this.a1z = this.t1x * this.i1e20 + this.t1y * this.i1e21 + this.t1z * this.i1e22;
  98024. this.a2x = this.t2x * this.i2e00 + this.t2y * this.i2e01 + this.t2z * this.i2e02;
  98025. this.a2y = this.t2x * this.i2e10 + this.t2y * this.i2e11 + this.t2z * this.i2e12;
  98026. this.a2z = this.t2x * this.i2e20 + this.t2y * this.i2e21 + this.t2z * this.i2e22;
  98027. this.motorDenom =
  98028. this.m1 + this.m2 +
  98029. this.ax * (this.a1y * this.r1z - this.a1z * this.r1y + this.a2y * this.r2z - this.a2z * this.r2y) +
  98030. this.ay * (this.a1z * this.r1x - this.a1x * this.r1z + this.a2z * this.r2x - this.a2x * this.r2z) +
  98031. this.az * (this.a1x * this.r1y - this.a1y * this.r1x + this.a2x * this.r2y - this.a2y * this.r2x);
  98032. this.invMotorDenom = 1 / this.motorDenom;
  98033. if (enableSpring && this.limitState != 2) {
  98034. var omega = 6.2831853 * frequency;
  98035. var k = omega * omega * timeStep;
  98036. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  98037. this.cfm = this.motorDenom * dmp;
  98038. this.limitVelocity *= k * dmp;
  98039. } else {
  98040. this.cfm = 0;
  98041. this.limitVelocity *= invTimeStep * 0.05;
  98042. }
  98043. this.invDenom = 1 / (this.motorDenom + this.cfm);
  98044. var totalImpulse = this.limitImpulse + this.motorImpulse;
  98045. this.l1.x += totalImpulse * this.l1x;
  98046. this.l1.y += totalImpulse * this.l1y;
  98047. this.l1.z += totalImpulse * this.l1z;
  98048. this.a1.x += totalImpulse * this.a1x;
  98049. this.a1.y += totalImpulse * this.a1y;
  98050. this.a1.z += totalImpulse * this.a1z;
  98051. this.l2.x -= totalImpulse * this.l2x;
  98052. this.l2.y -= totalImpulse * this.l2y;
  98053. this.l2.z -= totalImpulse * this.l2z;
  98054. this.a2.x -= totalImpulse * this.a2x;
  98055. this.a2.y -= totalImpulse * this.a2y;
  98056. this.a2.z -= totalImpulse * this.a2z;
  98057. },
  98058. solve: function () {
  98059. var rvn =
  98060. this.ax * (this.l2.x - this.l1.x) + this.ay * (this.l2.y - this.l1.y) + this.az * (this.l2.z - this.l1.z) +
  98061. 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;
  98062. // motor part
  98063. var newMotorImpulse;
  98064. if (this.enableMotor) {
  98065. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  98066. var oldMotorImpulse = this.motorImpulse;
  98067. this.motorImpulse += newMotorImpulse;
  98068. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  98069. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  98070. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  98071. rvn -= newMotorImpulse * this.motorDenom;
  98072. } else newMotorImpulse = 0;
  98073. // limit part
  98074. var newLimitImpulse;
  98075. if (this.limitState != 2) {
  98076. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  98077. var oldLimitImpulse = this.limitImpulse;
  98078. this.limitImpulse += newLimitImpulse;
  98079. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  98080. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  98081. } else newLimitImpulse = 0;
  98082. var totalImpulse = newLimitImpulse + newMotorImpulse;
  98083. this.l1.x += totalImpulse * this.l1x;
  98084. this.l1.y += totalImpulse * this.l1y;
  98085. this.l1.z += totalImpulse * this.l1z;
  98086. this.a1.x += totalImpulse * this.a1x;
  98087. this.a1.y += totalImpulse * this.a1y;
  98088. this.a1.z += totalImpulse * this.a1z;
  98089. this.l2.x -= totalImpulse * this.l2x;
  98090. this.l2.y -= totalImpulse * this.l2y;
  98091. this.l2.z -= totalImpulse * this.l2z;
  98092. this.a2.x -= totalImpulse * this.a2x;
  98093. this.a2.y -= totalImpulse * this.a2y;
  98094. this.a2.z -= totalImpulse * this.a2z;
  98095. }
  98096. }
  98097. /**
  98098. * A contact is a pair of shapes whose axis-aligned bounding boxes are overlapping.
  98099. * @author saharan
  98100. */
  98101. OIMO.Contact = function () {
  98102. // The first shape.
  98103. this.shape1 = null;
  98104. // The second shape.
  98105. this.shape2 = null;
  98106. // The first rigid body.
  98107. this.body1 = null;
  98108. // The second rigid body.
  98109. this.body2 = null;
  98110. // The previous contact in the world.
  98111. this.prev = null;
  98112. // The next contact in the world.
  98113. this.next = null;
  98114. // Internal
  98115. this.persisting = false;
  98116. // Whether both the rigid bodies are sleeping or not.
  98117. this.sleeping = false;
  98118. // The collision detector between two shapes.
  98119. this.detector = null;
  98120. // The contact constraint of the contact.
  98121. this.constraint = null;
  98122. // Whether the shapes are touching or not.
  98123. this.touching = false;
  98124. this.b1Link = new OIMO.ContactLink(this);
  98125. this.b2Link = new OIMO.ContactLink(this);
  98126. this.s1Link = new OIMO.ContactLink(this);
  98127. this.s2Link = new OIMO.ContactLink(this);
  98128. // The contact manifold of the contact.
  98129. this.manifold = new OIMO.ContactManifold();
  98130. this.buffer = [];// vector 4
  98131. this.buffer.length = 4;
  98132. this.buffer[0] = new OIMO.ImpulseDataBuffer();
  98133. this.buffer[1] = new OIMO.ImpulseDataBuffer();
  98134. this.buffer[2] = new OIMO.ImpulseDataBuffer();
  98135. this.buffer[3] = new OIMO.ImpulseDataBuffer();
  98136. this.points = this.manifold.points;
  98137. this.constraint = new OIMO.ContactConstraint(this.manifold);
  98138. }
  98139. OIMO.Contact.prototype = {
  98140. constructor: OIMO.Contact,
  98141. mixRestitution: function (restitution1, restitution2) {
  98142. return OIMO.sqrt(restitution1 * restitution2);
  98143. },
  98144. mixFriction: function (friction1, friction2) {
  98145. return OIMO.sqrt(friction1 * friction2);
  98146. },
  98147. /**
  98148. * Update the contact manifold.
  98149. */
  98150. updateManifold: function () {
  98151. this.constraint.restitution = this.mixRestitution(this.shape1.restitution, this.shape2.restitution);
  98152. this.constraint.friction = this.mixFriction(this.shape1.friction, this.shape2.friction);
  98153. var numBuffers = this.manifold.numPoints;
  98154. var i = numBuffers;
  98155. while (i--) {
  98156. //for(var i=0;i<numBuffers;i++){
  98157. var b = this.buffer[i];
  98158. var p = this.points[i];
  98159. b.lp1X = p.localPoint1.x;
  98160. b.lp1Y = p.localPoint1.y;
  98161. b.lp1Z = p.localPoint1.z;
  98162. b.lp2X = p.localPoint2.x;
  98163. b.lp2Y = p.localPoint2.y;
  98164. b.lp2Z = p.localPoint2.z;
  98165. b.impulse = p.normalImpulse;
  98166. }
  98167. this.manifold.numPoints = 0;
  98168. this.detector.detectCollision(this.shape1, this.shape2, this.manifold);
  98169. var num = this.manifold.numPoints;
  98170. if (num == 0) {
  98171. this.touching = false;
  98172. return;
  98173. }
  98174. this.touching = true;
  98175. i = num;
  98176. while (i--) {
  98177. //for(i=0; i<num; i++){
  98178. p = this.points[i];
  98179. var lp1x = p.localPoint1.x;
  98180. var lp1y = p.localPoint1.y;
  98181. var lp1z = p.localPoint1.z;
  98182. var lp2x = p.localPoint2.x;
  98183. var lp2y = p.localPoint2.y;
  98184. var lp2z = p.localPoint2.z;
  98185. var index = -1;
  98186. var minDistance = 0.0004;
  98187. var j = numBuffers;
  98188. while (j--) {
  98189. //for(var j=0;j<numBuffers;j++){
  98190. b = this.buffer[j];
  98191. var dx = b.lp1X - lp1x;
  98192. var dy = b.lp1Y - lp1y;
  98193. var dz = b.lp1Z - lp1z;
  98194. var distance1 = dx * dx + dy * dy + dz * dz;
  98195. dx = b.lp2X - lp2x;
  98196. dy = b.lp2Y - lp2y;
  98197. dz = b.lp2Z - lp2z;
  98198. var distance2 = dx * dx + dy * dy + dz * dz;
  98199. if (distance1 < distance2) {
  98200. if (distance1 < minDistance) {
  98201. minDistance = distance1;
  98202. index = j;
  98203. }
  98204. } else {
  98205. if (distance2 < minDistance) {
  98206. minDistance = distance2;
  98207. index = j;
  98208. }
  98209. }
  98210. }
  98211. if (index != -1) {
  98212. var tmp = this.buffer[index];
  98213. this.buffer[index] = this.buffer[--numBuffers];
  98214. this.buffer[numBuffers] = tmp;
  98215. p.normalImpulse = tmp.impulse;
  98216. p.warmStarted = true;
  98217. } else {
  98218. p.normalImpulse = 0;
  98219. p.warmStarted = false;
  98220. }
  98221. }
  98222. },
  98223. /**
  98224. * Attach the contact to the shapes.
  98225. * @param shape1
  98226. * @param shape2
  98227. */
  98228. attach: function (shape1, shape2) {
  98229. this.shape1 = shape1;
  98230. this.shape2 = shape2;
  98231. this.body1 = shape1.parent;
  98232. this.body2 = shape2.parent;
  98233. this.manifold.body1 = this.body1;
  98234. this.manifold.body2 = this.body2;
  98235. this.constraint.body1 = this.body1;
  98236. this.constraint.body2 = this.body2;
  98237. this.constraint.attach();
  98238. this.s1Link.shape = shape2;
  98239. this.s1Link.body = this.body2;
  98240. this.s2Link.shape = shape1;
  98241. this.s2Link.body = this.body1;
  98242. if (shape1.contactLink != null) (this.s1Link.next = shape1.contactLink).prev = this.s1Link;
  98243. else this.s1Link.next = null;
  98244. shape1.contactLink = this.s1Link;
  98245. shape1.numContacts++;
  98246. if (shape2.contactLink != null) (this.s2Link.next = shape2.contactLink).prev = this.s2Link;
  98247. else this.s2Link.next = null;
  98248. shape2.contactLink = this.s2Link;
  98249. shape2.numContacts++;
  98250. this.b1Link.shape = shape2;
  98251. this.b1Link.body = this.body2;
  98252. this.b2Link.shape = shape1;
  98253. this.b2Link.body = this.body1;
  98254. if (this.body1.contactLink != null) (this.b1Link.next = this.body1.contactLink).prev = this.b1Link;
  98255. else this.b1Link.next = null;
  98256. this.body1.contactLink = this.b1Link;
  98257. this.body1.numContacts++;
  98258. if (this.body2.contactLink != null) (this.b2Link.next = this.body2.contactLink).prev = this.b2Link;
  98259. else this.b2Link.next = null;
  98260. this.body2.contactLink = this.b2Link;
  98261. this.body2.numContacts++;
  98262. this.prev = null;
  98263. this.next = null;
  98264. this.persisting = true;
  98265. this.sleeping = this.body1.sleeping && this.body2.sleeping;
  98266. this.manifold.numPoints = 0;
  98267. },
  98268. /**
  98269. * Detach the contact from the shapes.
  98270. */
  98271. detach: function () {
  98272. var prev = this.s1Link.prev;
  98273. var next = this.s1Link.next;
  98274. if (prev !== null) prev.next = next;
  98275. if (next !== null) next.prev = prev;
  98276. if (this.shape1.contactLink == this.s1Link) this.shape1.contactLink = next;
  98277. this.s1Link.prev = null;
  98278. this.s1Link.next = null;
  98279. this.s1Link.shape = null;
  98280. this.s1Link.body = null;
  98281. this.shape1.numContacts--;
  98282. prev = this.s2Link.prev;
  98283. next = this.s2Link.next;
  98284. if (prev !== null) prev.next = next;
  98285. if (next !== null) next.prev = prev;
  98286. if (this.shape2.contactLink == this.s2Link) this.shape2.contactLink = next;
  98287. this.s2Link.prev = null;
  98288. this.s2Link.next = null;
  98289. this.s2Link.shape = null;
  98290. this.s2Link.body = null;
  98291. this.shape2.numContacts--;
  98292. prev = this.b1Link.prev;
  98293. next = this.b1Link.next;
  98294. if (prev !== null) prev.next = next;
  98295. if (next !== null) next.prev = prev;
  98296. if (this.body1.contactLink == this.b1Link) this.body1.contactLink = next;
  98297. this.b1Link.prev = null;
  98298. this.b1Link.next = null;
  98299. this.b1Link.shape = null;
  98300. this.b1Link.body = null;
  98301. this.body1.numContacts--;
  98302. prev = this.b2Link.prev;
  98303. next = this.b2Link.next;
  98304. if (prev !== null) prev.next = next;
  98305. if (next !== null) next.prev = prev;
  98306. if (this.body2.contactLink == this.b2Link) this.body2.contactLink = next;
  98307. this.b2Link.prev = null;
  98308. this.b2Link.next = null;
  98309. this.b2Link.shape = null;
  98310. this.b2Link.body = null;
  98311. this.body2.numContacts--;
  98312. this.manifold.body1 = null;
  98313. this.manifold.body2 = null;
  98314. this.constraint.body1 = null;
  98315. this.constraint.body2 = null;
  98316. this.constraint.detach();
  98317. this.shape1 = null;
  98318. this.shape2 = null;
  98319. this.body1 = null;
  98320. this.body2 = null;
  98321. }
  98322. }
  98323. /**
  98324. * ...
  98325. * @author saharan
  98326. */
  98327. OIMO.ContactConstraint = function (manifold) {
  98328. OIMO.Constraint.call(this);
  98329. // The contact manifold of the constraint.
  98330. this.manifold = manifold;
  98331. // The coefficient of restitution of the constraint.
  98332. this.restitution = NaN;
  98333. // The coefficient of friction of the constraint.
  98334. this.friction = NaN;
  98335. this.p1 = null;
  98336. this.p2 = null;
  98337. this.lv1 = null;
  98338. this.lv2 = null;
  98339. this.av1 = null;
  98340. this.av2 = null;
  98341. this.i1 = null;
  98342. this.i2 = null;
  98343. this.ii1 = null;
  98344. this.ii2 = null;
  98345. this.m1 = NaN;
  98346. this.m2 = NaN;
  98347. this.num = 0;
  98348. this.ps = manifold.points;
  98349. this.cs = new OIMO.ContactPointDataBuffer();
  98350. this.cs.next = new OIMO.ContactPointDataBuffer();
  98351. this.cs.next.next = new OIMO.ContactPointDataBuffer();
  98352. this.cs.next.next.next = new OIMO.ContactPointDataBuffer();
  98353. }
  98354. OIMO.ContactConstraint.prototype = Object.create(OIMO.Constraint.prototype);
  98355. /**
  98356. * Attach the constraint to the bodies.
  98357. */
  98358. OIMO.ContactConstraint.prototype.attach = function () {
  98359. this.p1 = this.body1.position;
  98360. this.p2 = this.body2.position;
  98361. this.lv1 = this.body1.linearVelocity;
  98362. this.av1 = this.body1.angularVelocity;
  98363. this.lv2 = this.body2.linearVelocity;
  98364. this.av2 = this.body2.angularVelocity;
  98365. this.i1 = this.body1.inverseInertia;
  98366. this.i2 = this.body2.inverseInertia;
  98367. }
  98368. /**
  98369. * Detach the constraint from the bodies.
  98370. */
  98371. OIMO.ContactConstraint.prototype.detach = function () {
  98372. this.p1 = null;
  98373. this.p2 = null;
  98374. this.lv1 = null;
  98375. this.lv2 = null;
  98376. this.av1 = null;
  98377. this.av2 = null;
  98378. this.i1 = null;
  98379. this.i2 = null;
  98380. }
  98381. OIMO.ContactConstraint.prototype.preSolve = function (timeStep, invTimeStep) {
  98382. this.m1 = this.body1.inverseMass;
  98383. this.m2 = this.body2.inverseMass;
  98384. this.ii1 = this.i1.clone();
  98385. this.ii2 = this.i2.clone();
  98386. var ii1 = this.ii1.elements;
  98387. var ii2 = this.ii2.elements;
  98388. var p1x = this.p1.x;
  98389. var p1y = this.p1.y;
  98390. var p1z = this.p1.z;
  98391. var p2x = this.p2.x;
  98392. var p2y = this.p2.y;
  98393. var p2z = this.p2.z;
  98394. var m1m2 = this.m1 + this.m2;
  98395. this.num = this.manifold.numPoints;
  98396. var c = this.cs;
  98397. for (var i = 0; i < this.num; i++) {
  98398. var p = this.ps[i];
  98399. var tmp1X;
  98400. var tmp1Y;
  98401. var tmp1Z;
  98402. var tmp2X;
  98403. var tmp2Y;
  98404. var tmp2Z;
  98405. tmp1X = p.position.x;
  98406. tmp1Y = p.position.y;
  98407. tmp1Z = p.position.z;
  98408. var rp1X = tmp1X - p1x;
  98409. var rp1Y = tmp1Y - p1y;
  98410. var rp1Z = tmp1Z - p1z;
  98411. var rp2X = tmp1X - p2x;
  98412. var rp2Y = tmp1Y - p2y;
  98413. var rp2Z = tmp1Z - p2z;
  98414. c.rp1X = rp1X;
  98415. c.rp1Y = rp1Y;
  98416. c.rp1Z = rp1Z;
  98417. c.rp2X = rp2X;
  98418. c.rp2Y = rp2Y;
  98419. c.rp2Z = rp2Z;
  98420. c.norImp = p.normalImpulse;
  98421. c.tanImp = p.tangentImpulse;
  98422. c.binImp = p.binormalImpulse;
  98423. var norX = p.normal.x;
  98424. var norY = p.normal.y;
  98425. var norZ = p.normal.z;
  98426. var rvX = (this.lv2.x + this.av2.y * rp2Z - this.av2.z * rp2Y) - (this.lv1.x + this.av1.y * rp1Z - this.av1.z * rp1Y);
  98427. var rvY = (this.lv2.y + this.av2.z * rp2X - this.av2.x * rp2Z) - (this.lv1.y + this.av1.z * rp1X - this.av1.x * rp1Z);
  98428. var rvZ = (this.lv2.z + this.av2.x * rp2Y - this.av2.y * rp2X) - (this.lv1.z + this.av1.x * rp1Y - this.av1.y * rp1X);
  98429. var rvn = norX * rvX + norY * rvY + norZ * rvZ;
  98430. var tanX = rvX - rvn * norX;
  98431. var tanY = rvY - rvn * norY;
  98432. var tanZ = rvZ - rvn * norZ;
  98433. var len = tanX * tanX + tanY * tanY + tanZ * tanZ;
  98434. if (len > 0.04) {
  98435. len = 1 / OIMO.sqrt(len);
  98436. } else {
  98437. tanX = norY * norX - norZ * norZ;
  98438. tanY = -norZ * norY - norX * norX;
  98439. tanZ = norX * norZ + norY * norY;
  98440. len = 1 / OIMO.sqrt(tanX * tanX + tanY * tanY + tanZ * tanZ);
  98441. }
  98442. tanX *= len;
  98443. tanY *= len;
  98444. tanZ *= len;
  98445. var binX = norY * tanZ - norZ * tanY;
  98446. var binY = norZ * tanX - norX * tanZ;
  98447. var binZ = norX * tanY - norY * tanX;
  98448. c.norX = norX;
  98449. c.norY = norY;
  98450. c.norZ = norZ;
  98451. c.tanX = tanX;
  98452. c.tanY = tanY;
  98453. c.tanZ = tanZ;
  98454. c.binX = binX;
  98455. c.binY = binY;
  98456. c.binZ = binZ;
  98457. c.norU1X = norX * this.m1;
  98458. c.norU1Y = norY * this.m1;
  98459. c.norU1Z = norZ * this.m1;
  98460. c.norU2X = norX * this.m2;
  98461. c.norU2Y = norY * this.m2;
  98462. c.norU2Z = norZ * this.m2;
  98463. c.tanU1X = tanX * this.m1;
  98464. c.tanU1Y = tanY * this.m1;
  98465. c.tanU1Z = tanZ * this.m1;
  98466. c.tanU2X = tanX * this.m2;
  98467. c.tanU2Y = tanY * this.m2;
  98468. c.tanU2Z = tanZ * this.m2;
  98469. c.binU1X = binX * this.m1;
  98470. c.binU1Y = binY * this.m1;
  98471. c.binU1Z = binZ * this.m1;
  98472. c.binU2X = binX * this.m2;
  98473. c.binU2Y = binY * this.m2;
  98474. c.binU2Z = binZ * this.m2;
  98475. var norT1X = rp1Y * norZ - rp1Z * norY;
  98476. var norT1Y = rp1Z * norX - rp1X * norZ;
  98477. var norT1Z = rp1X * norY - rp1Y * norX;
  98478. var norT2X = rp2Y * norZ - rp2Z * norY;
  98479. var norT2Y = rp2Z * norX - rp2X * norZ;
  98480. var norT2Z = rp2X * norY - rp2Y * norX;
  98481. var tanT1X = rp1Y * tanZ - rp1Z * tanY;
  98482. var tanT1Y = rp1Z * tanX - rp1X * tanZ;
  98483. var tanT1Z = rp1X * tanY - rp1Y * tanX;
  98484. var tanT2X = rp2Y * tanZ - rp2Z * tanY;
  98485. var tanT2Y = rp2Z * tanX - rp2X * tanZ;
  98486. var tanT2Z = rp2X * tanY - rp2Y * tanX;
  98487. var binT1X = rp1Y * binZ - rp1Z * binY;
  98488. var binT1Y = rp1Z * binX - rp1X * binZ;
  98489. var binT1Z = rp1X * binY - rp1Y * binX;
  98490. var binT2X = rp2Y * binZ - rp2Z * binY;
  98491. var binT2Y = rp2Z * binX - rp2X * binZ;
  98492. var binT2Z = rp2X * binY - rp2Y * binX;
  98493. var norTU1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  98494. var norTU1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  98495. var norTU1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  98496. var norTU2X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  98497. var norTU2Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  98498. var norTU2Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  98499. var tanTU1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  98500. var tanTU1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  98501. var tanTU1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  98502. var tanTU2X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  98503. var tanTU2Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  98504. var tanTU2Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  98505. var binTU1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  98506. var binTU1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  98507. var binTU1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  98508. var binTU2X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  98509. var binTU2Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  98510. var binTU2Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  98511. c.norT1X = norT1X;
  98512. c.norT1Y = norT1Y;
  98513. c.norT1Z = norT1Z;
  98514. c.tanT1X = tanT1X;
  98515. c.tanT1Y = tanT1Y;
  98516. c.tanT1Z = tanT1Z;
  98517. c.binT1X = binT1X;
  98518. c.binT1Y = binT1Y;
  98519. c.binT1Z = binT1Z;
  98520. c.norT2X = norT2X;
  98521. c.norT2Y = norT2Y;
  98522. c.norT2Z = norT2Z;
  98523. c.tanT2X = tanT2X;
  98524. c.tanT2Y = tanT2Y;
  98525. c.tanT2Z = tanT2Z;
  98526. c.binT2X = binT2X;
  98527. c.binT2Y = binT2Y;
  98528. c.binT2Z = binT2Z;
  98529. c.norTU1X = norTU1X;
  98530. c.norTU1Y = norTU1Y;
  98531. c.norTU1Z = norTU1Z;
  98532. c.tanTU1X = tanTU1X;
  98533. c.tanTU1Y = tanTU1Y;
  98534. c.tanTU1Z = tanTU1Z;
  98535. c.binTU1X = binTU1X;
  98536. c.binTU1Y = binTU1Y;
  98537. c.binTU1Z = binTU1Z;
  98538. c.norTU2X = norTU2X;
  98539. c.norTU2Y = norTU2Y;
  98540. c.norTU2Z = norTU2Z;
  98541. c.tanTU2X = tanTU2X;
  98542. c.tanTU2Y = tanTU2Y;
  98543. c.tanTU2Z = tanTU2Z;
  98544. c.binTU2X = binTU2X;
  98545. c.binTU2Y = binTU2Y;
  98546. c.binTU2Z = binTU2Z;
  98547. tmp1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  98548. tmp1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  98549. tmp1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  98550. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  98551. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  98552. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  98553. tmp1X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  98554. tmp1Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  98555. tmp1Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  98556. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  98557. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  98558. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  98559. var norDen = 1 / (m1m2 + norX * tmp2X + norY * tmp2Y + norZ * tmp2Z);
  98560. tmp1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  98561. tmp1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  98562. tmp1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  98563. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  98564. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  98565. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  98566. tmp1X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  98567. tmp1Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  98568. tmp1Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  98569. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  98570. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  98571. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  98572. var tanDen = 1 / (m1m2 + tanX * tmp2X + tanY * tmp2Y + tanZ * tmp2Z);
  98573. tmp1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  98574. tmp1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  98575. tmp1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  98576. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  98577. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  98578. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  98579. tmp1X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  98580. tmp1Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  98581. tmp1Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  98582. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  98583. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  98584. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  98585. var binDen = 1 / (m1m2 + binX * tmp2X + binY * tmp2Y + binZ * tmp2Z);
  98586. c.norDen = norDen;
  98587. c.tanDen = tanDen;
  98588. c.binDen = binDen;
  98589. if (p.warmStarted) {
  98590. var norImp = p.normalImpulse;
  98591. this.lv1.x += c.norU1X * norImp;
  98592. this.lv1.y += c.norU1Y * norImp;
  98593. this.lv1.z += c.norU1Z * norImp;
  98594. this.av1.x += norTU1X * norImp;
  98595. this.av1.y += norTU1Y * norImp;
  98596. this.av1.z += norTU1Z * norImp;
  98597. this.lv2.x -= c.norU2X * norImp;
  98598. this.lv2.y -= c.norU2Y * norImp;
  98599. this.lv2.z -= c.norU2Z * norImp;
  98600. this.av2.x -= norTU2X * norImp;
  98601. this.av2.y -= norTU2Y * norImp;
  98602. this.av2.z -= norTU2Z * norImp;
  98603. c.norImp = norImp;
  98604. c.tanImp = 0;
  98605. c.binImp = 0;
  98606. rvn = 0; // disable bouncing
  98607. } else {
  98608. c.norImp = 0;
  98609. c.tanImp = 0;
  98610. c.binImp = 0;
  98611. }
  98612. if (rvn > -1) {
  98613. rvn = 0; // disable bouncing
  98614. }
  98615. var norTar = this.restitution * -rvn;
  98616. var sepV = -(p.penetration + 0.005) * invTimeStep * 0.05; // allow 0.5cm error
  98617. if (norTar < sepV) norTar = sepV;
  98618. c.norTar = norTar;
  98619. c.last = i == this.num - 1;
  98620. c = c.next;
  98621. }
  98622. }
  98623. OIMO.ContactConstraint.prototype.solve = function () {
  98624. var lv1x = this.lv1.x;
  98625. var lv1y = this.lv1.y;
  98626. var lv1z = this.lv1.z;
  98627. var lv2x = this.lv2.x;
  98628. var lv2y = this.lv2.y;
  98629. var lv2z = this.lv2.z;
  98630. var av1x = this.av1.x;
  98631. var av1y = this.av1.y;
  98632. var av1z = this.av1.z;
  98633. var av2x = this.av2.x;
  98634. var av2y = this.av2.y;
  98635. var av2z = this.av2.z;
  98636. var c = this.cs;
  98637. while (true) {
  98638. var oldImp1;
  98639. var newImp1;
  98640. var oldImp2;
  98641. var newImp2;
  98642. var rvn;
  98643. var norImp = c.norImp;
  98644. var tanImp = c.tanImp;
  98645. var binImp = c.binImp;
  98646. var max = -norImp * this.friction;
  98647. var rvX = lv2x - lv1x;
  98648. var rvY = lv2y - lv1y;
  98649. var rvZ = lv2z - lv1z;
  98650. rvn =
  98651. rvX * c.tanX + rvY * c.tanY + rvZ * c.tanZ +
  98652. av2x * c.tanT2X + av2y * c.tanT2Y + av2z * c.tanT2Z -
  98653. av1x * c.tanT1X - av1y * c.tanT1Y - av1z * c.tanT1Z
  98654. ;
  98655. oldImp1 = tanImp;
  98656. newImp1 = rvn * c.tanDen;
  98657. tanImp += newImp1;
  98658. rvn =
  98659. rvX * c.binX + rvY * c.binY + rvZ * c.binZ +
  98660. av2x * c.binT2X + av2y * c.binT2Y + av2z * c.binT2Z -
  98661. av1x * c.binT1X - av1y * c.binT1Y - av1z * c.binT1Z
  98662. ;
  98663. oldImp2 = binImp;
  98664. newImp2 = rvn * c.binDen;
  98665. binImp += newImp2;
  98666. // cone friction clamp
  98667. var len = tanImp * tanImp + binImp * binImp;
  98668. if (len > max * max) {
  98669. len = max / OIMO.sqrt(len);
  98670. tanImp *= len;
  98671. binImp *= len;
  98672. }
  98673. newImp1 = tanImp - oldImp1;
  98674. newImp2 = binImp - oldImp2;
  98675. lv1x += c.tanU1X * newImp1 + c.binU1X * newImp2;
  98676. lv1y += c.tanU1Y * newImp1 + c.binU1Y * newImp2;
  98677. lv1z += c.tanU1Z * newImp1 + c.binU1Z * newImp2;
  98678. av1x += c.tanTU1X * newImp1 + c.binTU1X * newImp2;
  98679. av1y += c.tanTU1Y * newImp1 + c.binTU1Y * newImp2;
  98680. av1z += c.tanTU1Z * newImp1 + c.binTU1Z * newImp2;
  98681. lv2x -= c.tanU2X * newImp1 + c.binU2X * newImp2;
  98682. lv2y -= c.tanU2Y * newImp1 + c.binU2Y * newImp2;
  98683. lv2z -= c.tanU2Z * newImp1 + c.binU2Z * newImp2;
  98684. av2x -= c.tanTU2X * newImp1 + c.binTU2X * newImp2;
  98685. av2y -= c.tanTU2Y * newImp1 + c.binTU2Y * newImp2;
  98686. av2z -= c.tanTU2Z * newImp1 + c.binTU2Z * newImp2;
  98687. // restitution part
  98688. rvn =
  98689. (lv2x - lv1x) * c.norX + (lv2y - lv1y) * c.norY + (lv2z - lv1z) * c.norZ +
  98690. av2x * c.norT2X + av2y * c.norT2Y + av2z * c.norT2Z -
  98691. av1x * c.norT1X - av1y * c.norT1Y - av1z * c.norT1Z;
  98692. oldImp1 = norImp;
  98693. newImp1 = (rvn - c.norTar) * c.norDen;
  98694. norImp += newImp1;
  98695. if (norImp > 0) norImp = 0;
  98696. newImp1 = norImp - oldImp1;
  98697. lv1x += c.norU1X * newImp1;
  98698. lv1y += c.norU1Y * newImp1;
  98699. lv1z += c.norU1Z * newImp1;
  98700. av1x += c.norTU1X * newImp1;
  98701. av1y += c.norTU1Y * newImp1;
  98702. av1z += c.norTU1Z * newImp1;
  98703. lv2x -= c.norU2X * newImp1;
  98704. lv2y -= c.norU2Y * newImp1;
  98705. lv2z -= c.norU2Z * newImp1;
  98706. av2x -= c.norTU2X * newImp1;
  98707. av2y -= c.norTU2Y * newImp1;
  98708. av2z -= c.norTU2Z * newImp1;
  98709. c.norImp = norImp;
  98710. c.tanImp = tanImp;
  98711. c.binImp = binImp;
  98712. if (c.last) break;
  98713. c = c.next;
  98714. }
  98715. this.lv1.x = lv1x;
  98716. this.lv1.y = lv1y;
  98717. this.lv1.z = lv1z;
  98718. this.lv2.x = lv2x;
  98719. this.lv2.y = lv2y;
  98720. this.lv2.z = lv2z;
  98721. this.av1.x = av1x;
  98722. this.av1.y = av1y;
  98723. this.av1.z = av1z;
  98724. this.av2.x = av2x;
  98725. this.av2.y = av2y;
  98726. this.av2.z = av2z;
  98727. }
  98728. OIMO.ContactConstraint.prototype.postSolve = function () {
  98729. var c = this.cs;
  98730. var i = this.num;
  98731. while (i--) {
  98732. //for(var i=0;i<this.num;i++){
  98733. var p = this.ps[i];
  98734. p.normal.x = c.norX;
  98735. p.normal.y = c.norY;
  98736. p.normal.z = c.norZ;
  98737. p.tangent.x = c.tanX;
  98738. p.tangent.y = c.tanY;
  98739. p.tangent.z = c.tanZ;
  98740. p.binormal.x = c.binX;
  98741. p.binormal.y = c.binY;
  98742. p.binormal.z = c.binZ;
  98743. p.normalImpulse = c.norImp;
  98744. p.tangentImpulse = c.tanImp;
  98745. p.binormalImpulse = c.binImp;
  98746. p.normalDenominator = c.norDen;
  98747. p.tangentDenominator = c.tanDen;
  98748. p.binormalDenominator = c.binDen;
  98749. c = c.next;
  98750. }
  98751. }
  98752. /**
  98753. * A link list of contacts.
  98754. * @author saharan
  98755. */
  98756. OIMO.ContactLink = function (contact) {
  98757. // The previous contact link.
  98758. this.prev = null;
  98759. // The next contact link.
  98760. this.next = null;
  98761. // The shape of the contact.
  98762. this.shape = null;
  98763. // The other rigid body.
  98764. this.body = null;
  98765. // The contact of the link.
  98766. this.contact = contact;
  98767. }
  98768. /**
  98769. * A contact manifold between two shapes.
  98770. * @author saharan
  98771. */
  98772. OIMO.ContactManifold = function () {
  98773. // The first rigid body.
  98774. this.body1 = null;
  98775. // The second rigid body.
  98776. this.body2 = null;
  98777. // The number of manifold points.
  98778. this.numPoints = 0;
  98779. // The manifold points.
  98780. this.points = [];
  98781. this.points.length = 4;
  98782. this.points[0] = new OIMO.ManifoldPoint();
  98783. this.points[1] = new OIMO.ManifoldPoint();
  98784. this.points[2] = new OIMO.ManifoldPoint();
  98785. this.points[3] = new OIMO.ManifoldPoint();
  98786. }
  98787. OIMO.ContactManifold.prototype = {
  98788. constructor: OIMO.ContactManifold,
  98789. /**
  98790. * Reset the manifold.
  98791. * @param shape1
  98792. * @param shape2
  98793. */
  98794. reset: function (shape1, shape2) {
  98795. this.body1 = shape1.parent;
  98796. this.body2 = shape2.parent;
  98797. this.numPoints = 0;
  98798. },
  98799. /**
  98800. * Add a point into this manifold.
  98801. * @param x
  98802. * @param y
  98803. * @param z
  98804. * @param normalX
  98805. * @param normalY
  98806. * @param normalZ
  98807. * @param penetration
  98808. * @param flip
  98809. */
  98810. addPoint: function (x, y, z, normalX, normalY, normalZ, penetration, flip) {
  98811. var p = this.points[this.numPoints++];
  98812. p.position.x = x;
  98813. p.position.y = y;
  98814. p.position.z = z;
  98815. var r = this.body1.rotation;
  98816. var rx = x - this.body1.position.x;
  98817. var ry = y - this.body1.position.y;
  98818. var rz = z - this.body1.position.z;
  98819. var tr = r.elements;
  98820. p.localPoint1.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  98821. p.localPoint1.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  98822. p.localPoint1.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  98823. r = this.body2.rotation;
  98824. rx = x - this.body2.position.x;
  98825. ry = y - this.body2.position.y;
  98826. rz = z - this.body2.position.z;
  98827. p.localPoint2.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  98828. p.localPoint2.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  98829. p.localPoint2.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  98830. p.normalImpulse = 0;
  98831. if (flip) {
  98832. p.normal.x = -normalX;
  98833. p.normal.y = -normalY;
  98834. p.normal.z = -normalZ;
  98835. } else {
  98836. p.normal.x = normalX;
  98837. p.normal.y = normalY;
  98838. p.normal.z = normalZ;
  98839. }
  98840. p.penetration = penetration;
  98841. p.warmStarted = false;
  98842. }
  98843. }
  98844. OIMO.ContactPointDataBuffer = function () {
  98845. this.norX = NaN;
  98846. this.norY = NaN;
  98847. this.norZ = NaN;
  98848. this.tanX = NaN;
  98849. this.tanY = NaN;
  98850. this.tanZ = NaN;
  98851. this.binX = NaN;
  98852. this.binY = NaN;
  98853. this.binZ = NaN;
  98854. this.rp1X = NaN;
  98855. this.rp1Y = NaN;
  98856. this.rp1Z = NaN;
  98857. this.rp2X = NaN;
  98858. this.rp2Y = NaN;
  98859. this.rp2Z = NaN;
  98860. this.norU1X = NaN;
  98861. this.norU1Y = NaN;
  98862. this.norU1Z = NaN;
  98863. this.norU2X = NaN;
  98864. this.norU2Y = NaN;
  98865. this.norU2Z = NaN;
  98866. this.tanU1X = NaN;
  98867. this.tanU1Y = NaN;
  98868. this.tanU1Z = NaN;
  98869. this.tanU2X = NaN;
  98870. this.tanU2Y = NaN;
  98871. this.tanU2Z = NaN;
  98872. this.binU1X = NaN;
  98873. this.binU1Y = NaN;
  98874. this.binU1Z = NaN;
  98875. this.binU2X = NaN;
  98876. this.binU2Y = NaN;
  98877. this.binU2Z = NaN;
  98878. this.norT1X = NaN;
  98879. this.norT1Y = NaN;
  98880. this.norT1Z = NaN;
  98881. this.norT2X = NaN;
  98882. this.norT2Y = NaN;
  98883. this.norT2Z = NaN;
  98884. this.tanT1X = NaN;
  98885. this.tanT1Y = NaN;
  98886. this.tanT1Z = NaN;
  98887. this.tanT2X = NaN;
  98888. this.tanT2Y = NaN;
  98889. this.tanT2Z = NaN;
  98890. this.binT1X = NaN;
  98891. this.binT1Y = NaN;
  98892. this.binT1Z = NaN;
  98893. this.binT2X = NaN;
  98894. this.binT2Y = NaN;
  98895. this.binT2Z = NaN;
  98896. this.norTU1X = NaN;
  98897. this.norTU1Y = NaN;
  98898. this.norTU1Z = NaN;
  98899. this.norTU2X = NaN;
  98900. this.norTU2Y = NaN;
  98901. this.norTU2Z = NaN;
  98902. this.tanTU1X = NaN;
  98903. this.tanTU1Y = NaN;
  98904. this.tanTU1Z = NaN;
  98905. this.tanTU2X = NaN;
  98906. this.tanTU2Y = NaN;
  98907. this.tanTU2Z = NaN;
  98908. this.binTU1X = NaN;
  98909. this.binTU1Y = NaN;
  98910. this.binTU1Z = NaN;
  98911. this.binTU2X = NaN;
  98912. this.binTU2Y = NaN;
  98913. this.binTU2Z = NaN;
  98914. this.norImp = NaN;
  98915. this.tanImp = NaN;
  98916. this.binImp = NaN;
  98917. this.norDen = NaN;
  98918. this.tanDen = NaN;
  98919. this.binDen = NaN;
  98920. this.norTar = NaN;
  98921. this.next = null;
  98922. this.last = false;
  98923. }
  98924. OIMO.ImpulseDataBuffer = function () {
  98925. this.lp1X = NaN;
  98926. this.lp1Y = NaN;
  98927. this.lp1Z = NaN;
  98928. this.lp2X = NaN;
  98929. this.lp2Y = NaN;
  98930. this.lp2Z = NaN;
  98931. this.impulse = NaN;
  98932. }
  98933. /**
  98934. * The class holds details of the contact point.
  98935. * @author saharan
  98936. */
  98937. OIMO.ManifoldPoint = function () {
  98938. // Whether this manifold point is persisting or not.
  98939. this.warmStarted = false;
  98940. // The position of this manifold point.
  98941. this.position = new OIMO.Vec3();
  98942. // The position in the first shape's coordinate.
  98943. this.localPoint1 = new OIMO.Vec3();
  98944. // The position in the second shape's coordinate.
  98945. this.localPoint2 = new OIMO.Vec3();
  98946. // The normal vector of this manifold point.
  98947. this.normal = new OIMO.Vec3();
  98948. // The tangent vector of this manifold point.
  98949. this.tangent = new OIMO.Vec3();
  98950. // The binormal vector of this manifold point.
  98951. this.binormal = new OIMO.Vec3();
  98952. // The impulse in normal direction.
  98953. this.normalImpulse = 0;
  98954. // The impulse in tangent direction.
  98955. this.tangentImpulse = 0;
  98956. // The impulse in binormal direction.
  98957. this.binormalImpulse = 0;
  98958. // The denominator in normal direction.
  98959. this.normalDenominator = 0;
  98960. // The denominator in tangent direction.
  98961. this.tangentDenominator = 0;
  98962. // The denominator in binormal direction.
  98963. this.binormalDenominator = 0;
  98964. // The depth of penetration.
  98965. this.penetration = 0;
  98966. }
  98967. /**
  98968. * This class holds mass information of a shape.
  98969. * @author saharan
  98970. */
  98971. OIMO.MassInfo = function () {
  98972. // Mass of the shape.
  98973. this.mass = 0;
  98974. // The moment inertia of the shape.
  98975. this.inertia = new OIMO.Mat33();
  98976. };
  98977. /**
  98978. * A shape is used to detect collisions of rigid bodies.
  98979. * @author saharan
  98980. * @author lo-th
  98981. */
  98982. OIMO.Shape = function (config) {
  98983. this.type = OIMO.SHAPE_NULL;
  98984. // The global identification of the shape should be unique to the shape.
  98985. this.id = OIMO.nextID++;
  98986. // The previous shape in parent rigid body.
  98987. this.prev = null;
  98988. // The next shape in parent rigid body.
  98989. this.next = null;
  98990. // The proxy of the shape used for broad-phase collision detection.
  98991. this.proxy = null;
  98992. // The parent rigid body of the shape.
  98993. this.parent = null;
  98994. // The linked list of the contacts with the shape.
  98995. this.contactLink = null;
  98996. // The number of the contacts with the shape.
  98997. this.numContacts = 0;
  98998. // The center of gravity of the shape in world coordinate system.
  98999. this.position = new OIMO.Vec3();
  99000. // The rotation matrix of the shape in world coordinate system
  99001. this.rotation = new OIMO.Mat33();
  99002. // The position of the shape in parent's coordinate system.
  99003. this.relativePosition = new OIMO.Vec3().copy(config.relativePosition);
  99004. // The rotation matrix of the shape in parent's coordinate system.
  99005. this.relativeRotation = new OIMO.Mat33().copy(config.relativeRotation);
  99006. // The axis-aligned bounding box of the shape.
  99007. this.aabb = new OIMO.AABB();
  99008. // The density of the shape.
  99009. this.density = config.density;
  99010. // The coefficient of friction of the shape.
  99011. this.friction = config.friction;
  99012. // The coefficient of restitution of the shape.
  99013. this.restitution = config.restitution;
  99014. // The bits of the collision groups to which the shape belongs.
  99015. this.belongsTo = config.belongsTo;
  99016. // The bits of the collision groups with which the shape collides.
  99017. this.collidesWith = config.collidesWith;
  99018. };
  99019. OIMO.Shape.prototype = {
  99020. constructor: OIMO.Shape,
  99021. // Calculate the mass information of the shape.
  99022. calculateMassInfo: function (out) {
  99023. OIMO.Error("Shape", "Inheritance error.");
  99024. },
  99025. // Update the proxy of the shape.
  99026. updateProxy: function () {
  99027. OIMO.Error("Shape", "Inheritance error.");
  99028. }
  99029. };
  99030. /**
  99031. * A shape configuration holds common configuration data for constructing a shape.
  99032. * Shape configurations can be reused safely.
  99033. * @author saharan
  99034. */
  99035. OIMO.ShapeConfig = function () {
  99036. // The position of the shape in parent's coordinate system.
  99037. this.relativePosition = new OIMO.Vec3();
  99038. // The rotation matrix of the shape in parent's coordinate system.
  99039. this.relativeRotation = new OIMO.Mat33();
  99040. // The coefficient of friction of the shape.
  99041. this.friction = 0.4;
  99042. // The coefficient of restitution of the shape.
  99043. this.restitution = 0.2;
  99044. // The density of the shape.
  99045. this.density = 1;
  99046. // The bits of the collision groups to which the shape belongs.
  99047. this.belongsTo = 1;
  99048. // The bits of the collision groups with which the shape collides.
  99049. this.collidesWith = 0xffffffff;
  99050. };
  99051. /**
  99052. * A box shape.
  99053. * @author saharan
  99054. * @author lo-th
  99055. */
  99056. OIMO.BoxShape = function (config, Width, Height, Depth) {
  99057. OIMO.Shape.call(this, config);
  99058. this.type = OIMO.SHAPE_BOX;
  99059. // The width of the box.
  99060. this.width = Width;
  99061. // The height of the box.
  99062. this.height = Height;
  99063. // The depth of the box.
  99064. this.depth = Depth;
  99065. // The half-width of the box.
  99066. this.halfWidth = Width * 0.5;
  99067. // The half-height of the box.
  99068. this.halfHeight = Height * 0.5;
  99069. // The half-depth of the box.
  99070. this.halfDepth = Depth * 0.5;
  99071. this.dimentions = new OIMO_ARRAY_TYPE(18);
  99072. this.elements = new OIMO_ARRAY_TYPE(24);
  99073. };
  99074. OIMO.BoxShape.prototype = Object.create(OIMO.Shape.prototype);
  99075. OIMO.BoxShape.prototype.constructor = OIMO.BoxShape;
  99076. OIMO.BoxShape.prototype.calculateMassInfo = function (out) {
  99077. var mass = this.width * this.height * this.depth * this.density;
  99078. var divid = 1 / 12;
  99079. out.mass = mass;
  99080. out.inertia.set(
  99081. mass * (this.height * this.height + this.depth * this.depth) * divid, 0, 0,
  99082. 0, mass * (this.width * this.width + this.depth * this.depth) * divid, 0,
  99083. 0, 0, mass * (this.width * this.width + this.height * this.height) * divid
  99084. );
  99085. };
  99086. OIMO.BoxShape.prototype.updateProxy = function () {
  99087. var te = this.rotation.elements;
  99088. var di = this.dimentions;
  99089. // Width
  99090. di[0] = te[0];
  99091. di[1] = te[3];
  99092. di[2] = te[6];
  99093. // Height
  99094. di[3] = te[1];
  99095. di[4] = te[4];
  99096. di[5] = te[7];
  99097. // Depth
  99098. di[6] = te[2];
  99099. di[7] = te[5];
  99100. di[8] = te[8];
  99101. // halp Width
  99102. di[9] = te[0] * this.halfWidth;
  99103. di[10] = te[3] * this.halfWidth;
  99104. di[11] = te[6] * this.halfWidth;
  99105. // halp Height
  99106. di[12] = te[1] * this.halfHeight;
  99107. di[13] = te[4] * this.halfHeight;
  99108. di[14] = te[7] * this.halfHeight;
  99109. // halp Depth
  99110. di[15] = te[2] * this.halfDepth;
  99111. di[16] = te[5] * this.halfDepth;
  99112. di[17] = te[8] * this.halfDepth;
  99113. var wx = di[9];
  99114. var wy = di[10];
  99115. var wz = di[11];
  99116. var hx = di[12];
  99117. var hy = di[13];
  99118. var hz = di[14];
  99119. var dx = di[15];
  99120. var dy = di[16];
  99121. var dz = di[17];
  99122. var x = this.position.x;
  99123. var y = this.position.y;
  99124. var z = this.position.z;
  99125. var v = this.elements;
  99126. //v1
  99127. v[0] = x + wx + hx + dx;
  99128. v[1] = y + wy + hy + dy;
  99129. v[2] = z + wz + hz + dz;
  99130. //v2
  99131. v[3] = x + wx + hx - dx;
  99132. v[4] = y + wy + hy - dy;
  99133. v[5] = z + wz + hz - dz;
  99134. //v3
  99135. v[6] = x + wx - hx + dx;
  99136. v[7] = y + wy - hy + dy;
  99137. v[8] = z + wz - hz + dz;
  99138. //v4
  99139. v[9] = x + wx - hx - dx;
  99140. v[10] = y + wy - hy - dy;
  99141. v[11] = z + wz - hz - dz;
  99142. //v5
  99143. v[12] = x - wx + hx + dx;
  99144. v[13] = y - wy + hy + dy;
  99145. v[14] = z - wz + hz + dz;
  99146. //v6
  99147. v[15] = x - wx + hx - dx;
  99148. v[16] = y - wy + hy - dy;
  99149. v[17] = z - wz + hz - dz;
  99150. //v7
  99151. v[18] = x - wx - hx + dx;
  99152. v[19] = y - wy - hy + dy;
  99153. v[20] = z - wz - hz + dz;
  99154. //v8
  99155. v[21] = x - wx - hx - dx;
  99156. v[22] = y - wy - hy - dy;
  99157. v[23] = z - wz - hz - dz;
  99158. var w = di[9] < 0 ? -di[9] : di[9];
  99159. var h = di[10] < 0 ? -di[10] : di[10];
  99160. var d = di[11] < 0 ? -di[11] : di[11];
  99161. w = di[12] < 0 ? w - di[12] : w + di[12];
  99162. h = di[13] < 0 ? h - di[13] : h + di[13];
  99163. d = di[14] < 0 ? d - di[14] : d + di[14];
  99164. w = di[15] < 0 ? w - di[15] : w + di[15];
  99165. h = di[16] < 0 ? h - di[16] : h + di[16];
  99166. d = di[17] < 0 ? d - di[17] : d + di[17];
  99167. var p = OIMO.AABB_PROX;
  99168. this.aabb.set(
  99169. this.position.x - w - p, this.position.x + w + p,
  99170. this.position.y - h - p, this.position.y + h + p,
  99171. this.position.z - d - p, this.position.z + d + p
  99172. );
  99173. if (this.proxy != null) this.proxy.update();
  99174. };
  99175. /**
  99176. * A sphere shape.
  99177. * @author saharan
  99178. * @author lo-th
  99179. */
  99180. OIMO.SphereShape = function (config, radius) {
  99181. OIMO.Shape.call(this, config);
  99182. this.type = OIMO.SHAPE_SPHERE;
  99183. // The radius of the shape.
  99184. this.radius = radius;
  99185. };
  99186. OIMO.SphereShape.prototype = Object.create(OIMO.Shape.prototype);
  99187. OIMO.SphereShape.prototype.constructor = OIMO.SphereShape;
  99188. OIMO.SphereShape.prototype.calculateMassInfo = function (out) {
  99189. var mass = 1.333 * OIMO.PI * this.radius * this.radius * this.radius * this.density;
  99190. out.mass = mass;
  99191. var inertia = mass * this.radius * this.radius * 0.4;
  99192. out.inertia.set(inertia, 0, 0, 0, inertia, 0, 0, 0, inertia);
  99193. };
  99194. OIMO.SphereShape.prototype.updateProxy = function () {
  99195. var p = OIMO.AABB_PROX;
  99196. this.aabb.set(
  99197. this.position.x - this.radius - p, this.position.x + this.radius + p,
  99198. this.position.y - this.radius - p, this.position.y + this.radius + p,
  99199. this.position.z - this.radius - p, this.position.z + this.radius + p
  99200. );
  99201. if (this.proxy != null) this.proxy.update();
  99202. };
  99203. /**
  99204. * A cylinder shap.
  99205. * @author saharan
  99206. * @author lo-th
  99207. */
  99208. OIMO.CylinderShape = function (config, radius, height) {
  99209. OIMO.Shape.call(this, config);
  99210. this.type = OIMO.SHAPE_CYLINDER;
  99211. this.radius = radius;
  99212. this.height = height;
  99213. this.halfHeight = height * 0.5;
  99214. this.normalDirection = new OIMO.Vec3();
  99215. this.halfDirection = new OIMO.Vec3();
  99216. };
  99217. OIMO.CylinderShape.prototype = Object.create(OIMO.Shape.prototype);
  99218. OIMO.CylinderShape.prototype.constructor = OIMO.CylinderShape;
  99219. OIMO.CylinderShape.prototype.calculateMassInfo = function (out) {
  99220. var rsq = this.radius * this.radius;
  99221. var mass = OIMO.PI * rsq * this.height * this.density;
  99222. var inertiaXZ = ((0.25 * rsq) + (0.0833 * this.height * this.height)) * mass;
  99223. var inertiaY = 0.5 * rsq;
  99224. out.mass = mass;
  99225. out.inertia.set(inertiaXZ, 0, 0, 0, inertiaY, 0, 0, 0, inertiaXZ);
  99226. };
  99227. OIMO.CylinderShape.prototype.updateProxy = function () {
  99228. var te = this.rotation.elements;
  99229. var len, wx, hy, dz, xx, yy, zz, w, h, d, p;
  99230. xx = te[1] * te[1];
  99231. yy = te[4] * te[4];
  99232. zz = te[7] * te[7];
  99233. this.normalDirection.set(te[1], te[4], te[7]);
  99234. this.halfDirection.scale(this.normalDirection, this.halfHeight);
  99235. wx = 1 - xx;
  99236. len = OIMO.sqrt(wx * wx + xx * yy + xx * zz);
  99237. if (len > 0) len = this.radius / len;
  99238. wx *= len;
  99239. hy = 1 - yy;
  99240. len = OIMO.sqrt(yy * xx + hy * hy + yy * zz);
  99241. if (len > 0) len = this.radius / len;
  99242. hy *= len;
  99243. dz = 1 - zz;
  99244. len = OIMO.sqrt(zz * xx + zz * yy + dz * dz);
  99245. if (len > 0) len = this.radius / len;
  99246. dz *= len;
  99247. w = this.halfDirection.x < 0 ? -this.halfDirection.x : this.halfDirection.x;
  99248. h = this.halfDirection.y < 0 ? -this.halfDirection.y : this.halfDirection.y;
  99249. d = this.halfDirection.z < 0 ? -this.halfDirection.z : this.halfDirection.z;
  99250. w = wx < 0 ? w - wx : w + wx;
  99251. h = hy < 0 ? h - hy : h + hy;
  99252. d = dz < 0 ? d - dz : d + dz;
  99253. p = OIMO.AABB_PROX;
  99254. this.aabb.set(
  99255. this.position.x - w - p, this.position.x + w + p,
  99256. this.position.y - h - p, this.position.y + h + p,
  99257. this.position.z - d - p, this.position.z + d + p
  99258. );
  99259. if (this.proxy != null) this.proxy.update();
  99260. };
  99261. /**
  99262. * A tetra shape.
  99263. * @author xprogram
  99264. */
  99265. OIMO.TetraShape = function (config, p1, p2, p3, p4) {
  99266. OIMO.Shape.call(this, config);
  99267. this.type = OIMO.SHAPE_TETRA;
  99268. // Vertices and faces of tetra
  99269. this.verts = [p1, p2, p3, p4];
  99270. this.faces = [
  99271. mtri(0, 1, 2),
  99272. mtri(1, 2, 3),
  99273. mtri(2, 3, 4),
  99274. mtri(4, 0, 1),
  99275. ];
  99276. };
  99277. OIMO.TetraShape.prototype = Object.create(OIMO.Shape.prototype);
  99278. OIMO.TetraShape.prototype.constructor = OIMO.TetraShape;
  99279. OIMO.TetraShape.prototype.calculateMassInfo = function () {
  99280. // I guess you could calculate box mass and split it
  99281. // in half for the tetra...
  99282. };
  99283. OIMO.TetraShape.prototype.updateProxy = function () {
  99284. this.aabb.setFromPoints(this.verts);
  99285. if (this.proxy !== null)
  99286. this.proxy.update();
  99287. };
  99288. function mtri(a, b, c) {
  99289. return { a: a, b: b, c: c };
  99290. }
  99291. OIMO.CollisionDetector = function () {
  99292. this.flip = false;
  99293. };
  99294. OIMO.CollisionDetector.prototype = {
  99295. constructor: OIMO.CollisionDetector,
  99296. detectCollision: function (shape1, shape2, manifold) {
  99297. OIMO.Error("CollisionDetector", "Inheritance error.");
  99298. }
  99299. };
  99300. /**
  99301. * A collision detector which detects collisions between two boxes.
  99302. * @author saharan
  99303. */
  99304. OIMO.BoxBoxCollisionDetector = function () {
  99305. OIMO.CollisionDetector.call(this);
  99306. this.clipVertices1 = new OIMO_ARRAY_TYPE(24); // 8 vertices x,y,z
  99307. this.clipVertices2 = new OIMO_ARRAY_TYPE(24);
  99308. this.used = new OIMO_ARRAY_TYPE(8);
  99309. this.INF = 1 / 0;
  99310. };
  99311. OIMO.BoxBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  99312. OIMO.BoxBoxCollisionDetector.prototype.constructor = OIMO.BoxBoxCollisionDetector;
  99313. OIMO.BoxBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  99314. // What you are doing
  99315. // · I to prepare a separate axis of the fifteen
  99316. //-Six in each of three normal vectors of the xyz direction of the box both
  99317. // · Remaining nine 3x3 a vector perpendicular to the side of the box 2 and the side of the box 1
  99318. // · Calculate the depth to the separation axis
  99319. // Calculates the distance using the inner product and put the amount of embedment
  99320. // · However a vertical separation axis and side to weight a little to avoid vibration
  99321. // And end when there is a separate axis that is remote even one
  99322. // · I look for separation axis with little to dent most
  99323. // Men and if separation axis of the first six - end collision
  99324. // Heng If it separate axis of nine other - side collision
  99325. // Heng - case of a side collision
  99326. // · Find points of two sides on which you made ​​the separation axis
  99327. // Calculates the point of closest approach of a straight line consisting of separate axis points obtained, and the collision point
  99328. //-Surface - the case of the plane crash
  99329. //-Box A, box B and the other a box of better made ​​a separate axis
  99330. // • 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
  99331. // When viewed from the front surface A, and the cut part exceeding the area of the surface A is a surface B
  99332. //-Plane B becomes the 3-8 triangle, I a candidate for the collision point the vertex of surface B
  99333. // • If more than one candidate 5 exists, scraping up to four
  99334. // For potential collision points of all, to examine the distance between the surface A
  99335. // • If you were on the inside surface of A, and the collision point
  99336. var b1;
  99337. var b2;
  99338. if (shape1.id < shape2.id) {
  99339. b1 = (shape1);
  99340. b2 = (shape2);
  99341. } else {
  99342. b1 = (shape2);
  99343. b2 = (shape1);
  99344. }
  99345. var V1 = b1.elements;
  99346. var V2 = b2.elements;
  99347. var D1 = b1.dimentions;
  99348. var D2 = b2.dimentions;
  99349. var p1 = b1.position;
  99350. var p2 = b2.position;
  99351. var p1x = p1.x;
  99352. var p1y = p1.y;
  99353. var p1z = p1.z;
  99354. var p2x = p2.x;
  99355. var p2y = p2.y;
  99356. var p2z = p2.z;
  99357. // diff
  99358. var dx = p2x - p1x;
  99359. var dy = p2y - p1y;
  99360. var dz = p2z - p1z;
  99361. // distance
  99362. var w1 = b1.halfWidth;
  99363. var h1 = b1.halfHeight;
  99364. var d1 = b1.halfDepth;
  99365. var w2 = b2.halfWidth;
  99366. var h2 = b2.halfHeight;
  99367. var d2 = b2.halfDepth;
  99368. // direction
  99369. // ----------------------------
  99370. // 15 separating axes
  99371. // 1~6: face
  99372. // 7~f: edge
  99373. // http://marupeke296.com/COL_3D_No13_OBBvsOBB.html
  99374. // ----------------------------
  99375. var a1x = D1[0];
  99376. var a1y = D1[1];
  99377. var a1z = D1[2];
  99378. var a2x = D1[3];
  99379. var a2y = D1[4];
  99380. var a2z = D1[5];
  99381. var a3x = D1[6];
  99382. var a3y = D1[7];
  99383. var a3z = D1[8];
  99384. var d1x = D1[9];
  99385. var d1y = D1[10];
  99386. var d1z = D1[11];
  99387. var d2x = D1[12];
  99388. var d2y = D1[13];
  99389. var d2z = D1[14];
  99390. var d3x = D1[15];
  99391. var d3y = D1[16];
  99392. var d3z = D1[17];
  99393. var a4x = D2[0];
  99394. var a4y = D2[1];
  99395. var a4z = D2[2];
  99396. var a5x = D2[3];
  99397. var a5y = D2[4];
  99398. var a5z = D2[5];
  99399. var a6x = D2[6];
  99400. var a6y = D2[7];
  99401. var a6z = D2[8];
  99402. var d4x = D2[9];
  99403. var d4y = D2[10];
  99404. var d4z = D2[11];
  99405. var d5x = D2[12];
  99406. var d5y = D2[13];
  99407. var d5z = D2[14];
  99408. var d6x = D2[15];
  99409. var d6y = D2[16];
  99410. var d6z = D2[17];
  99411. var a7x = a1y * a4z - a1z * a4y;
  99412. var a7y = a1z * a4x - a1x * a4z;
  99413. var a7z = a1x * a4y - a1y * a4x;
  99414. var a8x = a1y * a5z - a1z * a5y;
  99415. var a8y = a1z * a5x - a1x * a5z;
  99416. var a8z = a1x * a5y - a1y * a5x;
  99417. var a9x = a1y * a6z - a1z * a6y;
  99418. var a9y = a1z * a6x - a1x * a6z;
  99419. var a9z = a1x * a6y - a1y * a6x;
  99420. var aax = a2y * a4z - a2z * a4y;
  99421. var aay = a2z * a4x - a2x * a4z;
  99422. var aaz = a2x * a4y - a2y * a4x;
  99423. var abx = a2y * a5z - a2z * a5y;
  99424. var aby = a2z * a5x - a2x * a5z;
  99425. var abz = a2x * a5y - a2y * a5x;
  99426. var acx = a2y * a6z - a2z * a6y;
  99427. var acy = a2z * a6x - a2x * a6z;
  99428. var acz = a2x * a6y - a2y * a6x;
  99429. var adx = a3y * a4z - a3z * a4y;
  99430. var ady = a3z * a4x - a3x * a4z;
  99431. var adz = a3x * a4y - a3y * a4x;
  99432. var aex = a3y * a5z - a3z * a5y;
  99433. var aey = a3z * a5x - a3x * a5z;
  99434. var aez = a3x * a5y - a3y * a5x;
  99435. var afx = a3y * a6z - a3z * a6y;
  99436. var afy = a3z * a6x - a3x * a6z;
  99437. var afz = a3x * a6y - a3y * a6x;
  99438. // right or left flags
  99439. var right1;
  99440. var right2;
  99441. var right3;
  99442. var right4;
  99443. var right5;
  99444. var right6;
  99445. var right7;
  99446. var right8;
  99447. var right9;
  99448. var righta;
  99449. var rightb;
  99450. var rightc;
  99451. var rightd;
  99452. var righte;
  99453. var rightf;
  99454. // overlapping distances
  99455. var overlap1;
  99456. var overlap2;
  99457. var overlap3;
  99458. var overlap4;
  99459. var overlap5;
  99460. var overlap6;
  99461. var overlap7;
  99462. var overlap8;
  99463. var overlap9;
  99464. var overlapa;
  99465. var overlapb;
  99466. var overlapc;
  99467. var overlapd;
  99468. var overlape;
  99469. var overlapf;
  99470. // invalid flags
  99471. var invalid7 = false;
  99472. var invalid8 = false;
  99473. var invalid9 = false;
  99474. var invalida = false;
  99475. var invalidb = false;
  99476. var invalidc = false;
  99477. var invalidd = false;
  99478. var invalide = false;
  99479. var invalidf = false;
  99480. // temporary variables
  99481. var len;
  99482. var len1;
  99483. var len2;
  99484. var dot1;
  99485. var dot2;
  99486. var dot3;
  99487. // try axis 1
  99488. len = a1x * dx + a1y * dy + a1z * dz;
  99489. right1 = len > 0;
  99490. if (!right1) len = -len;
  99491. len1 = w1;
  99492. dot1 = a1x * a4x + a1y * a4y + a1z * a4z;
  99493. dot2 = a1x * a5x + a1y * a5y + a1z * a5z;
  99494. dot3 = a1x * a6x + a1y * a6y + a1z * a6z;
  99495. if (dot1 < 0) dot1 = -dot1;
  99496. if (dot2 < 0) dot2 = -dot2;
  99497. if (dot3 < 0) dot3 = -dot3;
  99498. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  99499. overlap1 = len - len1 - len2;
  99500. if (overlap1 > 0) return;
  99501. // try axis 2
  99502. len = a2x * dx + a2y * dy + a2z * dz;
  99503. right2 = len > 0;
  99504. if (!right2) len = -len;
  99505. len1 = h1;
  99506. dot1 = a2x * a4x + a2y * a4y + a2z * a4z;
  99507. dot2 = a2x * a5x + a2y * a5y + a2z * a5z;
  99508. dot3 = a2x * a6x + a2y * a6y + a2z * a6z;
  99509. if (dot1 < 0) dot1 = -dot1;
  99510. if (dot2 < 0) dot2 = -dot2;
  99511. if (dot3 < 0) dot3 = -dot3;
  99512. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  99513. overlap2 = len - len1 - len2;
  99514. if (overlap2 > 0) return;
  99515. // try axis 3
  99516. len = a3x * dx + a3y * dy + a3z * dz;
  99517. right3 = len > 0;
  99518. if (!right3) len = -len;
  99519. len1 = d1;
  99520. dot1 = a3x * a4x + a3y * a4y + a3z * a4z;
  99521. dot2 = a3x * a5x + a3y * a5y + a3z * a5z;
  99522. dot3 = a3x * a6x + a3y * a6y + a3z * a6z;
  99523. if (dot1 < 0) dot1 = -dot1;
  99524. if (dot2 < 0) dot2 = -dot2;
  99525. if (dot3 < 0) dot3 = -dot3;
  99526. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  99527. overlap3 = len - len1 - len2;
  99528. if (overlap3 > 0) return;
  99529. // try axis 4
  99530. len = a4x * dx + a4y * dy + a4z * dz;
  99531. right4 = len > 0;
  99532. if (!right4) len = -len;
  99533. dot1 = a4x * a1x + a4y * a1y + a4z * a1z;
  99534. dot2 = a4x * a2x + a4y * a2y + a4z * a2z;
  99535. dot3 = a4x * a3x + a4y * a3y + a4z * a3z;
  99536. if (dot1 < 0) dot1 = -dot1;
  99537. if (dot2 < 0) dot2 = -dot2;
  99538. if (dot3 < 0) dot3 = -dot3;
  99539. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  99540. len2 = w2;
  99541. overlap4 = (len - len1 - len2) * 1.0;
  99542. if (overlap4 > 0) return;
  99543. // try axis 5
  99544. len = a5x * dx + a5y * dy + a5z * dz;
  99545. right5 = len > 0;
  99546. if (!right5) len = -len;
  99547. dot1 = a5x * a1x + a5y * a1y + a5z * a1z;
  99548. dot2 = a5x * a2x + a5y * a2y + a5z * a2z;
  99549. dot3 = a5x * a3x + a5y * a3y + a5z * a3z;
  99550. if (dot1 < 0) dot1 = -dot1;
  99551. if (dot2 < 0) dot2 = -dot2;
  99552. if (dot3 < 0) dot3 = -dot3;
  99553. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  99554. len2 = h2;
  99555. overlap5 = (len - len1 - len2) * 1.0;
  99556. if (overlap5 > 0) return;
  99557. // try axis 6
  99558. len = a6x * dx + a6y * dy + a6z * dz;
  99559. right6 = len > 0;
  99560. if (!right6) len = -len;
  99561. dot1 = a6x * a1x + a6y * a1y + a6z * a1z;
  99562. dot2 = a6x * a2x + a6y * a2y + a6z * a2z;
  99563. dot3 = a6x * a3x + a6y * a3y + a6z * a3z;
  99564. if (dot1 < 0) dot1 = -dot1;
  99565. if (dot2 < 0) dot2 = -dot2;
  99566. if (dot3 < 0) dot3 = -dot3;
  99567. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  99568. len2 = d2;
  99569. overlap6 = (len - len1 - len2) * 1.0;
  99570. if (overlap6 > 0) return;
  99571. // try axis 7
  99572. len = a7x * a7x + a7y * a7y + a7z * a7z;
  99573. if (len > 1e-5) {
  99574. len = 1 / OIMO.sqrt(len);
  99575. a7x *= len;
  99576. a7y *= len;
  99577. a7z *= len;
  99578. len = a7x * dx + a7y * dy + a7z * dz;
  99579. right7 = len > 0;
  99580. if (!right7) len = -len;
  99581. dot1 = a7x * a2x + a7y * a2y + a7z * a2z;
  99582. dot2 = a7x * a3x + a7y * a3y + a7z * a3z;
  99583. if (dot1 < 0) dot1 = -dot1;
  99584. if (dot2 < 0) dot2 = -dot2;
  99585. len1 = dot1 * h1 + dot2 * d1;
  99586. dot1 = a7x * a5x + a7y * a5y + a7z * a5z;
  99587. dot2 = a7x * a6x + a7y * a6y + a7z * a6z;
  99588. if (dot1 < 0) dot1 = -dot1;
  99589. if (dot2 < 0) dot2 = -dot2;
  99590. len2 = dot1 * h2 + dot2 * d2;
  99591. overlap7 = len - len1 - len2;
  99592. if (overlap7 > 0) return;
  99593. } else {
  99594. right7 = false;
  99595. overlap7 = 0;
  99596. invalid7 = true;
  99597. }
  99598. // try axis 8
  99599. len = a8x * a8x + a8y * a8y + a8z * a8z;
  99600. if (len > 1e-5) {
  99601. len = 1 / OIMO.sqrt(len);
  99602. a8x *= len;
  99603. a8y *= len;
  99604. a8z *= len;
  99605. len = a8x * dx + a8y * dy + a8z * dz;
  99606. right8 = len > 0;
  99607. if (!right8) len = -len;
  99608. dot1 = a8x * a2x + a8y * a2y + a8z * a2z;
  99609. dot2 = a8x * a3x + a8y * a3y + a8z * a3z;
  99610. if (dot1 < 0) dot1 = -dot1;
  99611. if (dot2 < 0) dot2 = -dot2;
  99612. len1 = dot1 * h1 + dot2 * d1;
  99613. dot1 = a8x * a4x + a8y * a4y + a8z * a4z;
  99614. dot2 = a8x * a6x + a8y * a6y + a8z * a6z;
  99615. if (dot1 < 0) dot1 = -dot1;
  99616. if (dot2 < 0) dot2 = -dot2;
  99617. len2 = dot1 * w2 + dot2 * d2;
  99618. overlap8 = len - len1 - len2;
  99619. if (overlap8 > 0) return;
  99620. } else {
  99621. right8 = false;
  99622. overlap8 = 0;
  99623. invalid8 = true;
  99624. }
  99625. // try axis 9
  99626. len = a9x * a9x + a9y * a9y + a9z * a9z;
  99627. if (len > 1e-5) {
  99628. len = 1 / OIMO.sqrt(len);
  99629. a9x *= len;
  99630. a9y *= len;
  99631. a9z *= len;
  99632. len = a9x * dx + a9y * dy + a9z * dz;
  99633. right9 = len > 0;
  99634. if (!right9) len = -len;
  99635. dot1 = a9x * a2x + a9y * a2y + a9z * a2z;
  99636. dot2 = a9x * a3x + a9y * a3y + a9z * a3z;
  99637. if (dot1 < 0) dot1 = -dot1;
  99638. if (dot2 < 0) dot2 = -dot2;
  99639. len1 = dot1 * h1 + dot2 * d1;
  99640. dot1 = a9x * a4x + a9y * a4y + a9z * a4z;
  99641. dot2 = a9x * a5x + a9y * a5y + a9z * a5z;
  99642. if (dot1 < 0) dot1 = -dot1;
  99643. if (dot2 < 0) dot2 = -dot2;
  99644. len2 = dot1 * w2 + dot2 * h2;
  99645. overlap9 = len - len1 - len2;
  99646. if (overlap9 > 0) return;
  99647. } else {
  99648. right9 = false;
  99649. overlap9 = 0;
  99650. invalid9 = true;
  99651. }
  99652. // try axis 10
  99653. len = aax * aax + aay * aay + aaz * aaz;
  99654. if (len > 1e-5) {
  99655. len = 1 / OIMO.sqrt(len);
  99656. aax *= len;
  99657. aay *= len;
  99658. aaz *= len;
  99659. len = aax * dx + aay * dy + aaz * dz;
  99660. righta = len > 0;
  99661. if (!righta) len = -len;
  99662. dot1 = aax * a1x + aay * a1y + aaz * a1z;
  99663. dot2 = aax * a3x + aay * a3y + aaz * a3z;
  99664. if (dot1 < 0) dot1 = -dot1;
  99665. if (dot2 < 0) dot2 = -dot2;
  99666. len1 = dot1 * w1 + dot2 * d1;
  99667. dot1 = aax * a5x + aay * a5y + aaz * a5z;
  99668. dot2 = aax * a6x + aay * a6y + aaz * a6z;
  99669. if (dot1 < 0) dot1 = -dot1;
  99670. if (dot2 < 0) dot2 = -dot2;
  99671. len2 = dot1 * h2 + dot2 * d2;
  99672. overlapa = len - len1 - len2;
  99673. if (overlapa > 0) return;
  99674. } else {
  99675. righta = false;
  99676. overlapa = 0;
  99677. invalida = true;
  99678. }
  99679. // try axis 11
  99680. len = abx * abx + aby * aby + abz * abz;
  99681. if (len > 1e-5) {
  99682. len = 1 / OIMO.sqrt(len);
  99683. abx *= len;
  99684. aby *= len;
  99685. abz *= len;
  99686. len = abx * dx + aby * dy + abz * dz;
  99687. rightb = len > 0;
  99688. if (!rightb) len = -len;
  99689. dot1 = abx * a1x + aby * a1y + abz * a1z;
  99690. dot2 = abx * a3x + aby * a3y + abz * a3z;
  99691. if (dot1 < 0) dot1 = -dot1;
  99692. if (dot2 < 0) dot2 = -dot2;
  99693. len1 = dot1 * w1 + dot2 * d1;
  99694. dot1 = abx * a4x + aby * a4y + abz * a4z;
  99695. dot2 = abx * a6x + aby * a6y + abz * a6z;
  99696. if (dot1 < 0) dot1 = -dot1;
  99697. if (dot2 < 0) dot2 = -dot2;
  99698. len2 = dot1 * w2 + dot2 * d2;
  99699. overlapb = len - len1 - len2;
  99700. if (overlapb > 0) return;
  99701. } else {
  99702. rightb = false;
  99703. overlapb = 0;
  99704. invalidb = true;
  99705. }
  99706. // try axis 12
  99707. len = acx * acx + acy * acy + acz * acz;
  99708. if (len > 1e-5) {
  99709. len = 1 / OIMO.sqrt(len);
  99710. acx *= len;
  99711. acy *= len;
  99712. acz *= len;
  99713. len = acx * dx + acy * dy + acz * dz;
  99714. rightc = len > 0;
  99715. if (!rightc) len = -len;
  99716. dot1 = acx * a1x + acy * a1y + acz * a1z;
  99717. dot2 = acx * a3x + acy * a3y + acz * a3z;
  99718. if (dot1 < 0) dot1 = -dot1;
  99719. if (dot2 < 0) dot2 = -dot2;
  99720. len1 = dot1 * w1 + dot2 * d1;
  99721. dot1 = acx * a4x + acy * a4y + acz * a4z;
  99722. dot2 = acx * a5x + acy * a5y + acz * a5z;
  99723. if (dot1 < 0) dot1 = -dot1;
  99724. if (dot2 < 0) dot2 = -dot2;
  99725. len2 = dot1 * w2 + dot2 * h2;
  99726. overlapc = len - len1 - len2;
  99727. if (overlapc > 0) return;
  99728. } else {
  99729. rightc = false;
  99730. overlapc = 0;
  99731. invalidc = true;
  99732. }
  99733. // try axis 13
  99734. len = adx * adx + ady * ady + adz * adz;
  99735. if (len > 1e-5) {
  99736. len = 1 / OIMO.sqrt(len);
  99737. adx *= len;
  99738. ady *= len;
  99739. adz *= len;
  99740. len = adx * dx + ady * dy + adz * dz;
  99741. rightd = len > 0;
  99742. if (!rightd) len = -len;
  99743. dot1 = adx * a1x + ady * a1y + adz * a1z;
  99744. dot2 = adx * a2x + ady * a2y + adz * a2z;
  99745. if (dot1 < 0) dot1 = -dot1;
  99746. if (dot2 < 0) dot2 = -dot2;
  99747. len1 = dot1 * w1 + dot2 * h1;
  99748. dot1 = adx * a5x + ady * a5y + adz * a5z;
  99749. dot2 = adx * a6x + ady * a6y + adz * a6z;
  99750. if (dot1 < 0) dot1 = -dot1;
  99751. if (dot2 < 0) dot2 = -dot2;
  99752. len2 = dot1 * h2 + dot2 * d2;
  99753. overlapd = len - len1 - len2;
  99754. if (overlapd > 0) return;
  99755. } else {
  99756. rightd = false;
  99757. overlapd = 0;
  99758. invalidd = true;
  99759. }
  99760. // try axis 14
  99761. len = aex * aex + aey * aey + aez * aez;
  99762. if (len > 1e-5) {
  99763. len = 1 / OIMO.sqrt(len);
  99764. aex *= len;
  99765. aey *= len;
  99766. aez *= len;
  99767. len = aex * dx + aey * dy + aez * dz;
  99768. righte = len > 0;
  99769. if (!righte) len = -len;
  99770. dot1 = aex * a1x + aey * a1y + aez * a1z;
  99771. dot2 = aex * a2x + aey * a2y + aez * a2z;
  99772. if (dot1 < 0) dot1 = -dot1;
  99773. if (dot2 < 0) dot2 = -dot2;
  99774. len1 = dot1 * w1 + dot2 * h1;
  99775. dot1 = aex * a4x + aey * a4y + aez * a4z;
  99776. dot2 = aex * a6x + aey * a6y + aez * a6z;
  99777. if (dot1 < 0) dot1 = -dot1;
  99778. if (dot2 < 0) dot2 = -dot2;
  99779. len2 = dot1 * w2 + dot2 * d2;
  99780. overlape = len - len1 - len2;
  99781. if (overlape > 0) return;
  99782. } else {
  99783. righte = false;
  99784. overlape = 0;
  99785. invalide = true;
  99786. }
  99787. // try axis 15
  99788. len = afx * afx + afy * afy + afz * afz;
  99789. if (len > 1e-5) {
  99790. len = 1 / OIMO.sqrt(len);
  99791. afx *= len;
  99792. afy *= len;
  99793. afz *= len;
  99794. len = afx * dx + afy * dy + afz * dz;
  99795. rightf = len > 0;
  99796. if (!rightf) len = -len;
  99797. dot1 = afx * a1x + afy * a1y + afz * a1z;
  99798. dot2 = afx * a2x + afy * a2y + afz * a2z;
  99799. if (dot1 < 0) dot1 = -dot1;
  99800. if (dot2 < 0) dot2 = -dot2;
  99801. len1 = dot1 * w1 + dot2 * h1;
  99802. dot1 = afx * a4x + afy * a4y + afz * a4z;
  99803. dot2 = afx * a5x + afy * a5y + afz * a5z;
  99804. if (dot1 < 0) dot1 = -dot1;
  99805. if (dot2 < 0) dot2 = -dot2;
  99806. len2 = dot1 * w2 + dot2 * h2;
  99807. overlapf = len - len1 - len2;
  99808. if (overlapf > 0) return;
  99809. } else {
  99810. rightf = false;
  99811. overlapf = 0;
  99812. invalidf = true;
  99813. }
  99814. // boxes are overlapping
  99815. var depth = overlap1;
  99816. var depth2 = overlap1;
  99817. var minIndex = 0;
  99818. var right = right1;
  99819. if (overlap2 > depth2) {
  99820. depth = overlap2;
  99821. depth2 = overlap2;
  99822. minIndex = 1;
  99823. right = right2;
  99824. }
  99825. if (overlap3 > depth2) {
  99826. depth = overlap3;
  99827. depth2 = overlap3;
  99828. minIndex = 2;
  99829. right = right3;
  99830. }
  99831. if (overlap4 > depth2) {
  99832. depth = overlap4;
  99833. depth2 = overlap4;
  99834. minIndex = 3;
  99835. right = right4;
  99836. }
  99837. if (overlap5 > depth2) {
  99838. depth = overlap5;
  99839. depth2 = overlap5;
  99840. minIndex = 4;
  99841. right = right5;
  99842. }
  99843. if (overlap6 > depth2) {
  99844. depth = overlap6;
  99845. depth2 = overlap6;
  99846. minIndex = 5;
  99847. right = right6;
  99848. }
  99849. if (overlap7 - 0.01 > depth2 && !invalid7) {
  99850. depth = overlap7;
  99851. depth2 = overlap7 - 0.01;
  99852. minIndex = 6;
  99853. right = right7;
  99854. }
  99855. if (overlap8 - 0.01 > depth2 && !invalid8) {
  99856. depth = overlap8;
  99857. depth2 = overlap8 - 0.01;
  99858. minIndex = 7;
  99859. right = right8;
  99860. }
  99861. if (overlap9 - 0.01 > depth2 && !invalid9) {
  99862. depth = overlap9;
  99863. depth2 = overlap9 - 0.01;
  99864. minIndex = 8;
  99865. right = right9;
  99866. }
  99867. if (overlapa - 0.01 > depth2 && !invalida) {
  99868. depth = overlapa;
  99869. depth2 = overlapa - 0.01;
  99870. minIndex = 9;
  99871. right = righta;
  99872. }
  99873. if (overlapb - 0.01 > depth2 && !invalidb) {
  99874. depth = overlapb;
  99875. depth2 = overlapb - 0.01;
  99876. minIndex = 10;
  99877. right = rightb;
  99878. }
  99879. if (overlapc - 0.01 > depth2 && !invalidc) {
  99880. depth = overlapc;
  99881. depth2 = overlapc - 0.01;
  99882. minIndex = 11;
  99883. right = rightc;
  99884. }
  99885. if (overlapd - 0.01 > depth2 && !invalidd) {
  99886. depth = overlapd;
  99887. depth2 = overlapd - 0.01;
  99888. minIndex = 12;
  99889. right = rightd;
  99890. }
  99891. if (overlape - 0.01 > depth2 && !invalide) {
  99892. depth = overlape;
  99893. depth2 = overlape - 0.01;
  99894. minIndex = 13;
  99895. right = righte;
  99896. }
  99897. if (overlapf - 0.01 > depth2 && !invalidf) {
  99898. depth = overlapf;
  99899. minIndex = 14;
  99900. right = rightf;
  99901. }
  99902. // normal
  99903. var nx = 0;
  99904. var ny = 0;
  99905. var nz = 0;
  99906. // edge line or face side normal
  99907. var n1x = 0;
  99908. var n1y = 0;
  99909. var n1z = 0;
  99910. var n2x = 0;
  99911. var n2y = 0;
  99912. var n2z = 0;
  99913. // center of current face
  99914. var cx = 0;
  99915. var cy = 0;
  99916. var cz = 0;
  99917. // face side
  99918. var s1x = 0;
  99919. var s1y = 0;
  99920. var s1z = 0;
  99921. var s2x = 0;
  99922. var s2y = 0;
  99923. var s2z = 0;
  99924. // swap b1 b2
  99925. var swap = false;
  99926. //_______________________________________
  99927. if (minIndex == 0) {// b1.x * b2
  99928. if (right) {
  99929. cx = p1x + d1x; cy = p1y + d1y; cz = p1z + d1z;
  99930. nx = a1x; ny = a1y; nz = a1z;
  99931. } else {
  99932. cx = p1x - d1x; cy = p1y - d1y; cz = p1z - d1z;
  99933. nx = -a1x; ny = -a1y; nz = -a1z;
  99934. }
  99935. s1x = d2x; s1y = d2y; s1z = d2z;
  99936. n1x = -a2x; n1y = -a2y; n1z = -a2z;
  99937. s2x = d3x; s2y = d3y; s2z = d3z;
  99938. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  99939. }
  99940. else if (minIndex == 1) {// b1.y * b2
  99941. if (right) {
  99942. cx = p1x + d2x; cy = p1y + d2y; cz = p1z + d2z;
  99943. nx = a2x; ny = a2y; nz = a2z;
  99944. } else {
  99945. cx = p1x - d2x; cy = p1y - d2y; cz = p1z - d2z;
  99946. nx = -a2x; ny = -a2y; nz = -a2z;
  99947. }
  99948. s1x = d1x; s1y = d1y; s1z = d1z;
  99949. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  99950. s2x = d3x; s2y = d3y; s2z = d3z;
  99951. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  99952. }
  99953. else if (minIndex == 2) {// b1.z * b2
  99954. if (right) {
  99955. cx = p1x + d3x; cy = p1y + d3y; cz = p1z + d3z;
  99956. nx = a3x; ny = a3y; nz = a3z;
  99957. } else {
  99958. cx = p1x - d3x; cy = p1y - d3y; cz = p1z - d3z;
  99959. nx = -a3x; ny = -a3y; nz = -a3z;
  99960. }
  99961. s1x = d1x; s1y = d1y; s1z = d1z;
  99962. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  99963. s2x = d2x; s2y = d2y; s2z = d2z;
  99964. n2x = -a2x; n2y = -a2y; n2z = -a2z;
  99965. }
  99966. else if (minIndex == 3) {// b2.x * b1
  99967. swap = true;
  99968. if (!right) {
  99969. cx = p2x + d4x; cy = p2y + d4y; cz = p2z + d4z;
  99970. nx = a4x; ny = a4y; nz = a4z;
  99971. } else {
  99972. cx = p2x - d4x; cy = p2y - d4y; cz = p2z - d4z;
  99973. nx = -a4x; ny = -a4y; nz = -a4z;
  99974. }
  99975. s1x = d5x; s1y = d5y; s1z = d5z;
  99976. n1x = -a5x; n1y = -a5y; n1z = -a5z;
  99977. s2x = d6x; s2y = d6y; s2z = d6z;
  99978. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  99979. }
  99980. else if (minIndex == 4) {// b2.y * b1
  99981. swap = true;
  99982. if (!right) {
  99983. cx = p2x + d5x; cy = p2y + d5y; cz = p2z + d5z;
  99984. nx = a5x; ny = a5y; nz = a5z;
  99985. } else {
  99986. cx = p2x - d5x; cy = p2y - d5y; cz = p2z - d5z;
  99987. nx = -a5x; ny = -a5y; nz = -a5z;
  99988. }
  99989. s1x = d4x; s1y = d4y; s1z = d4z;
  99990. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  99991. s2x = d6x; s2y = d6y; s2z = d6z;
  99992. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  99993. }
  99994. else if (minIndex == 5) {// b2.z * b1
  99995. swap = true;
  99996. if (!right) {
  99997. cx = p2x + d6x; cy = p2y + d6y; cz = p2z + d6z;
  99998. nx = a6x; ny = a6y; nz = a6z;
  99999. } else {
  100000. cx = p2x - d6x; cy = p2y - d6y; cz = p2z - d6z;
  100001. nx = -a6x; ny = -a6y; nz = -a6z;
  100002. }
  100003. s1x = d4x; s1y = d4y; s1z = d4z;
  100004. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  100005. s2x = d5x; s2y = d5y; s2z = d5z;
  100006. n2x = -a5x; n2y = -a5y; n2z = -a5z;
  100007. }
  100008. else if (minIndex == 6) {// b1.x * b2.x
  100009. nx = a7x; ny = a7y; nz = a7z;
  100010. n1x = a1x; n1y = a1y; n1z = a1z;
  100011. n2x = a4x; n2y = a4y; n2z = a4z;
  100012. }
  100013. else if (minIndex == 7) {// b1.x * b2.y
  100014. nx = a8x; ny = a8y; nz = a8z;
  100015. n1x = a1x; n1y = a1y; n1z = a1z;
  100016. n2x = a5x; n2y = a5y; n2z = a5z;
  100017. }
  100018. else if (minIndex == 8) {// b1.x * b2.z
  100019. nx = a9x; ny = a9y; nz = a9z;
  100020. n1x = a1x; n1y = a1y; n1z = a1z;
  100021. n2x = a6x; n2y = a6y; n2z = a6z;
  100022. }
  100023. else if (minIndex == 9) {// b1.y * b2.x
  100024. nx = aax; ny = aay; nz = aaz;
  100025. n1x = a2x; n1y = a2y; n1z = a2z;
  100026. n2x = a4x; n2y = a4y; n2z = a4z
  100027. }
  100028. else if (minIndex == 10) {// b1.y * b2.y
  100029. nx = abx; ny = aby; nz = abz;
  100030. n1x = a2x; n1y = a2y; n1z = a2z;
  100031. n2x = a5x; n2y = a5y; n2z = a5z;
  100032. }
  100033. else if (minIndex == 11) {// b1.y * b2.z
  100034. nx = acx; ny = acy; nz = acz;
  100035. n1x = a2x; n1y = a2y; n1z = a2z;
  100036. n2x = a6x; n2y = a6y; n2z = a6z;
  100037. }
  100038. else if (minIndex == 12) {// b1.z * b2.x
  100039. nx = adx; ny = ady; nz = adz;
  100040. n1x = a3x; n1y = a3y; n1z = a3z;
  100041. n2x = a4x; n2y = a4y; n2z = a4z;
  100042. }
  100043. else if (minIndex == 13) {// b1.z * b2.y
  100044. nx = aex; ny = aey; nz = aez;
  100045. n1x = a3x; n1y = a3y; n1z = a3z;
  100046. n2x = a5x; n2y = a5y; n2z = a5z;
  100047. }
  100048. else if (minIndex == 14) {// b1.z * b2.z
  100049. nx = afx; ny = afy; nz = afz;
  100050. n1x = a3x; n1y = a3y; n1z = a3z;
  100051. n2x = a6x; n2y = a6y; n2z = a6z;
  100052. }
  100053. //__________________________________________
  100054. var v;
  100055. if (minIndex > 5) {
  100056. if (!right) {
  100057. nx = -nx; ny = -ny; nz = -nz;
  100058. }
  100059. var distance;
  100060. var maxDistance;
  100061. var vx;
  100062. var vy;
  100063. var vz;
  100064. var v1x;
  100065. var v1y;
  100066. var v1z;
  100067. var v2x;
  100068. var v2y;
  100069. var v2z;
  100070. //vertex1;
  100071. v1x = V1[0]; v1y = V1[1]; v1z = V1[2];
  100072. maxDistance = nx * v1x + ny * v1y + nz * v1z;
  100073. //vertex2;
  100074. vx = V1[3]; vy = V1[4]; vz = V1[5];
  100075. distance = nx * vx + ny * vy + nz * vz;
  100076. if (distance > maxDistance) {
  100077. maxDistance = distance;
  100078. v1x = vx; v1y = vy; v1z = vz;
  100079. }
  100080. //vertex3;
  100081. vx = V1[6]; vy = V1[7]; vz = V1[8];
  100082. distance = nx * vx + ny * vy + nz * vz;
  100083. if (distance > maxDistance) {
  100084. maxDistance = distance;
  100085. v1x = vx; v1y = vy; v1z = vz;
  100086. }
  100087. //vertex4;
  100088. vx = V1[9]; vy = V1[10]; vz = V1[11];
  100089. distance = nx * vx + ny * vy + nz * vz;
  100090. if (distance > maxDistance) {
  100091. maxDistance = distance;
  100092. v1x = vx; v1y = vy; v1z = vz;
  100093. }
  100094. //vertex5;
  100095. vx = V1[12]; vy = V1[13]; vz = V1[14];
  100096. distance = nx * vx + ny * vy + nz * vz;
  100097. if (distance > maxDistance) {
  100098. maxDistance = distance;
  100099. v1x = vx; v1y = vy; v1z = vz;
  100100. }
  100101. //vertex6;
  100102. vx = V1[15]; vy = V1[16]; vz = V1[17];
  100103. distance = nx * vx + ny * vy + nz * vz;
  100104. if (distance > maxDistance) {
  100105. maxDistance = distance;
  100106. v1x = vx; v1y = vy; v1z = vz;
  100107. }
  100108. //vertex7;
  100109. vx = V1[18]; vy = V1[19]; vz = V1[20];
  100110. distance = nx * vx + ny * vy + nz * vz;
  100111. if (distance > maxDistance) {
  100112. maxDistance = distance;
  100113. v1x = vx; v1y = vy; v1z = vz;
  100114. }
  100115. //vertex8;
  100116. vx = V1[21]; vy = V1[22]; vz = V1[23];
  100117. distance = nx * vx + ny * vy + nz * vz;
  100118. if (distance > maxDistance) {
  100119. maxDistance = distance;
  100120. v1x = vx; v1y = vy; v1z = vz;
  100121. }
  100122. //vertex1;
  100123. v2x = V2[0]; v2y = V2[1]; v2z = V2[2];
  100124. maxDistance = nx * v2x + ny * v2y + nz * v2z;
  100125. //vertex2;
  100126. vx = V2[3]; vy = V2[4]; vz = V2[5];
  100127. distance = nx * vx + ny * vy + nz * vz;
  100128. if (distance < maxDistance) {
  100129. maxDistance = distance;
  100130. v2x = vx; v2y = vy; v2z = vz;
  100131. }
  100132. //vertex3;
  100133. vx = V2[6]; vy = V2[7]; vz = V2[8];
  100134. distance = nx * vx + ny * vy + nz * vz;
  100135. if (distance < maxDistance) {
  100136. maxDistance = distance;
  100137. v2x = vx; v2y = vy; v2z = vz;
  100138. }
  100139. //vertex4;
  100140. vx = V2[9]; vy = V2[10]; vz = V2[11];
  100141. distance = nx * vx + ny * vy + nz * vz;
  100142. if (distance < maxDistance) {
  100143. maxDistance = distance;
  100144. v2x = vx; v2y = vy; v2z = vz;
  100145. }
  100146. //vertex5;
  100147. vx = V2[12]; vy = V2[13]; vz = V2[14];
  100148. distance = nx * vx + ny * vy + nz * vz;
  100149. if (distance < maxDistance) {
  100150. maxDistance = distance;
  100151. v2x = vx; v2y = vy; v2z = vz;
  100152. }
  100153. //vertex6;
  100154. vx = V2[15]; vy = V2[16]; vz = V2[17];
  100155. distance = nx * vx + ny * vy + nz * vz;
  100156. if (distance < maxDistance) {
  100157. maxDistance = distance;
  100158. v2x = vx; v2y = vy; v2z = vz;
  100159. }
  100160. //vertex7;
  100161. vx = V2[18]; vy = V2[19]; vz = V2[20];
  100162. distance = nx * vx + ny * vy + nz * vz;
  100163. if (distance < maxDistance) {
  100164. maxDistance = distance;
  100165. v2x = vx; v2y = vy; v2z = vz;
  100166. }
  100167. //vertex8;
  100168. vx = V2[21]; vy = V2[22]; vz = V2[23];
  100169. distance = nx * vx + ny * vy + nz * vz;
  100170. if (distance < maxDistance) {
  100171. maxDistance = distance;
  100172. v2x = vx; v2y = vy; v2z = vz;
  100173. }
  100174. vx = v2x - v1x; vy = v2y - v1y; vz = v2z - v1z;
  100175. dot1 = n1x * n2x + n1y * n2y + n1z * n2z;
  100176. var t = (vx * (n1x - n2x * dot1) + vy * (n1y - n2y * dot1) + vz * (n1z - n2z * dot1)) / (1 - dot1 * dot1);
  100177. 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);
  100178. return;
  100179. }
  100180. // now detect face-face collision...
  100181. // target quad
  100182. var q1x;
  100183. var q1y;
  100184. var q1z;
  100185. var q2x;
  100186. var q2y;
  100187. var q2z;
  100188. var q3x;
  100189. var q3y;
  100190. var q3z;
  100191. var q4x;
  100192. var q4y;
  100193. var q4z;
  100194. // search support face and vertex
  100195. var minDot = 1;
  100196. var dot = 0;
  100197. var minDotIndex = 0;
  100198. if (swap) {
  100199. dot = a1x * nx + a1y * ny + a1z * nz;
  100200. if (dot < minDot) {
  100201. minDot = dot;
  100202. minDotIndex = 0;
  100203. }
  100204. if (-dot < minDot) {
  100205. minDot = -dot;
  100206. minDotIndex = 1;
  100207. }
  100208. dot = a2x * nx + a2y * ny + a2z * nz;
  100209. if (dot < minDot) {
  100210. minDot = dot;
  100211. minDotIndex = 2;
  100212. }
  100213. if (-dot < minDot) {
  100214. minDot = -dot;
  100215. minDotIndex = 3;
  100216. }
  100217. dot = a3x * nx + a3y * ny + a3z * nz;
  100218. if (dot < minDot) {
  100219. minDot = dot;
  100220. minDotIndex = 4;
  100221. }
  100222. if (-dot < minDot) {
  100223. minDot = -dot;
  100224. minDotIndex = 5;
  100225. }
  100226. if (minDotIndex == 0) {// x+ face
  100227. q1x = V1[0]; q1y = V1[1]; q1z = V1[2];//vertex1
  100228. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex3
  100229. q3x = V1[9]; q3y = V1[10]; q3z = V1[11];//vertex4
  100230. q4x = V1[3]; q4y = V1[4]; q4z = V1[5];//vertex2
  100231. }
  100232. else if (minDotIndex == 1) {// x- face
  100233. q1x = V1[15]; q1y = V1[16]; q1z = V1[17];//vertex6
  100234. q2x = V1[21]; q2y = V1[22]; q2z = V1[23];//vertex8
  100235. q3x = V1[18]; q3y = V1[19]; q3z = V1[20];//vertex7
  100236. q4x = V1[12]; q4y = V1[13]; q4z = V1[14];//vertex5
  100237. }
  100238. else if (minDotIndex == 2) {// y+ face
  100239. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  100240. q2x = V1[0]; q2y = V1[1]; q2z = V1[2];//vertex1
  100241. q3x = V1[3]; q3y = V1[4]; q3z = V1[5];//vertex2
  100242. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  100243. }
  100244. else if (minDotIndex == 3) {// y- face
  100245. q1x = V1[21]; q1y = V1[22]; q1z = V1[23];//vertex8
  100246. q2x = V1[9]; q2y = V1[10]; q2z = V1[11];//vertex4
  100247. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  100248. q4x = V1[18]; q4y = V1[19]; q4z = V1[20];//vertex7
  100249. }
  100250. else if (minDotIndex == 4) {// z+ face
  100251. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  100252. q2x = V1[18]; q2y = V1[19]; q2z = V1[20];//vertex7
  100253. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  100254. q4x = V1[0]; q4y = V1[1]; q4z = V1[2];//vertex1
  100255. }
  100256. else if (minDotIndex == 5) {// z- face
  100257. q1x = V1[3]; q1y = V1[4]; q1z = V1[5];//vertex2
  100258. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex4
  100259. q3x = V1[21]; q3y = V1[22]; q3z = V1[23];//vertex8
  100260. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  100261. }
  100262. } else {
  100263. dot = a4x * nx + a4y * ny + a4z * nz;
  100264. if (dot < minDot) {
  100265. minDot = dot;
  100266. minDotIndex = 0;
  100267. }
  100268. if (-dot < minDot) {
  100269. minDot = -dot;
  100270. minDotIndex = 1;
  100271. }
  100272. dot = a5x * nx + a5y * ny + a5z * nz;
  100273. if (dot < minDot) {
  100274. minDot = dot;
  100275. minDotIndex = 2;
  100276. }
  100277. if (-dot < minDot) {
  100278. minDot = -dot;
  100279. minDotIndex = 3;
  100280. }
  100281. dot = a6x * nx + a6y * ny + a6z * nz;
  100282. if (dot < minDot) {
  100283. minDot = dot;
  100284. minDotIndex = 4;
  100285. }
  100286. if (-dot < minDot) {
  100287. minDot = -dot;
  100288. minDotIndex = 5;
  100289. }
  100290. //______________________________________________________
  100291. if (minDotIndex == 0) {// x+ face
  100292. q1x = V2[0]; q1y = V2[1]; q1z = V2[2];//vertex1
  100293. q2x = V2[6]; q2y = V2[7]; q2z = V2[8];//vertex3
  100294. q3x = V2[9]; q3y = V2[10]; q3z = V2[11];//vertex4
  100295. q4x = V2[3]; q4y = V2[4]; q4z = V2[5];//vertex2
  100296. }
  100297. else if (minDotIndex == 1) {// x- face
  100298. q1x = V2[15]; q1y = V2[16]; q1z = V2[17];//vertex6
  100299. q2x = V2[21]; q2y = V2[22]; q2z = V2[23]; //vertex8
  100300. q3x = V2[18]; q3y = V2[19]; q3z = V2[20];//vertex7
  100301. q4x = V2[12]; q4y = V2[13]; q4z = V2[14];//vertex5
  100302. }
  100303. else if (minDotIndex == 2) {// y+ face
  100304. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  100305. q2x = V2[0]; q2y = V2[1]; q2z = V2[2];//vertex1
  100306. q3x = V2[3]; q3y = V2[4]; q3z = V2[5];//vertex2
  100307. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  100308. }
  100309. else if (minDotIndex == 3) {// y- face
  100310. q1x = V2[21]; q1y = V2[22]; q1z = V2[23];//vertex8
  100311. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  100312. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  100313. q4x = V2[18]; q4y = V2[19]; q4z = V2[20];//vertex7
  100314. }
  100315. else if (minDotIndex == 4) {// z+ face
  100316. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  100317. q2x = V2[18]; q2y = V2[19]; q2z = V2[20];//vertex7
  100318. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  100319. q4x = V2[0]; q4y = V2[1]; q4z = V2[2];//vertex1
  100320. }
  100321. else if (minDotIndex == 5) {// z- face
  100322. q1x = V2[3]; q1y = V2[4]; q1z = V2[5];//vertex2
  100323. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  100324. q3x = V2[21]; q3y = V2[22]; q3z = V2[23];//vertex8
  100325. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  100326. }
  100327. }
  100328. // clip vertices
  100329. var numClipVertices;
  100330. var numAddedClipVertices;
  100331. var index;
  100332. var x1;
  100333. var y1;
  100334. var z1;
  100335. var x2;
  100336. var y2;
  100337. var z2;
  100338. this.clipVertices1[0] = q1x;
  100339. this.clipVertices1[1] = q1y;
  100340. this.clipVertices1[2] = q1z;
  100341. this.clipVertices1[3] = q2x;
  100342. this.clipVertices1[4] = q2y;
  100343. this.clipVertices1[5] = q2z;
  100344. this.clipVertices1[6] = q3x;
  100345. this.clipVertices1[7] = q3y;
  100346. this.clipVertices1[8] = q3z;
  100347. this.clipVertices1[9] = q4x;
  100348. this.clipVertices1[10] = q4y;
  100349. this.clipVertices1[11] = q4z;
  100350. numAddedClipVertices = 0;
  100351. x1 = this.clipVertices1[9];
  100352. y1 = this.clipVertices1[10];
  100353. z1 = this.clipVertices1[11];
  100354. dot1 = (x1 - cx - s1x) * n1x + (y1 - cy - s1y) * n1y + (z1 - cz - s1z) * n1z;
  100355. //var i = 4;
  100356. //while(i--){
  100357. for (var i = 0; i < 4; i++) {
  100358. index = i * 3;
  100359. x2 = this.clipVertices1[index];
  100360. y2 = this.clipVertices1[index + 1];
  100361. z2 = this.clipVertices1[index + 2];
  100362. dot2 = (x2 - cx - s1x) * n1x + (y2 - cy - s1y) * n1y + (z2 - cz - s1z) * n1z;
  100363. if (dot1 > 0) {
  100364. if (dot2 > 0) {
  100365. index = numAddedClipVertices * 3;
  100366. numAddedClipVertices++;
  100367. this.clipVertices2[index] = x2;
  100368. this.clipVertices2[index + 1] = y2;
  100369. this.clipVertices2[index + 2] = z2;
  100370. } else {
  100371. index = numAddedClipVertices * 3;
  100372. numAddedClipVertices++;
  100373. t = dot1 / (dot1 - dot2);
  100374. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  100375. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  100376. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  100377. }
  100378. } else {
  100379. if (dot2 > 0) {
  100380. index = numAddedClipVertices * 3;
  100381. numAddedClipVertices++;
  100382. t = dot1 / (dot1 - dot2);
  100383. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  100384. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  100385. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  100386. index = numAddedClipVertices * 3;
  100387. numAddedClipVertices++;
  100388. this.clipVertices2[index] = x2;
  100389. this.clipVertices2[index + 1] = y2;
  100390. this.clipVertices2[index + 2] = z2;
  100391. }
  100392. }
  100393. x1 = x2;
  100394. y1 = y2;
  100395. z1 = z2;
  100396. dot1 = dot2;
  100397. }
  100398. numClipVertices = numAddedClipVertices;
  100399. if (numClipVertices == 0) return;
  100400. numAddedClipVertices = 0;
  100401. index = (numClipVertices - 1) * 3;
  100402. x1 = this.clipVertices2[index];
  100403. y1 = this.clipVertices2[index + 1];
  100404. z1 = this.clipVertices2[index + 2];
  100405. dot1 = (x1 - cx - s2x) * n2x + (y1 - cy - s2y) * n2y + (z1 - cz - s2z) * n2z;
  100406. //i = numClipVertices;
  100407. //while(i--){
  100408. for (i = 0; i < numClipVertices; i++) {
  100409. index = i * 3;
  100410. x2 = this.clipVertices2[index];
  100411. y2 = this.clipVertices2[index + 1];
  100412. z2 = this.clipVertices2[index + 2];
  100413. dot2 = (x2 - cx - s2x) * n2x + (y2 - cy - s2y) * n2y + (z2 - cz - s2z) * n2z;
  100414. if (dot1 > 0) {
  100415. if (dot2 > 0) {
  100416. index = numAddedClipVertices * 3;
  100417. numAddedClipVertices++;
  100418. this.clipVertices1[index] = x2;
  100419. this.clipVertices1[index + 1] = y2;
  100420. this.clipVertices1[index + 2] = z2;
  100421. } else {
  100422. index = numAddedClipVertices * 3;
  100423. numAddedClipVertices++;
  100424. t = dot1 / (dot1 - dot2);
  100425. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  100426. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  100427. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  100428. }
  100429. } else {
  100430. if (dot2 > 0) {
  100431. index = numAddedClipVertices * 3;
  100432. numAddedClipVertices++;
  100433. t = dot1 / (dot1 - dot2);
  100434. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  100435. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  100436. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  100437. index = numAddedClipVertices * 3;
  100438. numAddedClipVertices++;
  100439. this.clipVertices1[index] = x2;
  100440. this.clipVertices1[index + 1] = y2;
  100441. this.clipVertices1[index + 2] = z2;
  100442. }
  100443. }
  100444. x1 = x2;
  100445. y1 = y2;
  100446. z1 = z2;
  100447. dot1 = dot2;
  100448. }
  100449. numClipVertices = numAddedClipVertices;
  100450. if (numClipVertices == 0) return;
  100451. numAddedClipVertices = 0;
  100452. index = (numClipVertices - 1) * 3;
  100453. x1 = this.clipVertices1[index];
  100454. y1 = this.clipVertices1[index + 1];
  100455. z1 = this.clipVertices1[index + 2];
  100456. dot1 = (x1 - cx + s1x) * -n1x + (y1 - cy + s1y) * -n1y + (z1 - cz + s1z) * -n1z;
  100457. //i = numClipVertices;
  100458. //while(i--){
  100459. for (i = 0; i < numClipVertices; i++) {
  100460. index = i * 3;
  100461. x2 = this.clipVertices1[index];
  100462. y2 = this.clipVertices1[index + 1];
  100463. z2 = this.clipVertices1[index + 2];
  100464. dot2 = (x2 - cx + s1x) * -n1x + (y2 - cy + s1y) * -n1y + (z2 - cz + s1z) * -n1z;
  100465. if (dot1 > 0) {
  100466. if (dot2 > 0) {
  100467. index = numAddedClipVertices * 3;
  100468. numAddedClipVertices++;
  100469. this.clipVertices2[index] = x2;
  100470. this.clipVertices2[index + 1] = y2;
  100471. this.clipVertices2[index + 2] = z2;
  100472. } else {
  100473. index = numAddedClipVertices * 3;
  100474. numAddedClipVertices++;
  100475. t = dot1 / (dot1 - dot2);
  100476. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  100477. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  100478. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  100479. }
  100480. } else {
  100481. if (dot2 > 0) {
  100482. index = numAddedClipVertices * 3;
  100483. numAddedClipVertices++;
  100484. t = dot1 / (dot1 - dot2);
  100485. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  100486. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  100487. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  100488. index = numAddedClipVertices * 3;
  100489. numAddedClipVertices++;
  100490. this.clipVertices2[index] = x2;
  100491. this.clipVertices2[index + 1] = y2;
  100492. this.clipVertices2[index + 2] = z2;
  100493. }
  100494. }
  100495. x1 = x2;
  100496. y1 = y2;
  100497. z1 = z2;
  100498. dot1 = dot2;
  100499. }
  100500. numClipVertices = numAddedClipVertices;
  100501. if (numClipVertices == 0) return;
  100502. numAddedClipVertices = 0;
  100503. index = (numClipVertices - 1) * 3;
  100504. x1 = this.clipVertices2[index];
  100505. y1 = this.clipVertices2[index + 1];
  100506. z1 = this.clipVertices2[index + 2];
  100507. dot1 = (x1 - cx + s2x) * -n2x + (y1 - cy + s2y) * -n2y + (z1 - cz + s2z) * -n2z;
  100508. //i = numClipVertices;
  100509. //while(i--){
  100510. for (i = 0; i < numClipVertices; i++) {
  100511. index = i * 3;
  100512. x2 = this.clipVertices2[index];
  100513. y2 = this.clipVertices2[index + 1];
  100514. z2 = this.clipVertices2[index + 2];
  100515. dot2 = (x2 - cx + s2x) * -n2x + (y2 - cy + s2y) * -n2y + (z2 - cz + s2z) * -n2z;
  100516. if (dot1 > 0) {
  100517. if (dot2 > 0) {
  100518. index = numAddedClipVertices * 3;
  100519. numAddedClipVertices++;
  100520. this.clipVertices1[index] = x2;
  100521. this.clipVertices1[index + 1] = y2;
  100522. this.clipVertices1[index + 2] = z2;
  100523. } else {
  100524. index = numAddedClipVertices * 3;
  100525. numAddedClipVertices++;
  100526. t = dot1 / (dot1 - dot2);
  100527. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  100528. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  100529. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  100530. }
  100531. } else {
  100532. if (dot2 > 0) {
  100533. index = numAddedClipVertices * 3;
  100534. numAddedClipVertices++;
  100535. t = dot1 / (dot1 - dot2);
  100536. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  100537. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  100538. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  100539. index = numAddedClipVertices * 3;
  100540. numAddedClipVertices++;
  100541. this.clipVertices1[index] = x2;
  100542. this.clipVertices1[index + 1] = y2;
  100543. this.clipVertices1[index + 2] = z2;
  100544. }
  100545. }
  100546. x1 = x2;
  100547. y1 = y2;
  100548. z1 = z2;
  100549. dot1 = dot2;
  100550. }
  100551. numClipVertices = numAddedClipVertices;
  100552. if (swap) {
  100553. var tb = b1;
  100554. b1 = b2;
  100555. b2 = tb;
  100556. }
  100557. if (numClipVertices == 0) return;
  100558. var flipped = b1 != shape1;
  100559. if (numClipVertices > 4) {
  100560. x1 = (q1x + q2x + q3x + q4x) * 0.25;
  100561. y1 = (q1y + q2y + q3y + q4y) * 0.25;
  100562. z1 = (q1z + q2z + q3z + q4z) * 0.25;
  100563. n1x = q1x - x1;
  100564. n1y = q1y - y1;
  100565. n1z = q1z - z1;
  100566. n2x = q2x - x1;
  100567. n2y = q2y - y1;
  100568. n2z = q2z - z1;
  100569. var index1 = 0;
  100570. var index2 = 0;
  100571. var index3 = 0;
  100572. var index4 = 0;
  100573. var maxDot = -this.INF;
  100574. minDot = this.INF;
  100575. //i = numClipVertices;
  100576. //while(i--){
  100577. for (i = 0; i < numClipVertices; i++) {
  100578. this.used[i] = false;
  100579. index = i * 3;
  100580. x1 = this.clipVertices1[index];
  100581. y1 = this.clipVertices1[index + 1];
  100582. z1 = this.clipVertices1[index + 2];
  100583. dot = x1 * n1x + y1 * n1y + z1 * n1z;
  100584. if (dot < minDot) {
  100585. minDot = dot;
  100586. index1 = i;
  100587. }
  100588. if (dot > maxDot) {
  100589. maxDot = dot;
  100590. index3 = i;
  100591. }
  100592. }
  100593. this.used[index1] = true;
  100594. this.used[index3] = true;
  100595. maxDot = -this.INF;
  100596. minDot = this.INF;
  100597. //i = numClipVertices;
  100598. //while(i--){
  100599. for (i = 0; i < numClipVertices; i++) {
  100600. if (this.used[i]) continue;
  100601. index = i * 3;
  100602. x1 = this.clipVertices1[index];
  100603. y1 = this.clipVertices1[index + 1];
  100604. z1 = this.clipVertices1[index + 2];
  100605. dot = x1 * n2x + y1 * n2y + z1 * n2z;
  100606. if (dot < minDot) {
  100607. minDot = dot;
  100608. index2 = i;
  100609. }
  100610. if (dot > maxDot) {
  100611. maxDot = dot;
  100612. index4 = i;
  100613. }
  100614. }
  100615. index = index1 * 3;
  100616. x1 = this.clipVertices1[index];
  100617. y1 = this.clipVertices1[index + 1];
  100618. z1 = this.clipVertices1[index + 2];
  100619. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100620. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100621. index = index2 * 3;
  100622. x1 = this.clipVertices1[index];
  100623. y1 = this.clipVertices1[index + 1];
  100624. z1 = this.clipVertices1[index + 2];
  100625. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100626. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100627. index = index3 * 3;
  100628. x1 = this.clipVertices1[index];
  100629. y1 = this.clipVertices1[index + 1];
  100630. z1 = this.clipVertices1[index + 2];
  100631. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100632. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100633. index = index4 * 3;
  100634. x1 = this.clipVertices1[index];
  100635. y1 = this.clipVertices1[index + 1];
  100636. z1 = this.clipVertices1[index + 2];
  100637. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100638. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100639. } else {
  100640. //i = numClipVertices;
  100641. //while(i--){
  100642. for (i = 0; i < numClipVertices; i++) {
  100643. index = i * 3;
  100644. x1 = this.clipVertices1[index];
  100645. y1 = this.clipVertices1[index + 1];
  100646. z1 = this.clipVertices1[index + 2];
  100647. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100648. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100649. }
  100650. }
  100651. };
  100652. /**
  100653. * A collision detector which detects collisions between sphere and box.
  100654. * @author saharan
  100655. */
  100656. OIMO.SphereBoxCollisionDetector = function (flip) {
  100657. OIMO.CollisionDetector.call(this);
  100658. this.flip = flip;
  100659. };
  100660. OIMO.SphereBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  100661. OIMO.SphereBoxCollisionDetector.prototype.constructor = OIMO.SphereBoxCollisionDetector;
  100662. OIMO.SphereBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  100663. var s;
  100664. var b;
  100665. if (this.flip) {
  100666. s = (shape2);
  100667. b = (shape1);
  100668. } else {
  100669. s = (shape1);
  100670. b = (shape2);
  100671. }
  100672. var D = b.dimentions;
  100673. var ps = s.position;
  100674. var psx = ps.x;
  100675. var psy = ps.y;
  100676. var psz = ps.z;
  100677. var pb = b.position;
  100678. var pbx = pb.x;
  100679. var pby = pb.y;
  100680. var pbz = pb.z;
  100681. var rad = s.radius;
  100682. var hw = b.halfWidth;
  100683. var hh = b.halfHeight;
  100684. var hd = b.halfDepth;
  100685. var dx = psx - pbx;
  100686. var dy = psy - pby;
  100687. var dz = psz - pbz;
  100688. var sx = D[0] * dx + D[1] * dy + D[2] * dz;
  100689. var sy = D[3] * dx + D[4] * dy + D[5] * dz;
  100690. var sz = D[6] * dx + D[7] * dy + D[8] * dz;
  100691. var cx;
  100692. var cy;
  100693. var cz;
  100694. var len;
  100695. var invLen;
  100696. var overlap = 0;
  100697. if (sx > hw) {
  100698. sx = hw;
  100699. } else if (sx < -hw) {
  100700. sx = -hw;
  100701. } else {
  100702. overlap = 1;
  100703. }
  100704. if (sy > hh) {
  100705. sy = hh;
  100706. } else if (sy < -hh) {
  100707. sy = -hh;
  100708. } else {
  100709. overlap |= 2;
  100710. }
  100711. if (sz > hd) {
  100712. sz = hd;
  100713. } else if (sz < -hd) {
  100714. sz = -hd;
  100715. } else {
  100716. overlap |= 4;
  100717. }
  100718. if (overlap == 7) {
  100719. // center of sphere is in the box
  100720. if (sx < 0) {
  100721. dx = hw + sx;
  100722. } else {
  100723. dx = hw - sx;
  100724. }
  100725. if (sy < 0) {
  100726. dy = hh + sy;
  100727. } else {
  100728. dy = hh - sy;
  100729. }
  100730. if (sz < 0) {
  100731. dz = hd + sz;
  100732. } else {
  100733. dz = hd - sz;
  100734. }
  100735. if (dx < dy) {
  100736. if (dx < dz) {
  100737. len = dx - hw;
  100738. if (sx < 0) {
  100739. sx = -hw;
  100740. dx = D[0];
  100741. dy = D[1];
  100742. dz = D[2];
  100743. } else {
  100744. sx = hw;
  100745. dx = -D[0];
  100746. dy = -D[1];
  100747. dz = -D[2];
  100748. }
  100749. } else {
  100750. len = dz - hd;
  100751. if (sz < 0) {
  100752. sz = -hd;
  100753. dx = D[6];
  100754. dy = D[7];
  100755. dz = D[8];
  100756. } else {
  100757. sz = hd;
  100758. dx = -D[6];
  100759. dy = -D[7];
  100760. dz = -D[8];
  100761. }
  100762. }
  100763. } else {
  100764. if (dy < dz) {
  100765. len = dy - hh;
  100766. if (sy < 0) {
  100767. sy = -hh;
  100768. dx = D[3];
  100769. dy = D[4];
  100770. dz = D[5];
  100771. } else {
  100772. sy = hh;
  100773. dx = -D[3];
  100774. dy = -D[4];
  100775. dz = -D[5];
  100776. }
  100777. } else {
  100778. len = dz - hd;
  100779. if (sz < 0) {
  100780. sz = -hd;
  100781. dx = D[6];
  100782. dy = D[7];
  100783. dz = D[8];
  100784. } else {
  100785. sz = hd;
  100786. dx = -D[6];
  100787. dy = -D[7];
  100788. dz = -D[8];
  100789. }
  100790. }
  100791. }
  100792. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  100793. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  100794. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  100795. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  100796. } else {
  100797. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  100798. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  100799. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  100800. dx = cx - ps.x;
  100801. dy = cy - ps.y;
  100802. dz = cz - ps.z;
  100803. len = dx * dx + dy * dy + dz * dz;
  100804. if (len > 0 && len < rad * rad) {
  100805. len = OIMO.sqrt(len);
  100806. invLen = 1 / len;
  100807. dx *= invLen;
  100808. dy *= invLen;
  100809. dz *= invLen;
  100810. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  100811. }
  100812. }
  100813. };
  100814. /**
  100815. * A collision detector which detects collisions between two spheres.
  100816. * @author saharan
  100817. */
  100818. OIMO.SphereSphereCollisionDetector = function () {
  100819. OIMO.CollisionDetector.call(this);
  100820. };
  100821. OIMO.SphereSphereCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  100822. OIMO.SphereSphereCollisionDetector.prototype.constructor = OIMO.SphereSphereCollisionDetector;
  100823. OIMO.SphereSphereCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  100824. var s1 = shape1;
  100825. var s2 = shape2;
  100826. var p1 = s1.position;
  100827. var p2 = s2.position;
  100828. var dx = p2.x - p1.x;
  100829. var dy = p2.y - p1.y;
  100830. var dz = p2.z - p1.z;
  100831. var len = dx * dx + dy * dy + dz * dz;
  100832. var r1 = s1.radius;
  100833. var r2 = s2.radius;
  100834. var rad = r1 + r2;
  100835. if (len > 0 && len < rad * rad) {
  100836. len = OIMO.sqrt(len);
  100837. var invLen = 1 / len;
  100838. dx *= invLen;
  100839. dy *= invLen;
  100840. dz *= invLen;
  100841. manifold.addPoint(p1.x + dx * r1, p1.y + dy * r1, p1.z + dz * r1, dx, dy, dz, len - rad, false);
  100842. }
  100843. };
  100844. OIMO.BoxCylinderCollisionDetector = function (flip) {
  100845. OIMO.CollisionDetector.call(this);
  100846. this.flip = flip;
  100847. };
  100848. OIMO.BoxCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  100849. OIMO.BoxCylinderCollisionDetector.prototype.constructor = OIMO.BoxCylinderCollisionDetector;
  100850. OIMO.BoxCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  100851. var t1x;
  100852. var t1y;
  100853. var t1z;
  100854. var t2x;
  100855. var t2y;
  100856. var t2z;
  100857. var sup = new OIMO.Vec3();
  100858. var len;
  100859. var p1x;
  100860. var p1y;
  100861. var p1z;
  100862. var p2x;
  100863. var p2y;
  100864. var p2z;
  100865. var v01x = c1.position.x;
  100866. var v01y = c1.position.y;
  100867. var v01z = c1.position.z;
  100868. var v02x = c2.position.x;
  100869. var v02y = c2.position.y;
  100870. var v02z = c2.position.z;
  100871. var v0x = v02x - v01x;
  100872. var v0y = v02y - v01y;
  100873. var v0z = v02z - v01z;
  100874. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  100875. var nx = -v0x;
  100876. var ny = -v0y;
  100877. var nz = -v0z;
  100878. this.supportPointB(c1, -nx, -ny, -nz, sup);
  100879. var v11x = sup.x;
  100880. var v11y = sup.y;
  100881. var v11z = sup.z;
  100882. this.supportPointC(c2, nx, ny, nz, sup);
  100883. var v12x = sup.x;
  100884. var v12y = sup.y;
  100885. var v12z = sup.z;
  100886. var v1x = v12x - v11x;
  100887. var v1y = v12y - v11y;
  100888. var v1z = v12z - v11z;
  100889. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  100890. return false;
  100891. }
  100892. nx = v1y * v0z - v1z * v0y;
  100893. ny = v1z * v0x - v1x * v0z;
  100894. nz = v1x * v0y - v1y * v0x;
  100895. if (nx * nx + ny * ny + nz * nz == 0) {
  100896. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  100897. sep.normalize(sep);
  100898. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  100899. return true;
  100900. }
  100901. this.supportPointB(c1, -nx, -ny, -nz, sup);
  100902. var v21x = sup.x;
  100903. var v21y = sup.y;
  100904. var v21z = sup.z;
  100905. this.supportPointC(c2, nx, ny, nz, sup);
  100906. var v22x = sup.x;
  100907. var v22y = sup.y;
  100908. var v22z = sup.z;
  100909. var v2x = v22x - v21x;
  100910. var v2y = v22y - v21y;
  100911. var v2z = v22z - v21z;
  100912. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  100913. return false;
  100914. }
  100915. t1x = v1x - v0x;
  100916. t1y = v1y - v0y;
  100917. t1z = v1z - v0z;
  100918. t2x = v2x - v0x;
  100919. t2y = v2y - v0y;
  100920. t2z = v2z - v0z;
  100921. nx = t1y * t2z - t1z * t2y;
  100922. ny = t1z * t2x - t1x * t2z;
  100923. nz = t1x * t2y - t1y * t2x;
  100924. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  100925. t1x = v1x;
  100926. t1y = v1y;
  100927. t1z = v1z;
  100928. v1x = v2x;
  100929. v1y = v2y;
  100930. v1z = v2z;
  100931. v2x = t1x;
  100932. v2y = t1y;
  100933. v2z = t1z;
  100934. t1x = v11x;
  100935. t1y = v11y;
  100936. t1z = v11z;
  100937. v11x = v21x;
  100938. v11y = v21y;
  100939. v11z = v21z;
  100940. v21x = t1x;
  100941. v21y = t1y;
  100942. v21z = t1z;
  100943. t1x = v12x;
  100944. t1y = v12y;
  100945. t1z = v12z;
  100946. v12x = v22x;
  100947. v12y = v22y;
  100948. v12z = v22z;
  100949. v22x = t1x;
  100950. v22y = t1y;
  100951. v22z = t1z;
  100952. nx = -nx;
  100953. ny = -ny;
  100954. nz = -nz;
  100955. }
  100956. var iterations = 0;
  100957. while (true) {
  100958. if (++iterations > 100) {
  100959. return false;
  100960. }
  100961. this.supportPointB(c1, -nx, -ny, -nz, sup);
  100962. var v31x = sup.x;
  100963. var v31y = sup.y;
  100964. var v31z = sup.z;
  100965. this.supportPointC(c2, nx, ny, nz, sup);
  100966. var v32x = sup.x;
  100967. var v32y = sup.y;
  100968. var v32z = sup.z;
  100969. var v3x = v32x - v31x;
  100970. var v3y = v32y - v31y;
  100971. var v3z = v32z - v31z;
  100972. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  100973. return false;
  100974. }
  100975. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  100976. v2x = v3x;
  100977. v2y = v3y;
  100978. v2z = v3z;
  100979. v21x = v31x;
  100980. v21y = v31y;
  100981. v21z = v31z;
  100982. v22x = v32x;
  100983. v22y = v32y;
  100984. v22z = v32z;
  100985. t1x = v1x - v0x;
  100986. t1y = v1y - v0y;
  100987. t1z = v1z - v0z;
  100988. t2x = v3x - v0x;
  100989. t2y = v3y - v0y;
  100990. t2z = v3z - v0z;
  100991. nx = t1y * t2z - t1z * t2y;
  100992. ny = t1z * t2x - t1x * t2z;
  100993. nz = t1x * t2y - t1y * t2x;
  100994. continue;
  100995. }
  100996. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  100997. v1x = v3x;
  100998. v1y = v3y;
  100999. v1z = v3z;
  101000. v11x = v31x;
  101001. v11y = v31y;
  101002. v11z = v31z;
  101003. v12x = v32x;
  101004. v12y = v32y;
  101005. v12z = v32z;
  101006. t1x = v3x - v0x;
  101007. t1y = v3y - v0y;
  101008. t1z = v3z - v0z;
  101009. t2x = v2x - v0x;
  101010. t2y = v2y - v0y;
  101011. t2z = v2z - v0z;
  101012. nx = t1y * t2z - t1z * t2y;
  101013. ny = t1z * t2x - t1x * t2z;
  101014. nz = t1x * t2y - t1y * t2x;
  101015. continue;
  101016. }
  101017. var hit = false;
  101018. while (true) {
  101019. t1x = v2x - v1x;
  101020. t1y = v2y - v1y;
  101021. t1z = v2z - v1z;
  101022. t2x = v3x - v1x;
  101023. t2y = v3y - v1y;
  101024. t2z = v3z - v1z;
  101025. nx = t1y * t2z - t1z * t2y;
  101026. ny = t1z * t2x - t1x * t2z;
  101027. nz = t1x * t2y - t1y * t2x;
  101028. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  101029. nx *= len;
  101030. ny *= len;
  101031. nz *= len;
  101032. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  101033. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  101034. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  101035. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  101036. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  101037. var sum = b0 + b1 + b2 + b3;
  101038. if (sum <= 0) {
  101039. b0 = 0;
  101040. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  101041. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  101042. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  101043. sum = b1 + b2 + b3;
  101044. }
  101045. var inv = 1 / sum;
  101046. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  101047. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  101048. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  101049. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  101050. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  101051. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  101052. hit = true;
  101053. }
  101054. this.supportPointB(c1, -nx, -ny, -nz, sup);
  101055. var v41x = sup.x;
  101056. var v41y = sup.y;
  101057. var v41z = sup.z;
  101058. this.supportPointC(c2, nx, ny, nz, sup);
  101059. var v42x = sup.x;
  101060. var v42y = sup.y;
  101061. var v42z = sup.z;
  101062. var v4x = v42x - v41x;
  101063. var v4y = v42y - v41y;
  101064. var v4z = v42z - v41z;
  101065. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  101066. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  101067. if (hit) {
  101068. sep.init(-nx, -ny, -nz);
  101069. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  101070. dep.x = separation;
  101071. return true;
  101072. }
  101073. return false;
  101074. }
  101075. if (
  101076. (v4y * v1z - v4z * v1y) * v0x +
  101077. (v4z * v1x - v4x * v1z) * v0y +
  101078. (v4x * v1y - v4y * v1x) * v0z < 0
  101079. ) {
  101080. if (
  101081. (v4y * v2z - v4z * v2y) * v0x +
  101082. (v4z * v2x - v4x * v2z) * v0y +
  101083. (v4x * v2y - v4y * v2x) * v0z < 0
  101084. ) {
  101085. v1x = v4x;
  101086. v1y = v4y;
  101087. v1z = v4z;
  101088. v11x = v41x;
  101089. v11y = v41y;
  101090. v11z = v41z;
  101091. v12x = v42x;
  101092. v12y = v42y;
  101093. v12z = v42z;
  101094. } else {
  101095. v3x = v4x;
  101096. v3y = v4y;
  101097. v3z = v4z;
  101098. v31x = v41x;
  101099. v31y = v41y;
  101100. v31z = v41z;
  101101. v32x = v42x;
  101102. v32y = v42y;
  101103. v32z = v42z;
  101104. }
  101105. } else {
  101106. if (
  101107. (v4y * v3z - v4z * v3y) * v0x +
  101108. (v4z * v3x - v4x * v3z) * v0y +
  101109. (v4x * v3y - v4y * v3x) * v0z < 0
  101110. ) {
  101111. v2x = v4x;
  101112. v2y = v4y;
  101113. v2z = v4z;
  101114. v21x = v41x;
  101115. v21y = v41y;
  101116. v21z = v41z;
  101117. v22x = v42x;
  101118. v22y = v42y;
  101119. v22z = v42z;
  101120. } else {
  101121. v1x = v4x;
  101122. v1y = v4y;
  101123. v1z = v4z;
  101124. v11x = v41x;
  101125. v11y = v41y;
  101126. v11z = v41z;
  101127. v12x = v42x;
  101128. v12y = v42y;
  101129. v12z = v42z;
  101130. }
  101131. }
  101132. }
  101133. }
  101134. //return false;
  101135. };
  101136. OIMO.BoxCylinderCollisionDetector.prototype.supportPointB = function (c, dx, dy, dz, out) {
  101137. var rot = c.rotation.elements;
  101138. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  101139. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  101140. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  101141. var w = c.halfWidth;
  101142. var h = c.halfHeight;
  101143. var d = c.halfDepth;
  101144. var ox;
  101145. var oy;
  101146. var oz;
  101147. if (ldx < 0) ox = -w;
  101148. else ox = w;
  101149. if (ldy < 0) oy = -h;
  101150. else oy = h;
  101151. if (ldz < 0) oz = -d;
  101152. else oz = d;
  101153. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  101154. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  101155. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  101156. out.init(ldx, ldy, ldz);
  101157. };
  101158. OIMO.BoxCylinderCollisionDetector.prototype.supportPointC = function (c, dx, dy, dz, out) {
  101159. var rot = c.rotation.elements;
  101160. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  101161. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  101162. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  101163. var radx = ldx;
  101164. var radz = ldz;
  101165. var len = radx * radx + radz * radz;
  101166. var rad = c.radius;
  101167. var hh = c.halfHeight;
  101168. var ox;
  101169. var oy;
  101170. var oz;
  101171. if (len == 0) {
  101172. if (ldy < 0) {
  101173. ox = rad;
  101174. oy = -hh;
  101175. oz = 0;
  101176. } else {
  101177. ox = rad;
  101178. oy = hh;
  101179. oz = 0;
  101180. }
  101181. } else {
  101182. len = c.radius / OIMO.sqrt(len);
  101183. if (ldy < 0) {
  101184. ox = radx * len;
  101185. oy = -hh;
  101186. oz = radz * len;
  101187. } else {
  101188. ox = radx * len;
  101189. oy = hh;
  101190. oz = radz * len;
  101191. }
  101192. }
  101193. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  101194. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  101195. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  101196. out.init(ldx, ldy, ldz);
  101197. };
  101198. OIMO.BoxCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  101199. var b;
  101200. var c;
  101201. if (this.flip) {
  101202. b = shape2;
  101203. c = shape1;
  101204. } else {
  101205. b = shape1;
  101206. c = shape2;
  101207. }
  101208. var sep = new OIMO.Vec3();
  101209. var pos = new OIMO.Vec3();
  101210. var dep = new OIMO.Vec3();
  101211. var co;
  101212. if (!this.getSep(b, c, sep, pos, dep)) return;
  101213. var pbx = b.position.x;
  101214. var pby = b.position.y;
  101215. var pbz = b.position.z;
  101216. var pcx = c.position.x;
  101217. var pcy = c.position.y;
  101218. var pcz = c.position.z;
  101219. var bw = b.halfWidth;
  101220. var bh = b.halfHeight;
  101221. var bd = b.halfDepth;
  101222. var ch = c.halfHeight;
  101223. var r = c.radius;
  101224. var D = b.dimentions;
  101225. var nwx = D[0];//b.normalDirectionWidth.x;
  101226. var nwy = D[1];//b.normalDirectionWidth.y;
  101227. var nwz = D[2];//b.normalDirectionWidth.z;
  101228. var nhx = D[3];//b.normalDirectionHeight.x;
  101229. var nhy = D[4];//b.normalDirectionHeight.y;
  101230. var nhz = D[5];//b.normalDirectionHeight.z;
  101231. var ndx = D[6];//b.normalDirectionDepth.x;
  101232. var ndy = D[7];//b.normalDirectionDepth.y;
  101233. var ndz = D[8];//b.normalDirectionDepth.z;
  101234. var dwx = D[9];//b.halfDirectionWidth.x;
  101235. var dwy = D[10];//b.halfDirectionWidth.y;
  101236. var dwz = D[11];//b.halfDirectionWidth.z;
  101237. var dhx = D[12];//b.halfDirectionHeight.x;
  101238. var dhy = D[13];//b.halfDirectionHeight.y;
  101239. var dhz = D[14];//b.halfDirectionHeight.z;
  101240. var ddx = D[15];//b.halfDirectionDepth.x;
  101241. var ddy = D[16];//b.halfDirectionDepth.y;
  101242. var ddz = D[17];//b.halfDirectionDepth.z;
  101243. var ncx = c.normalDirection.x;
  101244. var ncy = c.normalDirection.y;
  101245. var ncz = c.normalDirection.z;
  101246. var dcx = c.halfDirection.x;
  101247. var dcy = c.halfDirection.y;
  101248. var dcz = c.halfDirection.z;
  101249. var nx = sep.x;
  101250. var ny = sep.y;
  101251. var nz = sep.z;
  101252. var dotw = nx * nwx + ny * nwy + nz * nwz;
  101253. var doth = nx * nhx + ny * nhy + nz * nhz;
  101254. var dotd = nx * ndx + ny * ndy + nz * ndz;
  101255. var dotc = nx * ncx + ny * ncy + nz * ncz;
  101256. var right1 = dotw > 0;
  101257. var right2 = doth > 0;
  101258. var right3 = dotd > 0;
  101259. var right4 = dotc > 0;
  101260. if (!right1) dotw = -dotw;
  101261. if (!right2) doth = -doth;
  101262. if (!right3) dotd = -dotd;
  101263. if (!right4) dotc = -dotc;
  101264. var state = 0;
  101265. if (dotc > 0.999) {
  101266. if (dotw > 0.999) {
  101267. if (dotw > dotc) state = 1;
  101268. else state = 4;
  101269. } else if (doth > 0.999) {
  101270. if (doth > dotc) state = 2;
  101271. else state = 4;
  101272. } else if (dotd > 0.999) {
  101273. if (dotd > dotc) state = 3;
  101274. else state = 4;
  101275. } else state = 4;
  101276. } else {
  101277. if (dotw > 0.999) state = 1;
  101278. else if (doth > 0.999) state = 2;
  101279. else if (dotd > 0.999) state = 3;
  101280. }
  101281. var cbx;
  101282. var cby;
  101283. var cbz;
  101284. var ccx;
  101285. var ccy;
  101286. var ccz;
  101287. var r00;
  101288. var r01;
  101289. var r02;
  101290. var r10;
  101291. var r11;
  101292. var r12;
  101293. var r20;
  101294. var r21;
  101295. var r22;
  101296. var px;
  101297. var py;
  101298. var pz;
  101299. var pd;
  101300. var dot;
  101301. var len;
  101302. var tx;
  101303. var ty;
  101304. var tz;
  101305. var td;
  101306. var dx;
  101307. var dy;
  101308. var dz;
  101309. var d1x;
  101310. var d1y;
  101311. var d1z;
  101312. var d2x;
  101313. var d2y;
  101314. var d2z;
  101315. var sx;
  101316. var sy;
  101317. var sz;
  101318. var sd;
  101319. var ex;
  101320. var ey;
  101321. var ez;
  101322. var ed;
  101323. var dot1;
  101324. var dot2;
  101325. var t1;
  101326. var t2;
  101327. var dir1x;
  101328. var dir1y;
  101329. var dir1z;
  101330. var dir2x;
  101331. var dir2y;
  101332. var dir2z;
  101333. var dir1l;
  101334. var dir2l;
  101335. if (state == 0) {
  101336. //manifold.addPoint(pos.x,pos.y,pos.z,nx,ny,nz,dep.x,b,c,0,0,false);
  101337. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, dep.x, this.flip);
  101338. } else if (state == 4) {
  101339. if (right4) {
  101340. ccx = pcx - dcx;
  101341. ccy = pcy - dcy;
  101342. ccz = pcz - dcz;
  101343. nx = -ncx;
  101344. ny = -ncy;
  101345. nz = -ncz;
  101346. } else {
  101347. ccx = pcx + dcx;
  101348. ccy = pcy + dcy;
  101349. ccz = pcz + dcz;
  101350. nx = ncx;
  101351. ny = ncy;
  101352. nz = ncz;
  101353. }
  101354. var v1x;
  101355. var v1y;
  101356. var v1z;
  101357. var v2x;
  101358. var v2y;
  101359. var v2z;
  101360. var v3x;
  101361. var v3y;
  101362. var v3z;
  101363. var v4x;
  101364. var v4y;
  101365. var v4z;
  101366. dot = 1;
  101367. state = 0;
  101368. dot1 = nwx * nx + nwy * ny + nwz * nz;
  101369. if (dot1 < dot) {
  101370. dot = dot1;
  101371. state = 0;
  101372. }
  101373. if (-dot1 < dot) {
  101374. dot = -dot1;
  101375. state = 1;
  101376. }
  101377. dot1 = nhx * nx + nhy * ny + nhz * nz;
  101378. if (dot1 < dot) {
  101379. dot = dot1;
  101380. state = 2;
  101381. }
  101382. if (-dot1 < dot) {
  101383. dot = -dot1;
  101384. state = 3;
  101385. }
  101386. dot1 = ndx * nx + ndy * ny + ndz * nz;
  101387. if (dot1 < dot) {
  101388. dot = dot1;
  101389. state = 4;
  101390. }
  101391. if (-dot1 < dot) {
  101392. dot = -dot1;
  101393. state = 5;
  101394. }
  101395. var v = b.elements;
  101396. switch (state) {
  101397. case 0:
  101398. //v=b.vertex1;
  101399. v1x = v[0];//v.x;
  101400. v1y = v[1];//v.y;
  101401. v1z = v[2];//v.z;
  101402. //v=b.vertex3;
  101403. v2x = v[6];//v.x;
  101404. v2y = v[7];//v.y;
  101405. v2z = v[8];//v.z;
  101406. //v=b.vertex4;
  101407. v3x = v[9];//v.x;
  101408. v3y = v[10];//v.y;
  101409. v3z = v[11];//v.z;
  101410. //v=b.vertex2;
  101411. v4x = v[3];//v.x;
  101412. v4y = v[4];//v.y;
  101413. v4z = v[5];//v.z;
  101414. break;
  101415. case 1:
  101416. //v=b.vertex6;
  101417. v1x = v[15];//v.x;
  101418. v1y = v[16];//v.y;
  101419. v1z = v[17];//v.z;
  101420. //v=b.vertex8;
  101421. v2x = v[21];//v.x;
  101422. v2y = v[22];//v.y;
  101423. v2z = v[23];//v.z;
  101424. //v=b.vertex7;
  101425. v3x = v[18];//v.x;
  101426. v3y = v[19];//v.y;
  101427. v3z = v[20];//v.z;
  101428. //v=b.vertex5;
  101429. v4x = v[12];//v.x;
  101430. v4y = v[13];//v.y;
  101431. v4z = v[14];//v.z;
  101432. break;
  101433. case 2:
  101434. //v=b.vertex5;
  101435. v1x = v[12];//v.x;
  101436. v1y = v[13];//v.y;
  101437. v1z = v[14];//v.z;
  101438. //v=b.vertex1;
  101439. v2x = v[0];//v.x;
  101440. v2y = v[1];//v.y;
  101441. v2z = v[2];//v.z;
  101442. //v=b.vertex2;
  101443. v3x = v[3];//v.x;
  101444. v3y = v[4];//v.y;
  101445. v3z = v[5];//v.z;
  101446. //v=b.vertex6;
  101447. v4x = v[15];//v.x;
  101448. v4y = v[16];//v.y;
  101449. v4z = v[17];//v.z;
  101450. break;
  101451. case 3:
  101452. //v=b.vertex8;
  101453. v1x = v[21];//v.x;
  101454. v1y = v[22];//v.y;
  101455. v1z = v[23];//v.z;
  101456. //v=b.vertex4;
  101457. v2x = v[9];//v.x;
  101458. v2y = v[10];//v.y;
  101459. v2z = v[11];//v.z;
  101460. //v=b.vertex3;
  101461. v3x = v[6];//v.x;
  101462. v3y = v[7];//v.y;
  101463. v3z = v[8];//v.z;
  101464. //v=b.vertex7;
  101465. v4x = v[18];//v.x;
  101466. v4y = v[19];//v.y;
  101467. v4z = v[20];//v.z;
  101468. break;
  101469. case 4:
  101470. //v=b.vertex5;
  101471. v1x = v[12];//v.x;
  101472. v1y = v[13];//v.y;
  101473. v1z = v[14];//v.z;
  101474. //v=b.vertex7;
  101475. v2x = v[18];//v.x;
  101476. v2y = v[19];//v.y;
  101477. v2z = v[20];//v.z;
  101478. //v=b.vertex3;
  101479. v3x = v[6];//v.x;
  101480. v3y = v[7];//v.y;
  101481. v3z = v[8];//v.z;
  101482. //v=b.vertex1;
  101483. v4x = v[0];//v.x;
  101484. v4y = v[1];//v.y;
  101485. v4z = v[2];//v.z;
  101486. break;
  101487. case 5:
  101488. //v=b.vertex2;
  101489. v1x = v[3];//v.x;
  101490. v1y = v[4];//v.y;
  101491. v1z = v[5];//v.z;
  101492. //v=b.vertex4;
  101493. v2x = v[9];//v.x;
  101494. v2y = v[10];//v.y;
  101495. v2z = v[11];//v.z;
  101496. //v=b.vertex8;
  101497. v3x = v[21];//v.x;
  101498. v3y = v[22];//v.y;
  101499. v3z = v[23];//v.z;
  101500. //v=b.vertex6;
  101501. v4x = v[15];//v.x;
  101502. v4y = v[16];//v.y;
  101503. v4z = v[17];//v.z;
  101504. break;
  101505. }
  101506. pd = nx * (v1x - ccx) + ny * (v1y - ccy) + nz * (v1z - ccz);
  101507. if (pd <= 0) manifold.addPoint(v1x, v1y, v1z, -nx, -ny, -nz, pd, this.flip);
  101508. pd = nx * (v2x - ccx) + ny * (v2y - ccy) + nz * (v2z - ccz);
  101509. if (pd <= 0) manifold.addPoint(v2x, v2y, v2z, -nx, -ny, -nz, pd, this.flip);
  101510. pd = nx * (v3x - ccx) + ny * (v3y - ccy) + nz * (v3z - ccz);
  101511. if (pd <= 0) manifold.addPoint(v3x, v3y, v3z, -nx, -ny, -nz, pd, this.flip);
  101512. pd = nx * (v4x - ccx) + ny * (v4y - ccy) + nz * (v4z - ccz);
  101513. if (pd <= 0) manifold.addPoint(v4x, v4y, v4z, -nx, -ny, -nz, pd, this.flip);
  101514. } else {
  101515. switch (state) {
  101516. case 1:
  101517. if (right1) {
  101518. cbx = pbx + dwx;
  101519. cby = pby + dwy;
  101520. cbz = pbz + dwz;
  101521. nx = nwx;
  101522. ny = nwy;
  101523. nz = nwz;
  101524. } else {
  101525. cbx = pbx - dwx;
  101526. cby = pby - dwy;
  101527. cbz = pbz - dwz;
  101528. nx = -nwx;
  101529. ny = -nwy;
  101530. nz = -nwz;
  101531. }
  101532. dir1x = nhx;
  101533. dir1y = nhy;
  101534. dir1z = nhz;
  101535. dir1l = bh;
  101536. dir2x = ndx;
  101537. dir2y = ndy;
  101538. dir2z = ndz;
  101539. dir2l = bd;
  101540. break;
  101541. case 2:
  101542. if (right2) {
  101543. cbx = pbx + dhx;
  101544. cby = pby + dhy;
  101545. cbz = pbz + dhz;
  101546. nx = nhx;
  101547. ny = nhy;
  101548. nz = nhz;
  101549. } else {
  101550. cbx = pbx - dhx;
  101551. cby = pby - dhy;
  101552. cbz = pbz - dhz;
  101553. nx = -nhx;
  101554. ny = -nhy;
  101555. nz = -nhz;
  101556. }
  101557. dir1x = nwx;
  101558. dir1y = nwy;
  101559. dir1z = nwz;
  101560. dir1l = bw;
  101561. dir2x = ndx;
  101562. dir2y = ndy;
  101563. dir2z = ndz;
  101564. dir2l = bd;
  101565. break;
  101566. case 3:
  101567. if (right3) {
  101568. cbx = pbx + ddx;
  101569. cby = pby + ddy;
  101570. cbz = pbz + ddz;
  101571. nx = ndx;
  101572. ny = ndy;
  101573. nz = ndz;
  101574. } else {
  101575. cbx = pbx - ddx;
  101576. cby = pby - ddy;
  101577. cbz = pbz - ddz;
  101578. nx = -ndx;
  101579. ny = -ndy;
  101580. nz = -ndz;
  101581. }
  101582. dir1x = nwx;
  101583. dir1y = nwy;
  101584. dir1z = nwz;
  101585. dir1l = bw;
  101586. dir2x = nhx;
  101587. dir2y = nhy;
  101588. dir2z = nhz;
  101589. dir2l = bh;
  101590. break;
  101591. }
  101592. dot = nx * ncx + ny * ncy + nz * ncz;
  101593. if (dot < 0) len = ch;
  101594. else len = -ch;
  101595. ccx = pcx + len * ncx;
  101596. ccy = pcy + len * ncy;
  101597. ccz = pcz + len * ncz;
  101598. if (dotc >= 0.999999) {
  101599. tx = -ny;
  101600. ty = nz;
  101601. tz = nx;
  101602. } else {
  101603. tx = nx;
  101604. ty = ny;
  101605. tz = nz;
  101606. }
  101607. len = tx * ncx + ty * ncy + tz * ncz;
  101608. dx = len * ncx - tx;
  101609. dy = len * ncy - ty;
  101610. dz = len * ncz - tz;
  101611. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  101612. if (len == 0) return;
  101613. len = r / len;
  101614. dx *= len;
  101615. dy *= len;
  101616. dz *= len;
  101617. tx = ccx + dx;
  101618. ty = ccy + dy;
  101619. tz = ccz + dz;
  101620. if (dot < -0.96 || dot > 0.96) {
  101621. r00 = ncx * ncx * 1.5 - 0.5;
  101622. r01 = ncx * ncy * 1.5 - ncz * 0.866025403;
  101623. r02 = ncx * ncz * 1.5 + ncy * 0.866025403;
  101624. r10 = ncy * ncx * 1.5 + ncz * 0.866025403;
  101625. r11 = ncy * ncy * 1.5 - 0.5;
  101626. r12 = ncy * ncz * 1.5 - ncx * 0.866025403;
  101627. r20 = ncz * ncx * 1.5 - ncy * 0.866025403;
  101628. r21 = ncz * ncy * 1.5 + ncx * 0.866025403;
  101629. r22 = ncz * ncz * 1.5 - 0.5;
  101630. px = tx;
  101631. py = ty;
  101632. pz = tz;
  101633. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  101634. tx = px - pd * nx - cbx;
  101635. ty = py - pd * ny - cby;
  101636. tz = pz - pd * nz - cbz;
  101637. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  101638. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  101639. if (sd < -dir1l) sd = -dir1l;
  101640. else if (sd > dir1l) sd = dir1l;
  101641. if (ed < -dir2l) ed = -dir2l;
  101642. else if (ed > dir2l) ed = dir2l;
  101643. tx = sd * dir1x + ed * dir2x;
  101644. ty = sd * dir1y + ed * dir2y;
  101645. tz = sd * dir1z + ed * dir2z;
  101646. px = cbx + tx;
  101647. py = cby + ty;
  101648. pz = cbz + tz;
  101649. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  101650. px = dx * r00 + dy * r01 + dz * r02;
  101651. py = dx * r10 + dy * r11 + dz * r12;
  101652. pz = dx * r20 + dy * r21 + dz * r22;
  101653. px = (dx = px) + ccx;
  101654. py = (dy = py) + ccy;
  101655. pz = (dz = pz) + ccz;
  101656. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  101657. if (pd <= 0) {
  101658. tx = px - pd * nx - cbx;
  101659. ty = py - pd * ny - cby;
  101660. tz = pz - pd * nz - cbz;
  101661. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  101662. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  101663. if (sd < -dir1l) sd = -dir1l;
  101664. else if (sd > dir1l) sd = dir1l;
  101665. if (ed < -dir2l) ed = -dir2l;
  101666. else if (ed > dir2l) ed = dir2l;
  101667. tx = sd * dir1x + ed * dir2x;
  101668. ty = sd * dir1y + ed * dir2y;
  101669. tz = sd * dir1z + ed * dir2z;
  101670. px = cbx + tx;
  101671. py = cby + ty;
  101672. pz = cbz + tz;
  101673. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,2,0,false);
  101674. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  101675. }
  101676. px = dx * r00 + dy * r01 + dz * r02;
  101677. py = dx * r10 + dy * r11 + dz * r12;
  101678. pz = dx * r20 + dy * r21 + dz * r22;
  101679. px = (dx = px) + ccx;
  101680. py = (dy = py) + ccy;
  101681. pz = (dz = pz) + ccz;
  101682. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  101683. if (pd <= 0) {
  101684. tx = px - pd * nx - cbx;
  101685. ty = py - pd * ny - cby;
  101686. tz = pz - pd * nz - cbz;
  101687. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  101688. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  101689. if (sd < -dir1l) sd = -dir1l;
  101690. else if (sd > dir1l) sd = dir1l;
  101691. if (ed < -dir2l) ed = -dir2l;
  101692. else if (ed > dir2l) ed = dir2l;
  101693. tx = sd * dir1x + ed * dir2x;
  101694. ty = sd * dir1y + ed * dir2y;
  101695. tz = sd * dir1z + ed * dir2z;
  101696. px = cbx + tx;
  101697. py = cby + ty;
  101698. pz = cbz + tz;
  101699. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,3,0,false);
  101700. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  101701. }
  101702. } else {
  101703. sx = tx;
  101704. sy = ty;
  101705. sz = tz;
  101706. sd = nx * (sx - cbx) + ny * (sy - cby) + nz * (sz - cbz);
  101707. sx -= sd * nx;
  101708. sy -= sd * ny;
  101709. sz -= sd * nz;
  101710. if (dot > 0) {
  101711. ex = tx + dcx * 2;
  101712. ey = ty + dcy * 2;
  101713. ez = tz + dcz * 2;
  101714. } else {
  101715. ex = tx - dcx * 2;
  101716. ey = ty - dcy * 2;
  101717. ez = tz - dcz * 2;
  101718. }
  101719. ed = nx * (ex - cbx) + ny * (ey - cby) + nz * (ez - cbz);
  101720. ex -= ed * nx;
  101721. ey -= ed * ny;
  101722. ez -= ed * nz;
  101723. d1x = sx - cbx;
  101724. d1y = sy - cby;
  101725. d1z = sz - cbz;
  101726. d2x = ex - cbx;
  101727. d2y = ey - cby;
  101728. d2z = ez - cbz;
  101729. tx = ex - sx;
  101730. ty = ey - sy;
  101731. tz = ez - sz;
  101732. td = ed - sd;
  101733. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  101734. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  101735. dot1 = dotw - dir1l;
  101736. dot2 = doth - dir1l;
  101737. if (dot1 > 0) {
  101738. if (dot2 > 0) return;
  101739. t1 = dot1 / (dot1 - dot2);
  101740. sx = sx + tx * t1;
  101741. sy = sy + ty * t1;
  101742. sz = sz + tz * t1;
  101743. sd = sd + td * t1;
  101744. d1x = sx - cbx;
  101745. d1y = sy - cby;
  101746. d1z = sz - cbz;
  101747. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  101748. tx = ex - sx;
  101749. ty = ey - sy;
  101750. tz = ez - sz;
  101751. td = ed - sd;
  101752. } else if (dot2 > 0) {
  101753. t1 = dot1 / (dot1 - dot2);
  101754. ex = sx + tx * t1;
  101755. ey = sy + ty * t1;
  101756. ez = sz + tz * t1;
  101757. ed = sd + td * t1;
  101758. d2x = ex - cbx;
  101759. d2y = ey - cby;
  101760. d2z = ez - cbz;
  101761. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  101762. tx = ex - sx;
  101763. ty = ey - sy;
  101764. tz = ez - sz;
  101765. td = ed - sd;
  101766. }
  101767. dot1 = dotw + dir1l;
  101768. dot2 = doth + dir1l;
  101769. if (dot1 < 0) {
  101770. if (dot2 < 0) return;
  101771. t1 = dot1 / (dot1 - dot2);
  101772. sx = sx + tx * t1;
  101773. sy = sy + ty * t1;
  101774. sz = sz + tz * t1;
  101775. sd = sd + td * t1;
  101776. d1x = sx - cbx;
  101777. d1y = sy - cby;
  101778. d1z = sz - cbz;
  101779. tx = ex - sx;
  101780. ty = ey - sy;
  101781. tz = ez - sz;
  101782. td = ed - sd;
  101783. } else if (dot2 < 0) {
  101784. t1 = dot1 / (dot1 - dot2);
  101785. ex = sx + tx * t1;
  101786. ey = sy + ty * t1;
  101787. ez = sz + tz * t1;
  101788. ed = sd + td * t1;
  101789. d2x = ex - cbx;
  101790. d2y = ey - cby;
  101791. d2z = ez - cbz;
  101792. tx = ex - sx;
  101793. ty = ey - sy;
  101794. tz = ez - sz;
  101795. td = ed - sd;
  101796. }
  101797. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  101798. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  101799. dot1 = dotw - dir2l;
  101800. dot2 = doth - dir2l;
  101801. if (dot1 > 0) {
  101802. if (dot2 > 0) return;
  101803. t1 = dot1 / (dot1 - dot2);
  101804. sx = sx + tx * t1;
  101805. sy = sy + ty * t1;
  101806. sz = sz + tz * t1;
  101807. sd = sd + td * t1;
  101808. d1x = sx - cbx;
  101809. d1y = sy - cby;
  101810. d1z = sz - cbz;
  101811. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  101812. tx = ex - sx;
  101813. ty = ey - sy;
  101814. tz = ez - sz;
  101815. td = ed - sd;
  101816. } else if (dot2 > 0) {
  101817. t1 = dot1 / (dot1 - dot2);
  101818. ex = sx + tx * t1;
  101819. ey = sy + ty * t1;
  101820. ez = sz + tz * t1;
  101821. ed = sd + td * t1;
  101822. d2x = ex - cbx;
  101823. d2y = ey - cby;
  101824. d2z = ez - cbz;
  101825. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  101826. tx = ex - sx;
  101827. ty = ey - sy;
  101828. tz = ez - sz;
  101829. td = ed - sd;
  101830. }
  101831. dot1 = dotw + dir2l;
  101832. dot2 = doth + dir2l;
  101833. if (dot1 < 0) {
  101834. if (dot2 < 0) return;
  101835. t1 = dot1 / (dot1 - dot2);
  101836. sx = sx + tx * t1;
  101837. sy = sy + ty * t1;
  101838. sz = sz + tz * t1;
  101839. sd = sd + td * t1;
  101840. } else if (dot2 < 0) {
  101841. t1 = dot1 / (dot1 - dot2);
  101842. ex = sx + tx * t1;
  101843. ey = sy + ty * t1;
  101844. ez = sz + tz * t1;
  101845. ed = sd + td * t1;
  101846. }
  101847. if (sd < 0) {
  101848. //manifold.addPoint(sx,sy,sz,nx,ny,nz,sd,b,c,1,0,false);
  101849. manifold.addPoint(sx, sy, sz, nx, ny, nz, sd, this.flip);
  101850. }
  101851. if (ed < 0) {
  101852. //manifold.addPoint(ex,ey,ez,nx,ny,nz,ed,b,c,4,0,false);
  101853. manifold.addPoint(ex, ey, ez, nx, ny, nz, ed, this.flip);
  101854. }
  101855. }
  101856. }
  101857. };
  101858. OIMO.CylinderCylinderCollisionDetector = function () {
  101859. OIMO.CollisionDetector.call(this);
  101860. };
  101861. OIMO.CylinderCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  101862. OIMO.CylinderCylinderCollisionDetector.prototype.constructor = OIMO.CylinderCylinderCollisionDetector;
  101863. OIMO.CylinderCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  101864. var t1x;
  101865. var t1y;
  101866. var t1z;
  101867. var t2x;
  101868. var t2y;
  101869. var t2z;
  101870. var sup = new OIMO.Vec3();
  101871. var len;
  101872. var p1x;
  101873. var p1y;
  101874. var p1z;
  101875. var p2x;
  101876. var p2y;
  101877. var p2z;
  101878. var v01x = c1.position.x;
  101879. var v01y = c1.position.y;
  101880. var v01z = c1.position.z;
  101881. var v02x = c2.position.x;
  101882. var v02y = c2.position.y;
  101883. var v02z = c2.position.z;
  101884. var v0x = v02x - v01x;
  101885. var v0y = v02y - v01y;
  101886. var v0z = v02z - v01z;
  101887. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  101888. var nx = -v0x;
  101889. var ny = -v0y;
  101890. var nz = -v0z;
  101891. this.supportPoint(c1, -nx, -ny, -nz, sup);
  101892. var v11x = sup.x;
  101893. var v11y = sup.y;
  101894. var v11z = sup.z;
  101895. this.supportPoint(c2, nx, ny, nz, sup);
  101896. var v12x = sup.x;
  101897. var v12y = sup.y;
  101898. var v12z = sup.z;
  101899. var v1x = v12x - v11x;
  101900. var v1y = v12y - v11y;
  101901. var v1z = v12z - v11z;
  101902. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  101903. return false;
  101904. }
  101905. nx = v1y * v0z - v1z * v0y;
  101906. ny = v1z * v0x - v1x * v0z;
  101907. nz = v1x * v0y - v1y * v0x;
  101908. if (nx * nx + ny * ny + nz * nz == 0) {
  101909. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  101910. sep.normalize(sep);
  101911. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  101912. return true;
  101913. }
  101914. this.supportPoint(c1, -nx, -ny, -nz, sup);
  101915. var v21x = sup.x;
  101916. var v21y = sup.y;
  101917. var v21z = sup.z;
  101918. this.supportPoint(c2, nx, ny, nz, sup);
  101919. var v22x = sup.x;
  101920. var v22y = sup.y;
  101921. var v22z = sup.z;
  101922. var v2x = v22x - v21x;
  101923. var v2y = v22y - v21y;
  101924. var v2z = v22z - v21z;
  101925. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  101926. return false;
  101927. }
  101928. t1x = v1x - v0x;
  101929. t1y = v1y - v0y;
  101930. t1z = v1z - v0z;
  101931. t2x = v2x - v0x;
  101932. t2y = v2y - v0y;
  101933. t2z = v2z - v0z;
  101934. nx = t1y * t2z - t1z * t2y;
  101935. ny = t1z * t2x - t1x * t2z;
  101936. nz = t1x * t2y - t1y * t2x;
  101937. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  101938. t1x = v1x;
  101939. t1y = v1y;
  101940. t1z = v1z;
  101941. v1x = v2x;
  101942. v1y = v2y;
  101943. v1z = v2z;
  101944. v2x = t1x;
  101945. v2y = t1y;
  101946. v2z = t1z;
  101947. t1x = v11x;
  101948. t1y = v11y;
  101949. t1z = v11z;
  101950. v11x = v21x;
  101951. v11y = v21y;
  101952. v11z = v21z;
  101953. v21x = t1x;
  101954. v21y = t1y;
  101955. v21z = t1z;
  101956. t1x = v12x;
  101957. t1y = v12y;
  101958. t1z = v12z;
  101959. v12x = v22x;
  101960. v12y = v22y;
  101961. v12z = v22z;
  101962. v22x = t1x;
  101963. v22y = t1y;
  101964. v22z = t1z;
  101965. nx = -nx;
  101966. ny = -ny;
  101967. nz = -nz;
  101968. }
  101969. var iterations = 0;
  101970. while (true) {
  101971. if (++iterations > 100) {
  101972. return false;
  101973. }
  101974. this.supportPoint(c1, -nx, -ny, -nz, sup);
  101975. var v31x = sup.x;
  101976. var v31y = sup.y;
  101977. var v31z = sup.z;
  101978. this.supportPoint(c2, nx, ny, nz, sup);
  101979. var v32x = sup.x;
  101980. var v32y = sup.y;
  101981. var v32z = sup.z;
  101982. var v3x = v32x - v31x;
  101983. var v3y = v32y - v31y;
  101984. var v3z = v32z - v31z;
  101985. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  101986. return false;
  101987. }
  101988. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  101989. v2x = v3x;
  101990. v2y = v3y;
  101991. v2z = v3z;
  101992. v21x = v31x;
  101993. v21y = v31y;
  101994. v21z = v31z;
  101995. v22x = v32x;
  101996. v22y = v32y;
  101997. v22z = v32z;
  101998. t1x = v1x - v0x;
  101999. t1y = v1y - v0y;
  102000. t1z = v1z - v0z;
  102001. t2x = v3x - v0x;
  102002. t2y = v3y - v0y;
  102003. t2z = v3z - v0z;
  102004. nx = t1y * t2z - t1z * t2y;
  102005. ny = t1z * t2x - t1x * t2z;
  102006. nz = t1x * t2y - t1y * t2x;
  102007. continue;
  102008. }
  102009. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  102010. v1x = v3x;
  102011. v1y = v3y;
  102012. v1z = v3z;
  102013. v11x = v31x;
  102014. v11y = v31y;
  102015. v11z = v31z;
  102016. v12x = v32x;
  102017. v12y = v32y;
  102018. v12z = v32z;
  102019. t1x = v3x - v0x;
  102020. t1y = v3y - v0y;
  102021. t1z = v3z - v0z;
  102022. t2x = v2x - v0x;
  102023. t2y = v2y - v0y;
  102024. t2z = v2z - v0z;
  102025. nx = t1y * t2z - t1z * t2y;
  102026. ny = t1z * t2x - t1x * t2z;
  102027. nz = t1x * t2y - t1y * t2x;
  102028. continue;
  102029. }
  102030. var hit = false;
  102031. while (true) {
  102032. t1x = v2x - v1x;
  102033. t1y = v2y - v1y;
  102034. t1z = v2z - v1z;
  102035. t2x = v3x - v1x;
  102036. t2y = v3y - v1y;
  102037. t2z = v3z - v1z;
  102038. nx = t1y * t2z - t1z * t2y;
  102039. ny = t1z * t2x - t1x * t2z;
  102040. nz = t1x * t2y - t1y * t2x;
  102041. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  102042. nx *= len;
  102043. ny *= len;
  102044. nz *= len;
  102045. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  102046. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  102047. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  102048. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  102049. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  102050. var sum = b0 + b1 + b2 + b3;
  102051. if (sum <= 0) {
  102052. b0 = 0;
  102053. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  102054. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  102055. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  102056. sum = b1 + b2 + b3;
  102057. }
  102058. var inv = 1 / sum;
  102059. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  102060. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  102061. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  102062. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  102063. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  102064. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  102065. hit = true;
  102066. }
  102067. this.supportPoint(c1, -nx, -ny, -nz, sup);
  102068. var v41x = sup.x;
  102069. var v41y = sup.y;
  102070. var v41z = sup.z;
  102071. this.supportPoint(c2, nx, ny, nz, sup);
  102072. var v42x = sup.x;
  102073. var v42y = sup.y;
  102074. var v42z = sup.z;
  102075. var v4x = v42x - v41x;
  102076. var v4y = v42y - v41y;
  102077. var v4z = v42z - v41z;
  102078. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  102079. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  102080. if (hit) {
  102081. sep.init(-nx, -ny, -nz);
  102082. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  102083. dep.x = separation;
  102084. return true;
  102085. }
  102086. return false;
  102087. }
  102088. if (
  102089. (v4y * v1z - v4z * v1y) * v0x +
  102090. (v4z * v1x - v4x * v1z) * v0y +
  102091. (v4x * v1y - v4y * v1x) * v0z < 0
  102092. ) {
  102093. if (
  102094. (v4y * v2z - v4z * v2y) * v0x +
  102095. (v4z * v2x - v4x * v2z) * v0y +
  102096. (v4x * v2y - v4y * v2x) * v0z < 0
  102097. ) {
  102098. v1x = v4x;
  102099. v1y = v4y;
  102100. v1z = v4z;
  102101. v11x = v41x;
  102102. v11y = v41y;
  102103. v11z = v41z;
  102104. v12x = v42x;
  102105. v12y = v42y;
  102106. v12z = v42z;
  102107. } else {
  102108. v3x = v4x;
  102109. v3y = v4y;
  102110. v3z = v4z;
  102111. v31x = v41x;
  102112. v31y = v41y;
  102113. v31z = v41z;
  102114. v32x = v42x;
  102115. v32y = v42y;
  102116. v32z = v42z;
  102117. }
  102118. } else {
  102119. if (
  102120. (v4y * v3z - v4z * v3y) * v0x +
  102121. (v4z * v3x - v4x * v3z) * v0y +
  102122. (v4x * v3y - v4y * v3x) * v0z < 0
  102123. ) {
  102124. v2x = v4x;
  102125. v2y = v4y;
  102126. v2z = v4z;
  102127. v21x = v41x;
  102128. v21y = v41y;
  102129. v21z = v41z;
  102130. v22x = v42x;
  102131. v22y = v42y;
  102132. v22z = v42z;
  102133. } else {
  102134. v1x = v4x;
  102135. v1y = v4y;
  102136. v1z = v4z;
  102137. v11x = v41x;
  102138. v11y = v41y;
  102139. v11z = v41z;
  102140. v12x = v42x;
  102141. v12y = v42y;
  102142. v12z = v42z;
  102143. }
  102144. }
  102145. }
  102146. }
  102147. //return false;
  102148. };
  102149. OIMO.CylinderCylinderCollisionDetector.prototype.supportPoint = function (c, dx, dy, dz, out) {
  102150. var rot = c.rotation.elements;
  102151. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  102152. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  102153. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  102154. var radx = ldx;
  102155. var radz = ldz;
  102156. var len = radx * radx + radz * radz;
  102157. var rad = c.radius;
  102158. var hh = c.halfHeight;
  102159. var ox;
  102160. var oy;
  102161. var oz;
  102162. if (len == 0) {
  102163. if (ldy < 0) {
  102164. ox = rad;
  102165. oy = -hh;
  102166. oz = 0;
  102167. } else {
  102168. ox = rad;
  102169. oy = hh;
  102170. oz = 0;
  102171. }
  102172. } else {
  102173. len = c.radius / OIMO.sqrt(len);
  102174. if (ldy < 0) {
  102175. ox = radx * len;
  102176. oy = -hh;
  102177. oz = radz * len;
  102178. } else {
  102179. ox = radx * len;
  102180. oy = hh;
  102181. oz = radz * len;
  102182. }
  102183. }
  102184. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  102185. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  102186. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  102187. out.init(ldx, ldy, ldz);
  102188. };
  102189. OIMO.CylinderCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  102190. var c1;
  102191. var c2;
  102192. if (shape1.id < shape2.id) {
  102193. c1 = shape1;
  102194. c2 = shape2;
  102195. } else {
  102196. c1 = shape2;
  102197. c2 = shape1;
  102198. }
  102199. var p1 = c1.position;
  102200. var p2 = c2.position;
  102201. var p1x = p1.x;
  102202. var p1y = p1.y;
  102203. var p1z = p1.z;
  102204. var p2x = p2.x;
  102205. var p2y = p2.y;
  102206. var p2z = p2.z;
  102207. var h1 = c1.halfHeight;
  102208. var h2 = c2.halfHeight;
  102209. var n1 = c1.normalDirection;
  102210. var n2 = c2.normalDirection;
  102211. var d1 = c1.halfDirection;
  102212. var d2 = c2.halfDirection;
  102213. var r1 = c1.radius;
  102214. var r2 = c2.radius;
  102215. var n1x = n1.x;
  102216. var n1y = n1.y;
  102217. var n1z = n1.z;
  102218. var n2x = n2.x;
  102219. var n2y = n2.y;
  102220. var n2z = n2.z;
  102221. var d1x = d1.x;
  102222. var d1y = d1.y;
  102223. var d1z = d1.z;
  102224. var d2x = d2.x;
  102225. var d2y = d2.y;
  102226. var d2z = d2.z;
  102227. var dx = p1x - p2x;
  102228. var dy = p1y - p2y;
  102229. var dz = p1z - p2z;
  102230. var len;
  102231. var len1;
  102232. var len2;
  102233. var c;
  102234. var c1x;
  102235. var c1y;
  102236. var c1z;
  102237. var c2x;
  102238. var c2y;
  102239. var c2z;
  102240. var tx;
  102241. var ty;
  102242. var tz;
  102243. var sx;
  102244. var sy;
  102245. var sz;
  102246. var ex;
  102247. var ey;
  102248. var ez;
  102249. var depth1;
  102250. var depth2;
  102251. var dot;
  102252. var t1;
  102253. var t2;
  102254. var sep = new OIMO.Vec3();
  102255. var pos = new OIMO.Vec3();
  102256. var dep = new OIMO.Vec3();
  102257. if (!this.getSep(c1, c2, sep, pos, dep)) return;
  102258. var dot1 = sep.x * n1x + sep.y * n1y + sep.z * n1z;
  102259. var dot2 = sep.x * n2x + sep.y * n2y + sep.z * n2z;
  102260. var right1 = dot1 > 0;
  102261. var right2 = dot2 > 0;
  102262. if (!right1) dot1 = -dot1;
  102263. if (!right2) dot2 = -dot2;
  102264. var state = 0;
  102265. if (dot1 > 0.999 || dot2 > 0.999) {
  102266. if (dot1 > dot2) state = 1;
  102267. else state = 2;
  102268. }
  102269. var nx;
  102270. var ny;
  102271. var nz;
  102272. var depth = dep.x;
  102273. var r00;
  102274. var r01;
  102275. var r02;
  102276. var r10;
  102277. var r11;
  102278. var r12;
  102279. var r20;
  102280. var r21;
  102281. var r22;
  102282. var px;
  102283. var py;
  102284. var pz;
  102285. var pd;
  102286. var a;
  102287. var b;
  102288. var e;
  102289. var f;
  102290. nx = sep.x;
  102291. ny = sep.y;
  102292. nz = sep.z;
  102293. switch (state) {
  102294. case 0:
  102295. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, depth, false);
  102296. break;
  102297. case 1:
  102298. if (right1) {
  102299. c1x = p1x + d1x;
  102300. c1y = p1y + d1y;
  102301. c1z = p1z + d1z;
  102302. nx = n1x;
  102303. ny = n1y;
  102304. nz = n1z;
  102305. } else {
  102306. c1x = p1x - d1x;
  102307. c1y = p1y - d1y;
  102308. c1z = p1z - d1z;
  102309. nx = -n1x;
  102310. ny = -n1y;
  102311. nz = -n1z;
  102312. }
  102313. dot = nx * n2x + ny * n2y + nz * n2z;
  102314. if (dot < 0) len = h2;
  102315. else len = -h2;
  102316. c2x = p2x + len * n2x;
  102317. c2y = p2y + len * n2y;
  102318. c2z = p2z + len * n2z;
  102319. if (dot2 >= 0.999999) {
  102320. tx = -ny;
  102321. ty = nz;
  102322. tz = nx;
  102323. } else {
  102324. tx = nx;
  102325. ty = ny;
  102326. tz = nz;
  102327. }
  102328. len = tx * n2x + ty * n2y + tz * n2z;
  102329. dx = len * n2x - tx;
  102330. dy = len * n2y - ty;
  102331. dz = len * n2z - tz;
  102332. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  102333. if (len == 0) break;
  102334. len = r2 / len;
  102335. dx *= len;
  102336. dy *= len;
  102337. dz *= len;
  102338. tx = c2x + dx;
  102339. ty = c2y + dy;
  102340. tz = c2z + dz;
  102341. if (dot < -0.96 || dot > 0.96) {
  102342. r00 = n2x * n2x * 1.5 - 0.5;
  102343. r01 = n2x * n2y * 1.5 - n2z * 0.866025403;
  102344. r02 = n2x * n2z * 1.5 + n2y * 0.866025403;
  102345. r10 = n2y * n2x * 1.5 + n2z * 0.866025403;
  102346. r11 = n2y * n2y * 1.5 - 0.5;
  102347. r12 = n2y * n2z * 1.5 - n2x * 0.866025403;
  102348. r20 = n2z * n2x * 1.5 - n2y * 0.866025403;
  102349. r21 = n2z * n2y * 1.5 + n2x * 0.866025403;
  102350. r22 = n2z * n2z * 1.5 - 0.5;
  102351. px = tx;
  102352. py = ty;
  102353. pz = tz;
  102354. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  102355. tx = px - pd * nx - c1x;
  102356. ty = py - pd * ny - c1y;
  102357. tz = pz - pd * nz - c1z;
  102358. len = tx * tx + ty * ty + tz * tz;
  102359. if (len > r1 * r1) {
  102360. len = r1 / OIMO.sqrt(len);
  102361. tx *= len;
  102362. ty *= len;
  102363. tz *= len;
  102364. }
  102365. px = c1x + tx;
  102366. py = c1y + ty;
  102367. pz = c1z + tz;
  102368. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  102369. px = dx * r00 + dy * r01 + dz * r02;
  102370. py = dx * r10 + dy * r11 + dz * r12;
  102371. pz = dx * r20 + dy * r21 + dz * r22;
  102372. px = (dx = px) + c2x;
  102373. py = (dy = py) + c2y;
  102374. pz = (dz = pz) + c2z;
  102375. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  102376. if (pd <= 0) {
  102377. tx = px - pd * nx - c1x;
  102378. ty = py - pd * ny - c1y;
  102379. tz = pz - pd * nz - c1z;
  102380. len = tx * tx + ty * ty + tz * tz;
  102381. if (len > r1 * r1) {
  102382. len = r1 / OIMO.sqrt(len);
  102383. tx *= len;
  102384. ty *= len;
  102385. tz *= len;
  102386. }
  102387. px = c1x + tx;
  102388. py = c1y + ty;
  102389. pz = c1z + tz;
  102390. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  102391. }
  102392. px = dx * r00 + dy * r01 + dz * r02;
  102393. py = dx * r10 + dy * r11 + dz * r12;
  102394. pz = dx * r20 + dy * r21 + dz * r22;
  102395. px = (dx = px) + c2x;
  102396. py = (dy = py) + c2y;
  102397. pz = (dz = pz) + c2z;
  102398. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  102399. if (pd <= 0) {
  102400. tx = px - pd * nx - c1x;
  102401. ty = py - pd * ny - c1y;
  102402. tz = pz - pd * nz - c1z;
  102403. len = tx * tx + ty * ty + tz * tz;
  102404. if (len > r1 * r1) {
  102405. len = r1 / OIMO.sqrt(len);
  102406. tx *= len;
  102407. ty *= len;
  102408. tz *= len;
  102409. }
  102410. px = c1x + tx;
  102411. py = c1y + ty;
  102412. pz = c1z + tz;
  102413. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  102414. }
  102415. } else {
  102416. sx = tx;
  102417. sy = ty;
  102418. sz = tz;
  102419. depth1 = nx * (sx - c1x) + ny * (sy - c1y) + nz * (sz - c1z);
  102420. sx -= depth1 * nx;
  102421. sy -= depth1 * ny;
  102422. sz -= depth1 * nz;
  102423. if (dot > 0) {
  102424. ex = tx + n2x * h2 * 2;
  102425. ey = ty + n2y * h2 * 2;
  102426. ez = tz + n2z * h2 * 2;
  102427. } else {
  102428. ex = tx - n2x * h2 * 2;
  102429. ey = ty - n2y * h2 * 2;
  102430. ez = tz - n2z * h2 * 2;
  102431. }
  102432. depth2 = nx * (ex - c1x) + ny * (ey - c1y) + nz * (ez - c1z);
  102433. ex -= depth2 * nx;
  102434. ey -= depth2 * ny;
  102435. ez -= depth2 * nz;
  102436. dx = c1x - sx;
  102437. dy = c1y - sy;
  102438. dz = c1z - sz;
  102439. tx = ex - sx;
  102440. ty = ey - sy;
  102441. tz = ez - sz;
  102442. a = dx * dx + dy * dy + dz * dz;
  102443. b = dx * tx + dy * ty + dz * tz;
  102444. e = tx * tx + ty * ty + tz * tz;
  102445. f = b * b - e * (a - r1 * r1);
  102446. if (f < 0) break;
  102447. f = OIMO.sqrt(f);
  102448. t1 = (b + f) / e;
  102449. t2 = (b - f) / e;
  102450. if (t2 < t1) {
  102451. len = t1;
  102452. t1 = t2;
  102453. t2 = len;
  102454. }
  102455. if (t2 > 1) t2 = 1;
  102456. if (t1 < 0) t1 = 0;
  102457. tx = sx + (ex - sx) * t1;
  102458. ty = sy + (ey - sy) * t1;
  102459. tz = sz + (ez - sz) * t1;
  102460. ex = sx + (ex - sx) * t2;
  102461. ey = sy + (ey - sy) * t2;
  102462. ez = sz + (ez - sz) * t2;
  102463. sx = tx;
  102464. sy = ty;
  102465. sz = tz;
  102466. len = depth1 + (depth2 - depth1) * t1;
  102467. depth2 = depth1 + (depth2 - depth1) * t2;
  102468. depth1 = len;
  102469. if (depth1 < 0) manifold.addPoint(sx, sy, sz, nx, ny, nz, pd, false);
  102470. if (depth2 < 0) manifold.addPoint(ex, ey, ez, nx, ny, nz, pd, false);
  102471. }
  102472. break;
  102473. case 2:
  102474. if (right2) {
  102475. c2x = p2x - d2x;
  102476. c2y = p2y - d2y;
  102477. c2z = p2z - d2z;
  102478. nx = -n2x;
  102479. ny = -n2y;
  102480. nz = -n2z;
  102481. } else {
  102482. c2x = p2x + d2x;
  102483. c2y = p2y + d2y;
  102484. c2z = p2z + d2z;
  102485. nx = n2x;
  102486. ny = n2y;
  102487. nz = n2z;
  102488. }
  102489. dot = nx * n1x + ny * n1y + nz * n1z;
  102490. if (dot < 0) len = h1;
  102491. else len = -h1;
  102492. c1x = p1x + len * n1x;
  102493. c1y = p1y + len * n1y;
  102494. c1z = p1z + len * n1z;
  102495. if (dot1 >= 0.999999) {
  102496. tx = -ny;
  102497. ty = nz;
  102498. tz = nx;
  102499. } else {
  102500. tx = nx;
  102501. ty = ny;
  102502. tz = nz;
  102503. }
  102504. len = tx * n1x + ty * n1y + tz * n1z;
  102505. dx = len * n1x - tx;
  102506. dy = len * n1y - ty;
  102507. dz = len * n1z - tz;
  102508. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  102509. if (len == 0) break;
  102510. len = r1 / len;
  102511. dx *= len;
  102512. dy *= len;
  102513. dz *= len;
  102514. tx = c1x + dx;
  102515. ty = c1y + dy;
  102516. tz = c1z + dz;
  102517. if (dot < -0.96 || dot > 0.96) {
  102518. r00 = n1x * n1x * 1.5 - 0.5;
  102519. r01 = n1x * n1y * 1.5 - n1z * 0.866025403;
  102520. r02 = n1x * n1z * 1.5 + n1y * 0.866025403;
  102521. r10 = n1y * n1x * 1.5 + n1z * 0.866025403;
  102522. r11 = n1y * n1y * 1.5 - 0.5;
  102523. r12 = n1y * n1z * 1.5 - n1x * 0.866025403;
  102524. r20 = n1z * n1x * 1.5 - n1y * 0.866025403;
  102525. r21 = n1z * n1y * 1.5 + n1x * 0.866025403;
  102526. r22 = n1z * n1z * 1.5 - 0.5;
  102527. px = tx;
  102528. py = ty;
  102529. pz = tz;
  102530. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  102531. tx = px - pd * nx - c2x;
  102532. ty = py - pd * ny - c2y;
  102533. tz = pz - pd * nz - c2z;
  102534. len = tx * tx + ty * ty + tz * tz;
  102535. if (len > r2 * r2) {
  102536. len = r2 / OIMO.sqrt(len);
  102537. tx *= len;
  102538. ty *= len;
  102539. tz *= len;
  102540. }
  102541. px = c2x + tx;
  102542. py = c2y + ty;
  102543. pz = c2z + tz;
  102544. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  102545. px = dx * r00 + dy * r01 + dz * r02;
  102546. py = dx * r10 + dy * r11 + dz * r12;
  102547. pz = dx * r20 + dy * r21 + dz * r22;
  102548. px = (dx = px) + c1x;
  102549. py = (dy = py) + c1y;
  102550. pz = (dz = pz) + c1z;
  102551. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  102552. if (pd <= 0) {
  102553. tx = px - pd * nx - c2x;
  102554. ty = py - pd * ny - c2y;
  102555. tz = pz - pd * nz - c2z;
  102556. len = tx * tx + ty * ty + tz * tz;
  102557. if (len > r2 * r2) {
  102558. len = r2 / OIMO.sqrt(len);
  102559. tx *= len;
  102560. ty *= len;
  102561. tz *= len;
  102562. }
  102563. px = c2x + tx;
  102564. py = c2y + ty;
  102565. pz = c2z + tz;
  102566. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  102567. }
  102568. px = dx * r00 + dy * r01 + dz * r02;
  102569. py = dx * r10 + dy * r11 + dz * r12;
  102570. pz = dx * r20 + dy * r21 + dz * r22;
  102571. px = (dx = px) + c1x;
  102572. py = (dy = py) + c1y;
  102573. pz = (dz = pz) + c1z;
  102574. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  102575. if (pd <= 0) {
  102576. tx = px - pd * nx - c2x;
  102577. ty = py - pd * ny - c2y;
  102578. tz = pz - pd * nz - c2z;
  102579. len = tx * tx + ty * ty + tz * tz;
  102580. if (len > r2 * r2) {
  102581. len = r2 / OIMO.sqrt(len);
  102582. tx *= len;
  102583. ty *= len;
  102584. tz *= len;
  102585. }
  102586. px = c2x + tx;
  102587. py = c2y + ty;
  102588. pz = c2z + tz;
  102589. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  102590. }
  102591. } else {
  102592. sx = tx;
  102593. sy = ty;
  102594. sz = tz;
  102595. depth1 = nx * (sx - c2x) + ny * (sy - c2y) + nz * (sz - c2z);
  102596. sx -= depth1 * nx;
  102597. sy -= depth1 * ny;
  102598. sz -= depth1 * nz;
  102599. if (dot > 0) {
  102600. ex = tx + n1x * h1 * 2;
  102601. ey = ty + n1y * h1 * 2;
  102602. ez = tz + n1z * h1 * 2;
  102603. } else {
  102604. ex = tx - n1x * h1 * 2;
  102605. ey = ty - n1y * h1 * 2;
  102606. ez = tz - n1z * h1 * 2;
  102607. }
  102608. depth2 = nx * (ex - c2x) + ny * (ey - c2y) + nz * (ez - c2z);
  102609. ex -= depth2 * nx;
  102610. ey -= depth2 * ny;
  102611. ez -= depth2 * nz;
  102612. dx = c2x - sx;
  102613. dy = c2y - sy;
  102614. dz = c2z - sz;
  102615. tx = ex - sx;
  102616. ty = ey - sy;
  102617. tz = ez - sz;
  102618. a = dx * dx + dy * dy + dz * dz;
  102619. b = dx * tx + dy * ty + dz * tz;
  102620. e = tx * tx + ty * ty + tz * tz;
  102621. f = b * b - e * (a - r2 * r2);
  102622. if (f < 0) break;
  102623. f = OIMO.sqrt(f);
  102624. t1 = (b + f) / e;
  102625. t2 = (b - f) / e;
  102626. if (t2 < t1) {
  102627. len = t1;
  102628. t1 = t2;
  102629. t2 = len;
  102630. }
  102631. if (t2 > 1) t2 = 1;
  102632. if (t1 < 0) t1 = 0;
  102633. tx = sx + (ex - sx) * t1;
  102634. ty = sy + (ey - sy) * t1;
  102635. tz = sz + (ez - sz) * t1;
  102636. ex = sx + (ex - sx) * t2;
  102637. ey = sy + (ey - sy) * t2;
  102638. ez = sz + (ez - sz) * t2;
  102639. sx = tx;
  102640. sy = ty;
  102641. sz = tz;
  102642. len = depth1 + (depth2 - depth1) * t1;
  102643. depth2 = depth1 + (depth2 - depth1) * t2;
  102644. depth1 = len;
  102645. if (depth1 < 0) {
  102646. manifold.addPoint(sx, sy, sz, -nx, -ny, -nz, depth1, false);
  102647. }
  102648. if (depth2 < 0) {
  102649. manifold.addPoint(ex, ey, ez, -nx, -ny, -nz, depth2, false);
  102650. }
  102651. }
  102652. break;
  102653. }
  102654. };
  102655. OIMO.SphereCylinderCollisionDetector = function (flip) {
  102656. OIMO.CollisionDetector.call(this);
  102657. this.flip = flip;
  102658. };
  102659. OIMO.SphereCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  102660. OIMO.SphereCylinderCollisionDetector.prototype.constructor = OIMO.SphereCylinderCollisionDetector;
  102661. OIMO.SphereCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  102662. var s;
  102663. var c;
  102664. if (this.flip) {
  102665. s = shape2;
  102666. c = shape1;
  102667. } else {
  102668. s = shape1;
  102669. c = shape2;
  102670. }
  102671. var ps = s.position;
  102672. var psx = ps.x;
  102673. var psy = ps.y;
  102674. var psz = ps.z;
  102675. var pc = c.position;
  102676. var pcx = pc.x;
  102677. var pcy = pc.y;
  102678. var pcz = pc.z;
  102679. var dirx = c.normalDirection.x;
  102680. var diry = c.normalDirection.y;
  102681. var dirz = c.normalDirection.z;
  102682. var rads = s.radius;
  102683. var radc = c.radius;
  102684. var rad2 = rads + radc;
  102685. var halfh = c.halfHeight;
  102686. var dx = psx - pcx;
  102687. var dy = psy - pcy;
  102688. var dz = psz - pcz;
  102689. var dot = dx * dirx + dy * diry + dz * dirz;
  102690. if (dot < -halfh - rads || dot > halfh + rads) return;
  102691. var cx = pcx + dot * dirx;
  102692. var cy = pcy + dot * diry;
  102693. var cz = pcz + dot * dirz;
  102694. var d2x = psx - cx;
  102695. var d2y = psy - cy;
  102696. var d2z = psz - cz;
  102697. var len = d2x * d2x + d2y * d2y + d2z * d2z;
  102698. if (len > rad2 * rad2) return;
  102699. if (len > radc * radc) {
  102700. len = radc / OIMO.sqrt(len);
  102701. d2x *= len;
  102702. d2y *= len;
  102703. d2z *= len;
  102704. }
  102705. if (dot < -halfh) dot = -halfh;
  102706. else if (dot > halfh) dot = halfh;
  102707. cx = pcx + dot * dirx + d2x;
  102708. cy = pcy + dot * diry + d2y;
  102709. cz = pcz + dot * dirz + d2z;
  102710. dx = cx - psx;
  102711. dy = cy - psy;
  102712. dz = cz - psz;
  102713. len = dx * dx + dy * dy + dz * dz;
  102714. var invLen;
  102715. if (len > 0 && len < rads * rads) {
  102716. len = OIMO.sqrt(len);
  102717. invLen = 1 / len;
  102718. dx *= invLen;
  102719. dy *= invLen;
  102720. dz *= invLen;
  102721. ///result.addContactInfo(psx+dx*rads,psy+dy*rads,psz+dz*rads,dx,dy,dz,len-rads,s,c,0,0,false);
  102722. manifold.addPoint(psx + dx * rads, psy + dy * rads, psz + dz * rads, dx, dy, dz, len - rads, this.flip);
  102723. }
  102724. };
  102725. /**
  102726. * Class for checking collisions between 2 tetras,
  102727. * a shape that is made with 4 vertices and 4 faces
  102728. * arranged in triangles. With this algorigthm, soft
  102729. * body physics are possible and easier to implement.
  102730. * @author xprogram
  102731. */
  102732. OIMO.TetraTetraCollisionDetector = function () {
  102733. OIMO.CollisionDetector.call(this);
  102734. };
  102735. OIMO.TetraTetraCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  102736. OIMO.TetraTetraCollisionDetector.prototype.constructor = OIMO.TetraTetraCollisionDetector;
  102737. OIMO.TetraTetraCollisionDetector.prototype.detectCollision = function (tet1, tet2, manifold) {
  102738. /*
  102739. * What we are doing:
  102740. * Each tetra is represented by four 3D triangles. The only
  102741. * quick way of finding if another tetra is within the other
  102742. * tetra is to see if a single vertex is within the triangles
  102743. * of the other tetra. So, for example, a tetra is represented
  102744. * by points B, C, D and E with triangles BCD, BCE, DCE and BDE.
  102745. * There is another tetra with a vertex A which was detected for
  102746. * collision by the broadphase. Now, if the point A is between ALL
  102747. * triangles of the other tetra (BCD, BCE, etc.) then the collision
  102748. * is valid and we can pass point A to the manifold. Since the only
  102749. * points on the tetra are the 4 vertices, collision detection is
  102750. * not so complex. However, it can be time-consuming because we
  102751. * need to split the 3D triangles into three 2D triangles each for
  102752. * collision detection.
  102753. */
  102754. var i, j, vec, fs1 = tet1.faces, vs1 = tet1.verts, fs2 = tet2.faces, vs2 = tet2.verts;
  102755. var j1, j2, j3, ts = 0; // Triangle vertices `j1`, `j2` and `j3`
  102756. // fs is undeclared
  102757. var fs = fs1;
  102758. for (i = 0; i < 4; i++) {
  102759. vec = vs1[i];
  102760. for (j = 0; j < 4; j++) {
  102761. j1 = vs2[fs[i].a];
  102762. j2 = vs2[fs[i].b];
  102763. j3 = vs2[fs[i].c];
  102764. if (
  102765. tricheck(pt(vec.x, vec.y), pt(j1.x, j1.y), pt(j2.x, j2.y), pt(j3.x, j3.y)) &&
  102766. tricheck(pt(vec.x, vec.z), pt(j1.x, j1.z), pt(j2.x, j2.z), pt(j3.x, j3.z)) &&
  102767. tricheck(pt(vec.z, vec.y), pt(j1.z, j1.y), pt(j2.z, j2.y), pt(j3.z, j3.y))
  102768. )
  102769. ts++;
  102770. if (ts === 4) // Only add point if it is inside all 4 triangles
  102771. manifold.addPoint(vec);
  102772. }
  102773. }
  102774. };
  102775. // Taken from: http://jsfiddle.net/PerroAZUL/zdaY8/1/
  102776. function tricheck(p, p0, p1, p2) {
  102777. var A = 0.5 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  102778. var sg = A < 0 ? -1 : 1;
  102779. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sg;
  102780. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sg;
  102781. return s > 0 && t > 0 && (s + t) < 2 * A * sg;
  102782. }
  102783. function pt(x, y) { return { x: x, y: y }; }
  102784. /**
  102785. * An axis-aligned bounding box.
  102786. * @author saharan
  102787. * @author lo-th
  102788. */
  102789. OIMO.AABB = function (minX, maxX, minY, maxY, minZ, maxZ) {
  102790. this.elements = new OIMO_ARRAY_TYPE(6);
  102791. var te = this.elements;
  102792. te[0] = minX || 0; te[1] = minY || 0; te[2] = minZ || 0;
  102793. te[3] = maxX || 0; te[4] = maxY || 0; te[5] = maxZ || 0;
  102794. };
  102795. OIMO.AABB.prototype = {
  102796. constructor: OIMO.AABB,
  102797. set: function (minX, maxX, minY, maxY, minZ, maxZ) {
  102798. var te = this.elements;
  102799. te[0] = minX; te[3] = maxX;
  102800. te[1] = minY; te[4] = maxY;
  102801. te[2] = minZ; te[5] = maxZ;
  102802. return this;
  102803. },
  102804. intersectTest: function (aabb) {
  102805. var te = this.elements;
  102806. var ue = aabb.elements;
  102807. 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];
  102808. },
  102809. intersectTestTwo: function (aabb) {
  102810. var te = this.elements;
  102811. var ue = aabb.elements;
  102812. 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];
  102813. },
  102814. clone: function () {
  102815. return new this.constructor().fromArray(this.elements);
  102816. },
  102817. copy: function (aabb, margin) {
  102818. var m = margin || 0;
  102819. var me = aabb.elements;
  102820. this.set(me[0] - m, me[3] + m, me[1] - m, me[4] + m, me[2] - m, me[5] + m);
  102821. return this;
  102822. },
  102823. fromArray: function (array) {
  102824. this.elements.set(array);
  102825. return this;
  102826. },
  102827. // Set this AABB to the combined AABB of aabb1 and aabb2.
  102828. combine: function (aabb1, aabb2) {
  102829. var a = aabb1.elements;
  102830. var b = aabb2.elements;
  102831. var te = this.elements;
  102832. te[0] = a[0] < b[0] ? a[0] : b[0];
  102833. te[1] = a[1] < b[1] ? a[1] : b[1];
  102834. te[2] = a[2] < b[2] ? a[2] : b[2];
  102835. te[3] = a[3] > b[3] ? a[3] : b[3];
  102836. te[4] = a[4] > b[4] ? a[4] : b[4];
  102837. te[5] = a[5] > b[5] ? a[5] : b[5];
  102838. return this;
  102839. },
  102840. // Get the surface area.
  102841. surfaceArea: function () {
  102842. var te = this.elements;
  102843. var a = te[3] - te[0];
  102844. var h = te[4] - te[1];
  102845. var d = te[5] - te[2];
  102846. return 2 * (a * (h + d) + h * d);
  102847. },
  102848. // Get whether the AABB intersects with the point or not.
  102849. intersectsWithPoint: function (x, y, z) {
  102850. var te = this.elements;
  102851. return x >= te[0] && x <= te[3] && y >= te[1] && y <= te[4] && z >= te[2] && z <= te[5];
  102852. },
  102853. /**
  102854. * Set the AABB from an array
  102855. * of vertices. From THREE.
  102856. * @author mrdoob
  102857. * @author xprogram
  102858. */
  102859. setFromPoints: function (arr) {
  102860. this.makeEmpty();
  102861. for (var i = 0; i < arr.length; i++) {
  102862. this.expandByPoint(arr[i]);
  102863. }
  102864. },
  102865. makeEmpty: function () {
  102866. this.set(-Infinity, -Infinity, -Infinity, Infinity, Infinity, Infinity);
  102867. },
  102868. expandByPoint: function (pt) {
  102869. var te = this.elements;
  102870. this.set(
  102871. OIMO.min(te[0], pt.x), OIMO.min(te[1], pt.y), OIMO.min(te[2], pt.z),
  102872. OIMO.max(te[3], pt.x), OIMO.max(te[4], pt.y), OIMO.max(te[5], pt.z)
  102873. );
  102874. }
  102875. };
  102876. /**
  102877. * A proxy is used for broad-phase collecting pairs that can be colliding.
  102878. */
  102879. OIMO.Proxy = function (shape) {
  102880. // The parent shape.
  102881. this.shape = shape;
  102882. // The axis-aligned bounding box.
  102883. this.aabb = shape.aabb;
  102884. };
  102885. OIMO.Proxy.prototype = {
  102886. constructor: OIMO.Proxy,
  102887. // Update the proxy.
  102888. update: function () {
  102889. OIMO.Error("Proxy", "Inheritance error.");
  102890. }
  102891. };
  102892. /**
  102893. * A basic implementation of proxies.
  102894. * @author saharan
  102895. */
  102896. OIMO.BasicProxy = function (shape) {
  102897. OIMO.Proxy.call(this, shape);
  102898. this.id = OIMO.proxyID++;
  102899. };
  102900. OIMO.BasicProxy.prototype = Object.create(OIMO.Proxy.prototype);
  102901. OIMO.BasicProxy.prototype.constructor = OIMO.BasicProxy;
  102902. OIMO.BasicProxy.prototype.update = function () {
  102903. };
  102904. /**
  102905. * The broad-phase is used for collecting all possible pairs for collision.
  102906. */
  102907. OIMO.BroadPhase = function () {
  102908. this.types = OIMO.BR_NULL;
  102909. this.numPairChecks = 0;
  102910. this.numPairs = 0;
  102911. this.pairs = [];
  102912. };
  102913. OIMO.BroadPhase.prototype = {
  102914. constructor: OIMO.BroadPhase,
  102915. /**
  102916. * Create a new proxy.
  102917. * @param shape
  102918. * @return
  102919. */
  102920. createProxy: function (shape) {
  102921. OIMO.Error("BroadPhase", "Inheritance error.");
  102922. },
  102923. /**
  102924. * Add the proxy into the broad-phase.
  102925. * @param proxy
  102926. */
  102927. addProxy: function (proxy) {
  102928. OIMO.Error("BroadPhase", "Inheritance error.");
  102929. },
  102930. /**
  102931. * Remove the proxy from the broad-phase.
  102932. * @param proxy
  102933. */
  102934. removeProxy: function (proxy) {
  102935. OIMO.Error("BroadPhase", "Inheritance error.");
  102936. },
  102937. /**
  102938. * Returns whether the pair is available or not.
  102939. * @param s1
  102940. * @param s2
  102941. * @return
  102942. */
  102943. isAvailablePair: function (s1, s2) {
  102944. var b1 = s1.parent;
  102945. var b2 = s2.parent;
  102946. if (b1 == b2 || // same parents
  102947. (!b1.isDynamic && !b2.isDynamic) || // static or kinematic object
  102948. (s1.belongsTo & s2.collidesWith) == 0 ||
  102949. (s2.belongsTo & s1.collidesWith) == 0 // collision filtering
  102950. ) { return false; }
  102951. var js;
  102952. if (b1.numJoints < b2.numJoints) js = b1.jointLink;
  102953. else js = b2.jointLink;
  102954. while (js !== null) {
  102955. var joint = js.joint;
  102956. if (!joint.allowCollision && ((joint.body1 == b1 && joint.body2 == b2) || (joint.body1 == b2 && joint.body2 == b1))) { return false; }
  102957. js = js.next;
  102958. }
  102959. return true;
  102960. },
  102961. // Detect overlapping pairs.
  102962. detectPairs: function () {
  102963. // clear old
  102964. this.pairs = [];
  102965. this.numPairs = 0;
  102966. this.numPairChecks = 0;
  102967. this.collectPairs();
  102968. },
  102969. collectPairs: function () {
  102970. OIMO.Error("BroadPhase", "Inheritance error.");
  102971. },
  102972. addPair: function (s1, s2) {
  102973. var pair = new OIMO.Pair(s1, s2);
  102974. this.pairs.push(pair);
  102975. this.numPairs++;
  102976. }
  102977. };
  102978. /**
  102979. * A broad-phase algorithm with brute-force search.
  102980. * This always checks for all possible pairs.
  102981. */
  102982. OIMO.BruteForceBroadPhase = function () {
  102983. OIMO.BroadPhase.call(this);
  102984. this.types = OIMO.BR_BRUTE_FORCE;;
  102985. //this.numProxies=0;
  102986. ///this.maxProxies = 256;
  102987. this.proxies = [];
  102988. //this.proxies.length = 256;
  102989. };
  102990. OIMO.BruteForceBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  102991. OIMO.BruteForceBroadPhase.prototype.constructor = OIMO.BruteForceBroadPhase;
  102992. OIMO.BruteForceBroadPhase.prototype.createProxy = function (shape) {
  102993. return new OIMO.BasicProxy(shape);
  102994. };
  102995. OIMO.BruteForceBroadPhase.prototype.addProxy = function (proxy) {
  102996. /*if(this.numProxies==this.maxProxies){
  102997. //this.maxProxies<<=1;
  102998. this.maxProxies*=2;
  102999. var newProxies=[];
  103000. newProxies.length = this.maxProxies;
  103001. var i = this.numProxies;
  103002. while(i--){
  103003. //for(var i=0, l=this.numProxies;i<l;i++){
  103004. newProxies[i]=this.proxies[i];
  103005. }
  103006. this.proxies=newProxies;
  103007. }*/
  103008. //this.proxies[this.numProxies++] = proxy;
  103009. this.proxies.push(proxy);
  103010. //this.numProxies++;
  103011. };
  103012. OIMO.BruteForceBroadPhase.prototype.removeProxy = function (proxy) {
  103013. var n = this.proxies.indexOf(proxy);
  103014. if (n > -1) {
  103015. this.proxies.splice(n, 1);
  103016. //this.numProxies--;
  103017. }
  103018. /*var i = this.numProxies;
  103019. while(i--){
  103020. //for(var i=0, l=this.numProxies;i<l;i++){
  103021. if(this.proxies[i] == proxy){
  103022. this.proxies[i] = this.proxies[--this.numProxies];
  103023. this.proxies[this.numProxies] = null;
  103024. return;
  103025. }
  103026. }*/
  103027. };
  103028. OIMO.BruteForceBroadPhase.prototype.collectPairs = function () {
  103029. var i = 0, j, p1, p2;
  103030. var px = this.proxies;
  103031. var l = px.length;//this.numProxies;
  103032. //var ar1 = [];
  103033. //var ar2 = [];
  103034. //for( i = px.length ; i-- ; ar1[ i ] = px[ i ] ){};
  103035. //for( i = px.length ; i-- ; ar2[ i ] = px[ i ] ){};
  103036. //var ar1 = JSON.parse(JSON.stringify(this.proxies))
  103037. //var ar2 = JSON.parse(JSON.stringify(this.proxies))
  103038. this.numPairChecks = l * (l - 1) >> 1;
  103039. //this.numPairChecks=this.numProxies*(this.numProxies-1)*0.5;
  103040. while (i < l) {
  103041. p1 = px[i++];
  103042. j = i + 1;
  103043. while (j < l) {
  103044. p2 = px[j++];
  103045. if (p1.aabb.intersectTest(p2.aabb) || !this.isAvailablePair(p1.shape, p2.shape)) continue;
  103046. this.addPair(p1.shape, p2.shape);
  103047. }
  103048. }
  103049. };
  103050. /**
  103051. * A pair of shapes that may collide.
  103052. * @author saharan
  103053. */
  103054. OIMO.Pair = function (s1, s2) {
  103055. // The first shape.
  103056. this.shape1 = s1 || null;
  103057. // The second shape.
  103058. this.shape2 = s2 || null;
  103059. };
  103060. /**
  103061. * A projection axis for sweep and prune broad-phase.
  103062. * @author saharan
  103063. */
  103064. OIMO.SAPAxis = function () {
  103065. this.numElements = 0;
  103066. this.bufferSize = 256;
  103067. this.elements = [];
  103068. this.elements.length = this.bufferSize;
  103069. this.stack = new OIMO_ARRAY_TYPE(64);
  103070. };
  103071. OIMO.SAPAxis.prototype = {
  103072. constructor: OIMO.SAPAxis,
  103073. addElements: function (min, max) {
  103074. if (this.numElements + 2 >= this.bufferSize) {
  103075. //this.bufferSize<<=1;
  103076. this.bufferSize *= 2;
  103077. var newElements = [];
  103078. var i = this.numElements;
  103079. while (i--) {
  103080. //for(var i=0, l=this.numElements; i<l; i++){
  103081. newElements[i] = this.elements[i];
  103082. }
  103083. }
  103084. this.elements[this.numElements++] = min;
  103085. this.elements[this.numElements++] = max;
  103086. },
  103087. removeElements: function (min, max) {
  103088. var minIndex = -1;
  103089. var maxIndex = -1;
  103090. for (var i = 0, l = this.numElements; i < l; i++) {
  103091. var e = this.elements[i];
  103092. if (e == min || e == max) {
  103093. if (minIndex == -1) {
  103094. minIndex = i;
  103095. } else {
  103096. maxIndex = i;
  103097. break;
  103098. }
  103099. }
  103100. }
  103101. for (i = minIndex + 1, l = maxIndex; i < l; i++) {
  103102. this.elements[i - 1] = this.elements[i];
  103103. }
  103104. for (i = maxIndex + 1, l = this.numElements; i < l; i++) {
  103105. this.elements[i - 2] = this.elements[i];
  103106. }
  103107. this.elements[--this.numElements] = null;
  103108. this.elements[--this.numElements] = null;
  103109. },
  103110. sort: function () {
  103111. var count = 0;
  103112. var threshold = 1;
  103113. while ((this.numElements >> threshold) != 0) threshold++;
  103114. threshold = threshold * this.numElements >> 2;
  103115. count = 0;
  103116. var giveup = false;
  103117. var elements = this.elements;
  103118. for (var i = 1, l = this.numElements; i < l; i++) { // try insertion sort
  103119. var tmp = elements[i];
  103120. var pivot = tmp.value;
  103121. var tmp2 = elements[i - 1];
  103122. if (tmp2.value > pivot) {
  103123. var j = i;
  103124. do {
  103125. elements[j] = tmp2;
  103126. if (--j == 0) break;
  103127. tmp2 = elements[j - 1];
  103128. } while (tmp2.value > pivot);
  103129. elements[j] = tmp;
  103130. count += i - j;
  103131. if (count > threshold) {
  103132. giveup = true; // stop and use quick sort
  103133. break;
  103134. }
  103135. }
  103136. }
  103137. if (!giveup) return;
  103138. count = 2; var stack = this.stack;
  103139. stack[0] = 0;
  103140. stack[1] = this.numElements - 1;
  103141. while (count > 0) {
  103142. var right = stack[--count];
  103143. var left = stack[--count];
  103144. var diff = right - left;
  103145. if (diff > 16) { // quick sort
  103146. //var mid=left+(diff>>1);
  103147. var mid = left + (OIMO.floor(diff * 0.5));
  103148. tmp = elements[mid];
  103149. elements[mid] = elements[right];
  103150. elements[right] = tmp;
  103151. pivot = tmp.value;
  103152. i = left - 1;
  103153. j = right;
  103154. while (true) {
  103155. var ei;
  103156. var ej;
  103157. do { ei = elements[++i]; } while (ei.value < pivot);
  103158. do { ej = elements[--j]; } while (pivot < ej.value && j != left);
  103159. if (i >= j) break;
  103160. elements[i] = ej;
  103161. elements[j] = ei;
  103162. }
  103163. elements[right] = elements[i];
  103164. elements[i] = tmp;
  103165. if (i - left > right - i) {
  103166. stack[count++] = left;
  103167. stack[count++] = i - 1;
  103168. stack[count++] = i + 1;
  103169. stack[count++] = right;
  103170. } else {
  103171. stack[count++] = i + 1;
  103172. stack[count++] = right;
  103173. stack[count++] = left;
  103174. stack[count++] = i - 1;
  103175. }
  103176. } else {
  103177. for (i = left + 1; i <= right; i++) {
  103178. tmp = elements[i];
  103179. pivot = tmp.value;
  103180. tmp2 = elements[i - 1];
  103181. if (tmp2.value > pivot) {
  103182. j = i;
  103183. do {
  103184. elements[j] = tmp2;
  103185. if (--j == 0) break;
  103186. tmp2 = elements[j - 1];
  103187. } while (tmp2.value > pivot);
  103188. elements[j] = tmp;
  103189. }
  103190. }
  103191. }
  103192. }
  103193. },
  103194. calculateTestCount: function () {
  103195. var num = 1;
  103196. var sum = 0;
  103197. for (var i = 1, l = this.numElements; i < l; i++) {
  103198. if (this.elements[i].max) {
  103199. num--;
  103200. } else {
  103201. sum += num;
  103202. num++;
  103203. }
  103204. }
  103205. return sum;
  103206. }
  103207. }
  103208. /**
  103209. * A broad-phase collision detection algorithm using sweep and prune.
  103210. * @author saharan
  103211. * @author lo-th
  103212. */
  103213. OIMO.SAPBroadPhase = function () {
  103214. OIMO.BroadPhase.call(this);
  103215. this.types = OIMO.BR_SWEEP_AND_PRUNE;
  103216. this.numElementsD = 0;
  103217. this.numElementsS = 0;
  103218. // dynamic proxies
  103219. this.axesD = [
  103220. new OIMO.SAPAxis(),
  103221. new OIMO.SAPAxis(),
  103222. new OIMO.SAPAxis()
  103223. ];
  103224. // static or sleeping proxies
  103225. this.axesS = [
  103226. new OIMO.SAPAxis(),
  103227. new OIMO.SAPAxis(),
  103228. new OIMO.SAPAxis()
  103229. ];
  103230. this.index1 = 0;
  103231. this.index2 = 1;
  103232. };
  103233. OIMO.SAPBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  103234. OIMO.SAPBroadPhase.prototype.constructor = OIMO.SAPBroadPhase;
  103235. OIMO.SAPBroadPhase.prototype.createProxy = function (shape) {
  103236. return new OIMO.SAPProxy(this, shape);
  103237. };
  103238. OIMO.SAPBroadPhase.prototype.addProxy = function (proxy) {
  103239. var p = proxy;
  103240. if (p.isDynamic()) {
  103241. this.axesD[0].addElements(p.min[0], p.max[0]);
  103242. this.axesD[1].addElements(p.min[1], p.max[1]);
  103243. this.axesD[2].addElements(p.min[2], p.max[2]);
  103244. p.belongsTo = 1;
  103245. this.numElementsD += 2;
  103246. } else {
  103247. this.axesS[0].addElements(p.min[0], p.max[0]);
  103248. this.axesS[1].addElements(p.min[1], p.max[1]);
  103249. this.axesS[2].addElements(p.min[2], p.max[2]);
  103250. p.belongsTo = 2;
  103251. this.numElementsS += 2;
  103252. }
  103253. };
  103254. OIMO.SAPBroadPhase.prototype.removeProxy = function (proxy) {
  103255. var p = proxy;
  103256. if (p.belongsTo == 0) return;
  103257. /*else if ( p.belongsTo == 1 ) {
  103258. this.axesD[0].removeElements( p.min[0], p.max[0] );
  103259. this.axesD[1].removeElements( p.min[1], p.max[1] );
  103260. this.axesD[2].removeElements( p.min[2], p.max[2] );
  103261. this.numElementsD -= 2;
  103262. } else if ( p.belongsTo == 2 ) {
  103263. this.axesS[0].removeElements( p.min[0], p.max[0] );
  103264. this.axesS[1].removeElements( p.min[1], p.max[1] );
  103265. this.axesS[2].removeElements( p.min[2], p.max[2] );
  103266. this.numElementsS -= 2;
  103267. }*/
  103268. switch (p.belongsTo) {
  103269. case 1:
  103270. this.axesD[0].removeElements(p.min[0], p.max[0]);
  103271. this.axesD[1].removeElements(p.min[1], p.max[1]);
  103272. this.axesD[2].removeElements(p.min[2], p.max[2]);
  103273. this.numElementsD -= 2;
  103274. break;
  103275. case 2:
  103276. this.axesS[0].removeElements(p.min[0], p.max[0]);
  103277. this.axesS[1].removeElements(p.min[1], p.max[1]);
  103278. this.axesS[2].removeElements(p.min[2], p.max[2]);
  103279. this.numElementsS -= 2;
  103280. break;
  103281. }
  103282. p.belongsTo = 0;
  103283. };
  103284. OIMO.SAPBroadPhase.prototype.collectPairs = function () {
  103285. if (this.numElementsD == 0) return;
  103286. var axis1 = this.axesD[this.index1];
  103287. var axis2 = this.axesD[this.index2];
  103288. axis1.sort();
  103289. axis2.sort();
  103290. var count1 = axis1.calculateTestCount();
  103291. var count2 = axis2.calculateTestCount();
  103292. var elementsD;
  103293. var elementsS;
  103294. if (count1 <= count2) {// select the best axis
  103295. axis2 = this.axesS[this.index1];
  103296. axis2.sort();
  103297. elementsD = axis1.elements;
  103298. elementsS = axis2.elements;
  103299. } else {
  103300. axis1 = this.axesS[this.index2];
  103301. axis1.sort();
  103302. elementsD = axis2.elements;
  103303. elementsS = axis1.elements;
  103304. this.index1 ^= this.index2;
  103305. this.index2 ^= this.index1;
  103306. this.index1 ^= this.index2;
  103307. }
  103308. var activeD;
  103309. var activeS;
  103310. var p = 0;
  103311. var q = 0;
  103312. while (p < this.numElementsD) {
  103313. var e1;
  103314. var dyn;
  103315. if (q == this.numElementsS) {
  103316. e1 = elementsD[p];
  103317. dyn = true;
  103318. p++;
  103319. } else {
  103320. var d = elementsD[p];
  103321. var s = elementsS[q];
  103322. if (d.value < s.value) {
  103323. e1 = d;
  103324. dyn = true;
  103325. p++;
  103326. } else {
  103327. e1 = s;
  103328. dyn = false;
  103329. q++;
  103330. }
  103331. }
  103332. if (!e1.max) {
  103333. var s1 = e1.proxy.shape;
  103334. var min1 = e1.min1.value;
  103335. var max1 = e1.max1.value;
  103336. var min2 = e1.min2.value;
  103337. var max2 = e1.max2.value;
  103338. for (var e2 = activeD; e2 != null; e2 = e2.pair) {// test for dynamic
  103339. var s2 = e2.proxy.shape;
  103340. this.numPairChecks++;
  103341. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  103342. this.addPair(s1, s2);
  103343. }
  103344. if (dyn) {
  103345. for (e2 = activeS; e2 != null; e2 = e2.pair) {// test for static
  103346. s2 = e2.proxy.shape;
  103347. this.numPairChecks++;
  103348. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  103349. this.addPair(s1, s2);
  103350. }
  103351. e1.pair = activeD;
  103352. activeD = e1;
  103353. } else {
  103354. e1.pair = activeS;
  103355. activeS = e1;
  103356. }
  103357. } else {
  103358. var min = e1.pair;
  103359. if (dyn) {
  103360. if (min == activeD) {
  103361. activeD = activeD.pair;
  103362. continue;
  103363. } else {
  103364. e1 = activeD;
  103365. }
  103366. } else {
  103367. if (min == activeS) {
  103368. activeS = activeS.pair;
  103369. continue;
  103370. } else {
  103371. e1 = activeS;
  103372. }
  103373. }
  103374. do {
  103375. e2 = e1.pair;
  103376. if (e2 == min) {
  103377. e1.pair = e2.pair;
  103378. break;
  103379. }
  103380. e1 = e2;
  103381. } while (e1 != null);
  103382. }
  103383. }
  103384. this.index2 = (this.index1 | this.index2) ^ 3;
  103385. };
  103386. /**
  103387. * An element of proxies.
  103388. * @author saharan
  103389. */
  103390. OIMO.SAPElement = function (proxy, max) {
  103391. // The parent proxy
  103392. this.proxy = proxy;
  103393. // The pair element.
  103394. this.pair = null;
  103395. // The minimum element on other axis.
  103396. this.min1 = null;
  103397. // The maximum element on other axis.
  103398. this.max1 = null;
  103399. // The minimum element on other axis.
  103400. this.min2 = null;
  103401. // The maximum element on other axis.
  103402. this.max2 = null;
  103403. // Whether the element has maximum value or not.
  103404. this.max = max;
  103405. // The value of the element.
  103406. this.value = 0;
  103407. };
  103408. /**
  103409. * A proxy for sweep and prune broad-phase.
  103410. * @author saharan
  103411. * @author lo-th
  103412. */
  103413. OIMO.SAPProxy = function (sap, shape) {
  103414. OIMO.Proxy.call(this, shape);
  103415. // Type of the axis to which the proxy belongs to. [0:none, 1:dynamic, 2:static]
  103416. this.belongsTo = 0;
  103417. // The maximum elements on each axis.
  103418. this.max = [];
  103419. // The minimum elements on each axis.
  103420. this.min = [];
  103421. this.sap = sap;
  103422. this.min[0] = new OIMO.SAPElement(this, false);
  103423. this.max[0] = new OIMO.SAPElement(this, true);
  103424. this.min[1] = new OIMO.SAPElement(this, false);
  103425. this.max[1] = new OIMO.SAPElement(this, true);
  103426. this.min[2] = new OIMO.SAPElement(this, false);
  103427. this.max[2] = new OIMO.SAPElement(this, true);
  103428. this.max[0].pair = this.min[0];
  103429. this.max[1].pair = this.min[1];
  103430. this.max[2].pair = this.min[2];
  103431. this.min[0].min1 = this.min[1];
  103432. this.min[0].max1 = this.max[1];
  103433. this.min[0].min2 = this.min[2];
  103434. this.min[0].max2 = this.max[2];
  103435. this.min[1].min1 = this.min[0];
  103436. this.min[1].max1 = this.max[0];
  103437. this.min[1].min2 = this.min[2];
  103438. this.min[1].max2 = this.max[2];
  103439. this.min[2].min1 = this.min[0];
  103440. this.min[2].max1 = this.max[0];
  103441. this.min[2].min2 = this.min[1];
  103442. this.min[2].max2 = this.max[1];
  103443. };
  103444. OIMO.SAPProxy.prototype = Object.create(OIMO.Proxy.prototype);
  103445. OIMO.SAPProxy.prototype.constructor = OIMO.SAPProxy;
  103446. // Returns whether the proxy is dynamic or not.
  103447. OIMO.SAPProxy.prototype.isDynamic = function () {
  103448. var body = this.shape.parent;
  103449. return body.isDynamic && !body.sleeping;
  103450. };
  103451. OIMO.SAPProxy.prototype.update = function () {
  103452. var te = this.aabb.elements;
  103453. this.min[0].value = te[0];
  103454. this.min[1].value = te[1];
  103455. this.min[2].value = te[2];
  103456. this.max[0].value = te[3];
  103457. this.max[1].value = te[4];
  103458. this.max[2].value = te[5];
  103459. if (this.belongsTo == 1 && !this.isDynamic() || this.belongsTo == 2 && this.isDynamic()) {
  103460. this.sap.removeProxy(this);
  103461. this.sap.addProxy(this);
  103462. }
  103463. };
  103464. /**
  103465. * A dynamic bounding volume tree for the broad-phase algorithm.
  103466. * @author saharan
  103467. * @author lo-th
  103468. */
  103469. OIMO.DBVT = function () {
  103470. // The root of the tree.
  103471. this.root = null;
  103472. this.freeNodes = [];
  103473. this.freeNodes.length = 16384;
  103474. this.numFreeNodes = 0;
  103475. this.aabb = new OIMO.AABB();
  103476. };
  103477. OIMO.DBVT.prototype = {
  103478. constructor: OIMO.DBVT,
  103479. /**
  103480. * Move a leaf.
  103481. * @param leaf
  103482. */
  103483. moveLeaf: function (leaf) {
  103484. this.deleteLeaf(leaf);
  103485. this.insertLeaf(leaf);
  103486. },
  103487. /**
  103488. * Insert a leaf to the tree.
  103489. * @param node
  103490. */
  103491. insertLeaf: function (leaf) {
  103492. if (this.root == null) {
  103493. this.root = leaf;
  103494. return;
  103495. }
  103496. var lb = leaf.aabb;
  103497. var sibling = this.root;
  103498. var oldArea;
  103499. var newArea;
  103500. while (sibling.proxy == null) { // descend the node to search the best pair
  103501. var c1 = sibling.child1;
  103502. var c2 = sibling.child2;
  103503. var b = sibling.aabb;
  103504. var c1b = c1.aabb;
  103505. var c2b = c2.aabb;
  103506. oldArea = b.surfaceArea();
  103507. this.aabb.combine(lb, b);
  103508. newArea = this.aabb.surfaceArea();
  103509. var creatingCost = newArea * 2;
  103510. var incrementalCost = (newArea - oldArea) * 2; // cost of creating a new pair with the node
  103511. var discendingCost1 = incrementalCost;
  103512. this.aabb.combine(lb, c1b);
  103513. if (c1.proxy != null) {
  103514. // leaf cost = area(combined aabb)
  103515. discendingCost1 += this.aabb.surfaceArea();
  103516. } else {
  103517. // node cost = area(combined aabb) - area(old aabb)
  103518. discendingCost1 += this.aabb.surfaceArea() - c1b.surfaceArea();
  103519. }
  103520. var discendingCost2 = incrementalCost;
  103521. this.aabb.combine(lb, c2b);
  103522. if (c2.proxy != null) {
  103523. // leaf cost = area(combined aabb)
  103524. discendingCost2 += this.aabb.surfaceArea();
  103525. } else {
  103526. // node cost = area(combined aabb) - area(old aabb)
  103527. discendingCost2 += this.aabb.surfaceArea() - c2b.surfaceArea();
  103528. }
  103529. if (discendingCost1 < discendingCost2) {
  103530. if (creatingCost < discendingCost1) {
  103531. break;// stop descending
  103532. } else {
  103533. sibling = c1;// descend into first child
  103534. }
  103535. } else {
  103536. if (creatingCost < discendingCost2) {
  103537. break;// stop descending
  103538. } else {
  103539. sibling = c2;// descend into second child
  103540. }
  103541. }
  103542. }
  103543. var oldParent = sibling.parent;
  103544. var newParent;
  103545. if (this.numFreeNodes > 0) {
  103546. newParent = this.freeNodes[--this.numFreeNodes];
  103547. } else {
  103548. newParent = new OIMO.DBVTNode();
  103549. }
  103550. newParent.parent = oldParent;
  103551. newParent.child1 = leaf;
  103552. newParent.child2 = sibling;
  103553. newParent.aabb.combine(leaf.aabb, sibling.aabb);
  103554. newParent.height = sibling.height + 1;
  103555. sibling.parent = newParent;
  103556. leaf.parent = newParent;
  103557. if (sibling == this.root) {
  103558. // replace root
  103559. this.root = newParent;
  103560. } else {
  103561. // replace child
  103562. if (oldParent.child1 == sibling) {
  103563. oldParent.child1 = newParent;
  103564. } else {
  103565. oldParent.child2 = newParent;
  103566. }
  103567. }
  103568. // update whole tree
  103569. do {
  103570. newParent = this.balance(newParent);
  103571. this.fix(newParent);
  103572. newParent = newParent.parent;
  103573. } while (newParent != null);
  103574. },
  103575. getBalance: function (node) {
  103576. if (node.proxy != null) return 0;
  103577. return node.child1.height - node.child2.height;
  103578. },
  103579. /*print:function(node,indent,text){
  103580. var hasChild=node.proxy==null;
  103581. if(hasChild)text=this.print(node.child1,indent+1,text);
  103582. for(var i=indent*2;i>=0;i--){
  103583. text+=" ";
  103584. }
  103585. text+=(hasChild?this.getBalance(node):"["+node.proxy.aabb.minX+"]")+"\n";
  103586. if(hasChild)text=this.print(node.child2,indent+1,text);
  103587. return text;
  103588. },*/
  103589. /**
  103590. * Delete a leaf from the tree.
  103591. * @param node
  103592. */
  103593. deleteLeaf: function (leaf) {
  103594. if (leaf == this.root) {
  103595. this.root = null;
  103596. return;
  103597. }
  103598. var parent = leaf.parent;
  103599. var sibling;
  103600. if (parent.child1 == leaf) {
  103601. sibling = parent.child2;
  103602. } else {
  103603. sibling = parent.child1;
  103604. }
  103605. if (parent == this.root) {
  103606. this.root = sibling;
  103607. sibling.parent = null;
  103608. return;
  103609. }
  103610. var grandParent = parent.parent;
  103611. sibling.parent = grandParent;
  103612. if (grandParent.child1 == parent) {
  103613. grandParent.child1 = sibling;
  103614. } else {
  103615. grandParent.child2 = sibling;
  103616. }
  103617. if (this.numFreeNodes < 16384) {
  103618. this.freeNodes[this.numFreeNodes++] = parent;
  103619. }
  103620. do {
  103621. grandParent = this.balance(grandParent);
  103622. this.fix(grandParent);
  103623. grandParent = grandParent.parent;
  103624. } while (grandParent != null);
  103625. },
  103626. balance: function (node) {
  103627. var nh = node.height;
  103628. if (nh < 2) {
  103629. return node;
  103630. }
  103631. var p = node.parent;
  103632. var l = node.child1;
  103633. var r = node.child2;
  103634. var lh = l.height;
  103635. var rh = r.height;
  103636. var balance = lh - rh;
  103637. var t;// for bit operation
  103638. // [ N ]
  103639. // / \
  103640. // [ L ] [ R ]
  103641. // / \ / \
  103642. // [L-L] [L-R] [R-L] [R-R]
  103643. // Is the tree balanced?
  103644. if (balance > 1) {
  103645. var ll = l.child1;
  103646. var lr = l.child2;
  103647. var llh = ll.height;
  103648. var lrh = lr.height;
  103649. // Is L-L higher than L-R?
  103650. if (llh > lrh) {
  103651. // set N to L-R
  103652. l.child2 = node;
  103653. node.parent = l;
  103654. // [ L ]
  103655. // / \
  103656. // [L-L] [ N ]
  103657. // / \ / \
  103658. // [...] [...] [ L ] [ R ]
  103659. // set L-R
  103660. node.child1 = lr;
  103661. lr.parent = node;
  103662. // [ L ]
  103663. // / \
  103664. // [L-L] [ N ]
  103665. // / \ / \
  103666. // [...] [...] [L-R] [ R ]
  103667. // fix bounds and heights
  103668. node.aabb.combine(lr.aabb, r.aabb);
  103669. t = lrh - rh;
  103670. node.height = lrh - (t & t >> 31) + 1;
  103671. l.aabb.combine(ll.aabb, node.aabb);
  103672. t = llh - nh;
  103673. l.height = llh - (t & t >> 31) + 1;
  103674. } else {
  103675. // set N to L-L
  103676. l.child1 = node;
  103677. node.parent = l;
  103678. // [ L ]
  103679. // / \
  103680. // [ N ] [L-R]
  103681. // / \ / \
  103682. // [ L ] [ R ] [...] [...]
  103683. // set L-L
  103684. node.child1 = ll;
  103685. ll.parent = node;
  103686. // [ L ]
  103687. // / \
  103688. // [ N ] [L-R]
  103689. // / \ / \
  103690. // [L-L] [ R ] [...] [...]
  103691. // fix bounds and heights
  103692. node.aabb.combine(ll.aabb, r.aabb);
  103693. t = llh - rh;
  103694. node.height = llh - (t & t >> 31) + 1;
  103695. l.aabb.combine(node.aabb, lr.aabb);
  103696. t = nh - lrh;
  103697. l.height = nh - (t & t >> 31) + 1;
  103698. }
  103699. // set new parent of L
  103700. if (p != null) {
  103701. if (p.child1 == node) {
  103702. p.child1 = l;
  103703. } else {
  103704. p.child2 = l;
  103705. }
  103706. } else {
  103707. this.root = l;
  103708. }
  103709. l.parent = p;
  103710. return l;
  103711. } else if (balance < -1) {
  103712. var rl = r.child1;
  103713. var rr = r.child2;
  103714. var rlh = rl.height;
  103715. var rrh = rr.height;
  103716. // Is R-L higher than R-R?
  103717. if (rlh > rrh) {
  103718. // set N to R-R
  103719. r.child2 = node;
  103720. node.parent = r;
  103721. // [ R ]
  103722. // / \
  103723. // [R-L] [ N ]
  103724. // / \ / \
  103725. // [...] [...] [ L ] [ R ]
  103726. // set R-R
  103727. node.child2 = rr;
  103728. rr.parent = node;
  103729. // [ R ]
  103730. // / \
  103731. // [R-L] [ N ]
  103732. // / \ / \
  103733. // [...] [...] [ L ] [R-R]
  103734. // fix bounds and heights
  103735. node.aabb.combine(l.aabb, rr.aabb);
  103736. t = lh - rrh;
  103737. node.height = lh - (t & t >> 31) + 1;
  103738. r.aabb.combine(rl.aabb, node.aabb);
  103739. t = rlh - nh;
  103740. r.height = rlh - (t & t >> 31) + 1;
  103741. } else {
  103742. // set N to R-L
  103743. r.child1 = node;
  103744. node.parent = r;
  103745. // [ R ]
  103746. // / \
  103747. // [ N ] [R-R]
  103748. // / \ / \
  103749. // [ L ] [ R ] [...] [...]
  103750. // set R-L
  103751. node.child2 = rl;
  103752. rl.parent = node;
  103753. // [ R ]
  103754. // / \
  103755. // [ N ] [R-R]
  103756. // / \ / \
  103757. // [ L ] [R-L] [...] [...]
  103758. // fix bounds and heights
  103759. node.aabb.combine(l.aabb, rl.aabb);
  103760. t = lh - rlh;
  103761. node.height = lh - (t & t >> 31) + 1;
  103762. r.aabb.combine(node.aabb, rr.aabb);
  103763. t = nh - rrh;
  103764. r.height = nh - (t & t >> 31) + 1;
  103765. }
  103766. // set new parent of R
  103767. if (p != null) {
  103768. if (p.child1 == node) {
  103769. p.child1 = r;
  103770. } else {
  103771. p.child2 = r;
  103772. }
  103773. } else {
  103774. this.root = r;
  103775. }
  103776. r.parent = p;
  103777. return r;
  103778. }
  103779. return node;
  103780. },
  103781. fix: function (node) {
  103782. var c1 = node.child1;
  103783. var c2 = node.child2;
  103784. node.aabb.combine(c1.aabb, c2.aabb);
  103785. //var h1 = c1.height;
  103786. //var h2 = c2.height;
  103787. node.height = c1.height < c2.height ? c2.height + 1 : c1.height + 1;
  103788. /*if( h1 < h2 ) {
  103789. node.height = h2+1;
  103790. }else{
  103791. node.height = h1+1;
  103792. }*/
  103793. }
  103794. }
  103795. /**
  103796. * A broad-phase algorithm using dynamic bounding volume tree.
  103797. * @author saharan
  103798. * @author lo-th
  103799. */
  103800. OIMO.DBVTBroadPhase = function () {
  103801. OIMO.BroadPhase.call(this);
  103802. this.types = OIMO.BR_BOUNDING_VOLUME_TREE;
  103803. this.tree = new OIMO.DBVT();
  103804. this.stack = [];
  103805. this.leaves = [];
  103806. this.numLeaves = 0;
  103807. };
  103808. OIMO.DBVTBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  103809. OIMO.DBVTBroadPhase.prototype.constructor = OIMO.DBVTBroadPhase;
  103810. OIMO.DBVTBroadPhase.prototype.createProxy = function (shape) {
  103811. return new OIMO.DBVTProxy(shape);
  103812. };
  103813. OIMO.DBVTBroadPhase.prototype.addProxy = function (proxy) {
  103814. this.tree.insertLeaf(proxy.leaf);
  103815. this.leaves.push(proxy.leaf);
  103816. this.numLeaves++;
  103817. };
  103818. OIMO.DBVTBroadPhase.prototype.removeProxy = function (proxy) {
  103819. this.tree.deleteLeaf(proxy.leaf);
  103820. var n = this.leaves.indexOf(proxy.leaf);
  103821. if (n > -1) {
  103822. this.leaves.splice(n, 1);
  103823. this.numLeaves--;
  103824. }
  103825. };
  103826. OIMO.DBVTBroadPhase.prototype.collectPairs = function () {
  103827. if (this.numLeaves < 2) return;
  103828. var leaf, margin = 0.1, i = this.numLeaves;
  103829. while (i--) {
  103830. leaf = this.leaves[i];
  103831. if (leaf.proxy.aabb.intersectTestTwo(leaf.aabb)) {
  103832. leaf.aabb.copy(leaf.proxy.aabb, margin);
  103833. this.tree.deleteLeaf(leaf);
  103834. this.tree.insertLeaf(leaf);
  103835. this.collide(leaf, this.tree.root);
  103836. }
  103837. }
  103838. };
  103839. OIMO.DBVTBroadPhase.prototype.collide = function (node1, node2) {
  103840. var stackCount = 2;
  103841. var s1, s2, n1, n2, l1, l2;
  103842. this.stack[0] = node1;
  103843. this.stack[1] = node2;
  103844. while (stackCount > 0) {
  103845. n1 = this.stack[--stackCount];
  103846. n2 = this.stack[--stackCount];
  103847. l1 = n1.proxy != null;
  103848. l2 = n2.proxy != null;
  103849. this.numPairChecks++;
  103850. if (l1 && l2) {
  103851. s1 = n1.proxy.shape;
  103852. s2 = n2.proxy.shape;
  103853. if (s1 == s2 || s1.aabb.intersectTest(s2.aabb) || !this.isAvailablePair(s1, s2)) continue;
  103854. this.addPair(s1, s2);
  103855. } else {
  103856. if (n1.aabb.intersectTest(n2.aabb)) continue;
  103857. /*if(stackCount+4>=this.maxStack){// expand the stack
  103858. //this.maxStack<<=1;
  103859. this.maxStack*=2;
  103860. var newStack = [];// vector
  103861. newStack.length = this.maxStack;
  103862. for(var i=0;i<stackCount;i++){
  103863. newStack[i] = this.stack[i];
  103864. }
  103865. this.stack = newStack;
  103866. }*/
  103867. if (l2 || !l1 && (n1.aabb.surfaceArea() > n2.aabb.surfaceArea())) {
  103868. this.stack[stackCount++] = n1.child1;
  103869. this.stack[stackCount++] = n2;
  103870. this.stack[stackCount++] = n1.child2;
  103871. this.stack[stackCount++] = n2;
  103872. } else {
  103873. this.stack[stackCount++] = n1;
  103874. this.stack[stackCount++] = n2.child1;
  103875. this.stack[stackCount++] = n1;
  103876. this.stack[stackCount++] = n2.child2;
  103877. }
  103878. }
  103879. }
  103880. };
  103881. /**
  103882. * A node of the dynamic bounding volume tree.
  103883. * @author saharan
  103884. */
  103885. OIMO.DBVTNode = function () {
  103886. // The first child node of this node.
  103887. this.child1 = null;
  103888. // The second child node of this node.
  103889. this.child2 = null;
  103890. // The parent node of this tree.
  103891. this.parent = null;
  103892. // The proxy of this node. This has no value if this node is not leaf.
  103893. this.proxy = null;
  103894. // The maximum distance from leaf nodes.
  103895. this.height = 0;
  103896. // The AABB of this node.
  103897. this.aabb = new OIMO.AABB();
  103898. };
  103899. /**
  103900. * A proxy for dynamic bounding volume tree broad-phase.
  103901. * @author saharan
  103902. */
  103903. OIMO.DBVTProxy = function (shape) {
  103904. OIMO.Proxy.call(this, shape);
  103905. // The leaf of the proxy.
  103906. this.leaf = new OIMO.DBVTNode();
  103907. this.leaf.proxy = this;
  103908. };
  103909. OIMO.DBVTProxy.prototype = Object.create(OIMO.Proxy.prototype);
  103910. OIMO.DBVTProxy.prototype.constructor = OIMO.DBVTProxy;
  103911. OIMO.DBVTProxy.prototype.update = function () {
  103912. };
  103913. OIMO.World.prototype.add = function (obj) {
  103914. obj = obj || {};
  103915. var type = obj.type || "box";
  103916. if (typeof type === 'string') type = [type];// single shape
  103917. if (type[0].substring(0, 5) == 'joint') { // is joint
  103918. if (type[0] === 'joint') type[0] = 'jointHinge';
  103919. var axe1 = obj.axe1 || [1, 0, 0];
  103920. var axe2 = obj.axe2 || [1, 0, 0];
  103921. var pos1 = obj.pos1 || [0, 0, 0];
  103922. var pos2 = obj.pos2 || [0, 0, 0];
  103923. pos1 = pos1.map(function (x) { return x * OIMO.INV_SCALE; });
  103924. pos2 = pos2.map(function (x) { return x * OIMO.INV_SCALE; });
  103925. var min, max;
  103926. if (type[0] === "jointDistance") {
  103927. min = obj.min || 0;
  103928. max = obj.max || 10;
  103929. min = min * OIMO.INV_SCALE;
  103930. max = max * OIMO.INV_SCALE;
  103931. } else {
  103932. min = obj.min || 57.29578;
  103933. max = obj.max || 0;
  103934. min = min * OIMO.degtorad;
  103935. max = max * OIMO.degtorad;
  103936. }
  103937. var limit = obj.limit || null;
  103938. var spring = obj.spring || null;
  103939. var motor = obj.motor || null;
  103940. // joint setting
  103941. var jc = new OIMO.JointConfig();
  103942. jc.allowCollision = obj.collision || false;;
  103943. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  103944. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  103945. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  103946. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  103947. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = this.getByName(obj.body1);
  103948. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = this.getByName(obj.body2);
  103949. jc.body1 = obj.body1;
  103950. jc.body2 = obj.body2;
  103951. var joint;
  103952. switch (type[0]) {
  103953. case "jointDistance": joint = new OIMO.DistanceJoint(jc, min, max);
  103954. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);
  103955. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  103956. break;
  103957. case "jointHinge": joint = new OIMO.HingeJoint(jc, min, max);
  103958. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  103959. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  103960. break;
  103961. case "jointPrisme": joint = new OIMO.PrismaticJoint(jc, min, max); break;
  103962. case "jointSlide": joint = new OIMO.SliderJoint(jc, min, max); break;
  103963. case "jointBall": joint = new OIMO.BallAndSocketJoint(jc); break;
  103964. case "jointWheel": joint = new OIMO.WheelJoint(jc);
  103965. if (limit !== null) joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  103966. if (spring !== null) joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  103967. if (motor !== null) joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  103968. break;
  103969. }
  103970. joint.name = obj.name || '';
  103971. // finaly add to physics world
  103972. this.addJoint(joint);
  103973. return joint;
  103974. } else { // is body
  103975. // I'm dynamique or not
  103976. var move = obj.move || false;
  103977. // I can sleep or not
  103978. var noSleep = obj.noSleep || false;
  103979. // My start position
  103980. var p = obj.pos || [0, 0, 0];
  103981. p = p.map(function (x) { return x * OIMO.INV_SCALE; });
  103982. // My size
  103983. var s = obj.size || [1, 1, 1];
  103984. s = s.map(function (x) { return x * OIMO.INV_SCALE; });
  103985. // My rotation in degre
  103986. var rot = obj.rot || [0, 0, 0];
  103987. rot = rot.map(function (x) { return x * OIMO.degtorad; });
  103988. var r = [];
  103989. for (var i = 0; i < rot.length / 3; i++) {
  103990. var tmp = OIMO.EulerToAxis(rot[i + 0], rot[i + 1], rot[i + 2]);
  103991. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  103992. }
  103993. // My physics setting
  103994. var sc = new OIMO.ShapeConfig();
  103995. if (obj.sc !== undefined) sc = obj.sc;
  103996. if (obj.config) {
  103997. // The density of the shape.
  103998. sc.density = obj.config[0] === undefined ? 1 : obj.config[0];
  103999. // The coefficient of friction of the shape.
  104000. sc.friction = obj.config[1] === undefined ? 0.4 : obj.config[1];
  104001. // The coefficient of restitution of the shape.
  104002. sc.restitution = obj.config[2] === undefined ? 0.2 : obj.config[2];
  104003. // The bits of the collision groups to which the shape belongs.
  104004. sc.belongsTo = obj.config[3] || 1;
  104005. //sc.belongsTo = obj.config[3] === undefined ? 1 : obj.config[3];
  104006. // The bits of the collision groups with which the shape collides.
  104007. sc.collidesWith = obj.config[4] || 0xffffffff;
  104008. //sc.collidesWith = obj.config[4] === undefined ? 0xffffffff : obj.config[4];
  104009. }
  104010. // direct physics setting
  104011. if (obj.density !== undefined) sc.density = obj.density;
  104012. if (obj.friction !== undefined) sc.friction = obj.friction;
  104013. if (obj.restitution !== undefined) sc.restitution = obj.restitution;
  104014. if (obj.belongsTo !== undefined) sc.belongsTo = obj.belongsTo;
  104015. if (obj.collidesWith !== undefined) sc.collidesWith = obj.collidesWith;
  104016. if (obj.massPos) {
  104017. obj.massPos = obj.massPos.map(function (x) { return x * OIMO.INV_SCALE; });
  104018. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  104019. }
  104020. if (obj.massRot) {
  104021. obj.massRot = obj.massRot.map(function (x) { return x * OIMO.degtorad; });
  104022. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  104023. }
  104024. // My rigidbody
  104025. var body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  104026. // My shapes
  104027. var shapes = [];
  104028. //if( typeof type === 'string' ) type = [type];// single shape
  104029. var n, n2;
  104030. for (var i = 0; i < type.length; i++) {
  104031. n = i * 3;
  104032. n2 = i * 4;
  104033. switch (type[i]) {
  104034. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n]); break;
  104035. case "cylinder": shapes[i] = new OIMO.CylinderShape(sc, s[n], s[n + 1]); break;
  104036. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n], s[n + 1], s[n + 2]); break;
  104037. }
  104038. body.addShape(shapes[i]);
  104039. if (i > 0) {
  104040. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  104041. shapes[i].relativePosition = new OIMO.Vec3(p[n], p[n + 1], p[n + 2]);
  104042. if (r[n2 + 0]) shapes[i].relativeRotation = [r[n2], r[n2 + 1], r[n2 + 2], r[n2 + 3]];
  104043. }
  104044. }
  104045. // I'm static or i move
  104046. if (move) {
  104047. if (obj.massPos || obj.massRot) body.setupMass(0x1, false);
  104048. else body.setupMass(0x1, true);
  104049. if (noSleep) body.allowSleep = false;
  104050. else body.allowSleep = true;
  104051. } else {
  104052. body.setupMass(0x2);
  104053. }
  104054. body.name = obj.name || ' ';
  104055. // finaly add to physics world
  104056. this.addRigidBody(body);
  104057. return body;
  104058. }
  104059. }
  104060. //UMD simplified
  104061. var root = this;
  104062. if (!root['OIMO']) {
  104063. if (true)
  104064. module.exports = OIMO;
  104065. else if (typeof define === 'function' && define.amd)
  104066. define([], function () {
  104067. return OIMO;
  104068. });
  104069. else if (typeof exports === 'object')
  104070. exports["OIMO"] = OIMO;
  104071. else {
  104072. root["OIMO"] = OIMO;
  104073. }
  104074. }
  104075. /***/ }),
  104076. /* 19 */
  104077. /***/ (function(module, exports, __webpack_require__) {
  104078. "use strict";
  104079. Object.defineProperty(exports, "__esModule", { value: true });
  104080. var babylonjs_1 = __webpack_require__(0);
  104081. var helper_1 = __webpack_require__(2);
  104082. var TemplateManager = (function () {
  104083. function TemplateManager(containerElement) {
  104084. this.containerElement = containerElement;
  104085. this.templates = {};
  104086. this.onInit = new babylonjs_1.Observable();
  104087. this.onLoaded = new babylonjs_1.Observable();
  104088. this.onStateChange = new babylonjs_1.Observable();
  104089. this.onAllLoaded = new babylonjs_1.Observable();
  104090. this.onEventTriggered = new babylonjs_1.Observable();
  104091. this.eventManager = new eventManager_1.EventManager(this);
  104092. }
  104093. TemplateManager.prototype.initTemplate = function (templates) {
  104094. var _this = this;
  104095. var internalInit = function (dependencyMap, name, parentTemplate) {
  104096. var template = _this.templates[name];
  104097. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  104098. return internalInit(dependencyMap[childName], childName, template);
  104099. });
  104100. var addToParent = function () {
  104101. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  104102. template.appendTo(containingElement);
  104103. _this.checkLoadedState();
  104104. };
  104105. if (parentTemplate && !parentTemplate.parent) {
  104106. parentTemplate.onAppended.add(function () {
  104107. addToParent();
  104108. });
  104109. }
  104110. else {
  104111. addToParent();
  104112. }
  104113. return template;
  104114. };
  104115. return this.buildHTMLTree(templates).then(function (htmlTree) {
  104116. if (_this.templates['main']) {
  104117. internalInit(htmlTree, 'main');
  104118. }
  104119. else {
  104120. _this.checkLoadedState();
  104121. }
  104122. return;
  104123. });
  104124. };
  104125. TemplateManager.prototype.buildHTMLTree = function (templates) {
  104126. var _this = this;
  104127. var promises = Object.keys(templates).map(function (name) {
  104128. if (!templates[name])
  104129. return Promise.resolve(false);
  104130. var template = new Template(name, templates[name]);
  104131. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  104132. _this.templates[name] = template;
  104133. return template.initPromise;
  104134. });
  104135. return Promise.all(promises).then(function () {
  104136. var templateStructure = {};
  104137. var buildTree = function (parentObject, name) {
  104138. _this.templates[name].isInHtmlTree = true;
  104139. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  104140. childNodes.forEach(function (element) {
  104141. parentObject[element] = {};
  104142. buildTree(parentObject[element], element);
  104143. });
  104144. };
  104145. if (_this.templates['main']) {
  104146. buildTree(templateStructure, "main");
  104147. }
  104148. return templateStructure;
  104149. });
  104150. };
  104151. TemplateManager.prototype.getCanvas = function () {
  104152. return this.containerElement.querySelector('canvas');
  104153. };
  104154. TemplateManager.prototype.getTemplate = function (name) {
  104155. return this.templates[name];
  104156. };
  104157. TemplateManager.prototype.checkLoadedState = function () {
  104158. var _this = this;
  104159. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  104160. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  104161. });
  104162. if (done) {
  104163. this.onAllLoaded.notifyObservers(this);
  104164. }
  104165. };
  104166. TemplateManager.prototype.dispose = function () {
  104167. var _this = this;
  104168. Object.keys(this.templates).forEach(function (template) {
  104169. _this.templates[template].dispose();
  104170. });
  104171. this.onInit.clear();
  104172. this.onAllLoaded.clear();
  104173. this.onEventTriggered.clear();
  104174. this.onLoaded.clear();
  104175. this.onStateChange.clear();
  104176. };
  104177. return TemplateManager;
  104178. }());
  104179. exports.TemplateManager = TemplateManager;
  104180. var Handlebars = __webpack_require__(20);
  104181. var eventManager_1 = __webpack_require__(21);
  104182. Handlebars.registerHelper('eachInMap', function (map, block) {
  104183. var out = '';
  104184. Object.keys(map).map(function (prop) {
  104185. var data = map[prop];
  104186. if (typeof data === 'object') {
  104187. data.id = data.id || prop;
  104188. out += block.fn(data);
  104189. }
  104190. else {
  104191. out += block.fn({ id: prop, value: data });
  104192. }
  104193. });
  104194. return out;
  104195. });
  104196. var Template = (function () {
  104197. function Template(name, _configuration) {
  104198. var _this = this;
  104199. this.name = name;
  104200. this._configuration = _configuration;
  104201. this.onInit = new babylonjs_1.Observable();
  104202. this.onLoaded = new babylonjs_1.Observable();
  104203. this.onAppended = new babylonjs_1.Observable();
  104204. this.onStateChange = new babylonjs_1.Observable();
  104205. this.onEventTriggered = new babylonjs_1.Observable();
  104206. this.loadRequests = [];
  104207. this.isLoaded = false;
  104208. this.isShown = false;
  104209. this.isInHtmlTree = false;
  104210. this.onInit.notifyObservers(this);
  104211. var htmlContentPromise = this.getTemplateAsHtml(_configuration);
  104212. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  104213. if (htmlTemplate) {
  104214. _this.htmlTemplate = htmlTemplate;
  104215. var compiledTemplate = Handlebars.compile(htmlTemplate);
  104216. var config = _this._configuration.params || {};
  104217. var rawHtml = compiledTemplate(config);
  104218. _this.fragment = document.createRange().createContextualFragment(rawHtml);
  104219. _this.isLoaded = true;
  104220. _this.isShown = true;
  104221. _this.onLoaded.notifyObservers(_this);
  104222. }
  104223. return _this;
  104224. });
  104225. }
  104226. Template.prototype.updateParams = function (params) {
  104227. this._configuration.params = params;
  104228. if (this.isLoaded) {
  104229. this.dispose();
  104230. }
  104231. var compiledTemplate = Handlebars.compile(this.htmlTemplate);
  104232. var config = this._configuration.params || {};
  104233. var rawHtml = compiledTemplate(config);
  104234. this.fragment = document.createRange().createContextualFragment(rawHtml);
  104235. if (this.parent) {
  104236. this.appendTo(this.parent, true);
  104237. }
  104238. };
  104239. Object.defineProperty(Template.prototype, "configuration", {
  104240. get: function () {
  104241. return this._configuration;
  104242. },
  104243. enumerable: true,
  104244. configurable: true
  104245. });
  104246. Template.prototype.getChildElements = function () {
  104247. var childrenArray = [];
  104248. var children = this.fragment.children;
  104249. if (!children) {
  104250. children = this.fragment.querySelectorAll('*');
  104251. }
  104252. for (var i = 0; i < children.length; ++i) {
  104253. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  104254. }
  104255. return childrenArray;
  104256. };
  104257. Template.prototype.appendTo = function (parent, forceRemove) {
  104258. var _this = this;
  104259. if (this.parent) {
  104260. if (forceRemove) {
  104261. this.parent.removeChild(this.fragment);
  104262. }
  104263. else {
  104264. return;
  104265. }
  104266. }
  104267. this.parent = parent;
  104268. if (this._configuration.id) {
  104269. this.parent.id = this._configuration.id;
  104270. }
  104271. this.fragment = this.parent.appendChild(this.fragment);
  104272. setTimeout(function () {
  104273. _this.registerEvents();
  104274. _this.onAppended.notifyObservers(_this);
  104275. });
  104276. };
  104277. Template.prototype.show = function (visibilityFunction) {
  104278. var _this = this;
  104279. if (this.isHiding)
  104280. return Promise.resolve(this);
  104281. return Promise.resolve().then(function () {
  104282. _this.isShowing = true;
  104283. if (visibilityFunction) {
  104284. return visibilityFunction(_this);
  104285. }
  104286. else {
  104287. _this.parent.style.display = 'flex';
  104288. return _this;
  104289. }
  104290. }).then(function () {
  104291. _this.isShown = true;
  104292. _this.isShowing = false;
  104293. _this.onStateChange.notifyObservers(_this);
  104294. return _this;
  104295. });
  104296. };
  104297. Template.prototype.hide = function (visibilityFunction) {
  104298. var _this = this;
  104299. if (this.isShowing)
  104300. return Promise.resolve(this);
  104301. return Promise.resolve().then(function () {
  104302. _this.isHiding = true;
  104303. if (visibilityFunction) {
  104304. return visibilityFunction(_this);
  104305. }
  104306. else {
  104307. _this.parent.style.display = 'hide';
  104308. return _this;
  104309. }
  104310. }).then(function () {
  104311. _this.isShown = false;
  104312. _this.isHiding = false;
  104313. _this.onStateChange.notifyObservers(_this);
  104314. return _this;
  104315. });
  104316. };
  104317. Template.prototype.dispose = function () {
  104318. this.onAppended.clear();
  104319. this.onEventTriggered.clear();
  104320. this.onInit.clear();
  104321. this.onLoaded.clear();
  104322. this.onStateChange.clear();
  104323. this.isLoaded = false;
  104324. this.parent.removeChild(this.fragment);
  104325. this.loadRequests.forEach(function (request) {
  104326. request.abort();
  104327. });
  104328. };
  104329. Template.prototype.getTemplateAsHtml = function (templateConfig) {
  104330. var _this = this;
  104331. if (!templateConfig) {
  104332. return Promise.reject('No templateConfig provided');
  104333. }
  104334. else if (templateConfig.html !== undefined) {
  104335. return Promise.resolve(templateConfig.html);
  104336. }
  104337. else {
  104338. var location_1 = getTemplateLocation(templateConfig);
  104339. if (helper_1.isUrl(location_1)) {
  104340. return new Promise(function (resolve, reject) {
  104341. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  104342. resolve(data);
  104343. }, undefined, undefined, false, function (request, error) {
  104344. reject(error);
  104345. });
  104346. _this.loadRequests.push(fileRequest);
  104347. });
  104348. }
  104349. else {
  104350. location_1 = location_1.replace('#', '');
  104351. var element = document.getElementById(location_1);
  104352. if (element) {
  104353. return Promise.resolve(element.innerHTML);
  104354. }
  104355. else {
  104356. return Promise.reject('Template ID not found');
  104357. }
  104358. }
  104359. }
  104360. };
  104361. Template.prototype.registerEvents = function () {
  104362. var _this = this;
  104363. this.registeredEvents = this.registeredEvents || [];
  104364. if (this.registeredEvents.length) {
  104365. this.registeredEvents.forEach(function (evt) {
  104366. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  104367. });
  104368. }
  104369. if (this._configuration.events) {
  104370. var _loop_1 = function (eventName) {
  104371. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  104372. var functionToFire_1 = function (selector, event) {
  104373. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  104374. };
  104375. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  104376. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, '#' + this_1.parent.id), false);
  104377. }
  104378. else if (typeof this_1._configuration.events[eventName] === 'object') {
  104379. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  104380. var event_1 = this_1._configuration.events[eventName] || {};
  104381. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  104382. if (selector && selector.indexOf('#') !== 0) {
  104383. selector = '#' + selector;
  104384. }
  104385. var htmlElement = _this.parent.querySelector(selector);
  104386. if (htmlElement) {
  104387. var binding = functionToFire_1.bind(_this, selector);
  104388. htmlElement.addEventListener(eventName, binding, false);
  104389. _this.registeredEvents.push({
  104390. htmlElement: htmlElement,
  104391. eventName: eventName,
  104392. function: binding
  104393. });
  104394. }
  104395. });
  104396. }
  104397. }
  104398. };
  104399. var this_1 = this;
  104400. for (var eventName in this._configuration.events) {
  104401. _loop_1(eventName);
  104402. }
  104403. }
  104404. };
  104405. return Template;
  104406. }());
  104407. exports.Template = Template;
  104408. function getTemplateLocation(templateConfig) {
  104409. if (!templateConfig || typeof templateConfig === 'string') {
  104410. return templateConfig;
  104411. }
  104412. else {
  104413. return templateConfig.location;
  104414. }
  104415. }
  104416. exports.getTemplateLocation = getTemplateLocation;
  104417. /***/ }),
  104418. /* 20 */
  104419. /***/ (function(module, exports, __webpack_require__) {
  104420. /**!
  104421. @license
  104422. handlebars v4.0.11
  104423. Copyright (C) 2011-2017 by Yehuda Katz
  104424. Permission is hereby granted, free of charge, to any person obtaining a copy
  104425. of this software and associated documentation files (the "Software"), to deal
  104426. in the Software without restriction, including without limitation the rights
  104427. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  104428. copies of the Software, and to permit persons to whom the Software is
  104429. furnished to do so, subject to the following conditions:
  104430. The above copyright notice and this permission notice shall be included in
  104431. all copies or substantial portions of the Software.
  104432. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  104433. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  104434. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  104435. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  104436. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  104437. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  104438. THE SOFTWARE.
  104439. */
  104440. !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],
  104441. 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){
  104442. 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"]}])});
  104443. /***/ }),
  104444. /* 21 */
  104445. /***/ (function(module, exports, __webpack_require__) {
  104446. "use strict";
  104447. Object.defineProperty(exports, "__esModule", { value: true });
  104448. var EventManager = (function () {
  104449. function EventManager(templateManager) {
  104450. var _this = this;
  104451. this.templateManager = templateManager;
  104452. this.callbacksContainer = {};
  104453. this.templateManager.onEventTriggered.add(function (eventData) {
  104454. _this.eventTriggered(eventData);
  104455. });
  104456. }
  104457. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  104458. if (!this.callbacksContainer[templateName]) {
  104459. this.callbacksContainer[templateName] = [];
  104460. }
  104461. this.callbacksContainer[templateName].push({
  104462. eventType: eventType,
  104463. callback: callback
  104464. });
  104465. };
  104466. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  104467. var callbackDefs = this.callbacksContainer[templateName] || [];
  104468. this.callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  104469. };
  104470. EventManager.prototype.eventTriggered = function (data) {
  104471. var templateName = data.template.name;
  104472. var eventType = data.event.type;
  104473. var selector = data.selector;
  104474. var callbackDefs = this.callbacksContainer[templateName] || [];
  104475. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  104476. callbackDef.callback(data);
  104477. });
  104478. };
  104479. return EventManager;
  104480. }());
  104481. exports.EventManager = EventManager;
  104482. /***/ }),
  104483. /* 22 */
  104484. /***/ (function(module, exports, __webpack_require__) {
  104485. "use strict";
  104486. Object.defineProperty(exports, "__esModule", { value: true });
  104487. var mappers_1 = __webpack_require__(1);
  104488. var types_1 = __webpack_require__(23);
  104489. var deepmerge = __webpack_require__(13);
  104490. var babylonjs_1 = __webpack_require__(0);
  104491. var ConfigurationLoader = (function () {
  104492. function ConfigurationLoader() {
  104493. this.configurationCache = {};
  104494. this.loadRequests = [];
  104495. }
  104496. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  104497. var _this = this;
  104498. if (initConfig === void 0) { initConfig = {}; }
  104499. var loadedConfig = deepmerge({}, initConfig);
  104500. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  104501. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  104502. if (loadedConfig.configuration) {
  104503. var mapperType_1 = "json";
  104504. return Promise.resolve().then(function () {
  104505. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  104506. var url = '';
  104507. if (typeof loadedConfig.configuration === "string") {
  104508. url = loadedConfig.configuration;
  104509. }
  104510. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  104511. url = loadedConfig.configuration.url;
  104512. var type = loadedConfig.configuration.mapper;
  104513. if (!type) {
  104514. type = loadedConfig.configuration.url.split('.').pop();
  104515. }
  104516. mapperType_1 = type || mapperType_1;
  104517. }
  104518. return _this.loadFile(url);
  104519. }
  104520. else {
  104521. if (typeof loadedConfig.configuration === "object") {
  104522. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  104523. return loadedConfig.configuration.payload || {};
  104524. }
  104525. return {};
  104526. }
  104527. }).then(function (data) {
  104528. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  104529. var parsed = mapper.map(data);
  104530. var merged = deepmerge(loadedConfig, parsed);
  104531. if (callback)
  104532. callback(merged);
  104533. return merged;
  104534. });
  104535. }
  104536. else {
  104537. if (callback)
  104538. callback(loadedConfig);
  104539. return Promise.resolve(loadedConfig);
  104540. }
  104541. };
  104542. ConfigurationLoader.prototype.dispose = function () {
  104543. this.loadRequests.forEach(function (request) {
  104544. request.abort();
  104545. });
  104546. };
  104547. ConfigurationLoader.prototype.loadFile = function (url) {
  104548. var _this = this;
  104549. var cacheReference = this.configurationCache;
  104550. if (cacheReference[url]) {
  104551. return Promise.resolve(cacheReference[url]);
  104552. }
  104553. return new Promise(function (resolve, reject) {
  104554. var fileRequest = babylonjs_1.Tools.LoadFile(url, resolve, undefined, undefined, false, function (request, error) {
  104555. reject(error);
  104556. });
  104557. _this.loadRequests.push(fileRequest);
  104558. });
  104559. };
  104560. return ConfigurationLoader;
  104561. }());
  104562. exports.ConfigurationLoader = ConfigurationLoader;
  104563. exports.configurationLoader = new ConfigurationLoader();
  104564. exports.default = exports.configurationLoader;
  104565. /***/ }),
  104566. /* 23 */
  104567. /***/ (function(module, exports, __webpack_require__) {
  104568. "use strict";
  104569. Object.defineProperty(exports, "__esModule", { value: true });
  104570. var minimal_1 = __webpack_require__(24);
  104571. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  104572. var default_1 = __webpack_require__(25);
  104573. exports.defaultConfiguration = default_1.defaultConfiguration;
  104574. var getConfigurationType = function (type) {
  104575. switch (type) {
  104576. case 'default':
  104577. return default_1.defaultConfiguration;
  104578. case 'minimal':
  104579. return minimal_1.minimalConfiguration;
  104580. case 'none':
  104581. return {};
  104582. default:
  104583. return default_1.defaultConfiguration;
  104584. }
  104585. };
  104586. exports.getConfigurationType = getConfigurationType;
  104587. /***/ }),
  104588. /* 24 */
  104589. /***/ (function(module, exports, __webpack_require__) {
  104590. "use strict";
  104591. Object.defineProperty(exports, "__esModule", { value: true });
  104592. exports.minimalConfiguration = {
  104593. version: "0.1",
  104594. templates: {
  104595. main: {
  104596. html: __webpack_require__(6)
  104597. },
  104598. loadingScreen: {
  104599. html: __webpack_require__(7),
  104600. params: {
  104601. backgroundColor: "#000000",
  104602. loadingImage: __webpack_require__(8)
  104603. }
  104604. },
  104605. viewer: {
  104606. html: __webpack_require__(9),
  104607. },
  104608. overlay: {
  104609. html: __webpack_require__(10),
  104610. params: {
  104611. closeImage: __webpack_require__(11),
  104612. closeText: 'Close'
  104613. }
  104614. },
  104615. error: {
  104616. html: __webpack_require__(12)
  104617. }
  104618. },
  104619. engine: {
  104620. antialiasing: true
  104621. }
  104622. };
  104623. /***/ }),
  104624. /* 25 */
  104625. /***/ (function(module, exports, __webpack_require__) {
  104626. "use strict";
  104627. Object.defineProperty(exports, "__esModule", { value: true });
  104628. exports.defaultConfiguration = {
  104629. version: "3.2.0-alpha4",
  104630. templates: {
  104631. main: {
  104632. html: __webpack_require__(6)
  104633. },
  104634. loadingScreen: {
  104635. html: __webpack_require__(7),
  104636. params: {
  104637. backgroundColor: "#000000",
  104638. loadingImage: __webpack_require__(8)
  104639. }
  104640. },
  104641. viewer: {
  104642. html: __webpack_require__(9),
  104643. events: {
  104644. pointerout: true,
  104645. pointerdown: true,
  104646. pointerup: true
  104647. }
  104648. },
  104649. navBar: {
  104650. html: __webpack_require__(26),
  104651. params: {
  104652. buttons: {
  104653. "fullscreen-button": {
  104654. altText: "Fullscreen",
  104655. image: __webpack_require__(27)
  104656. }
  104657. },
  104658. visibilityTimeout: 2000
  104659. },
  104660. events: {
  104661. pointerdown: { 'fullscreen-button': true },
  104662. pointerover: true
  104663. }
  104664. },
  104665. overlay: {
  104666. html: __webpack_require__(10),
  104667. params: {
  104668. closeImage: __webpack_require__(11),
  104669. closeText: 'Close'
  104670. }
  104671. },
  104672. help: {
  104673. html: __webpack_require__(28)
  104674. },
  104675. share: {
  104676. html: __webpack_require__(29)
  104677. },
  104678. error: {
  104679. html: __webpack_require__(12)
  104680. }
  104681. },
  104682. camera: {
  104683. behaviors: {
  104684. autoRotate: 0,
  104685. framing: {
  104686. type: 2,
  104687. zoomOnBoundingInfo: true,
  104688. zoomStopsAnimation: false
  104689. }
  104690. }
  104691. },
  104692. skybox: {
  104693. pbr: true,
  104694. blur: 0.7,
  104695. infiniteDIstance: false,
  104696. },
  104697. ground: true,
  104698. engine: {
  104699. antialiasing: true
  104700. },
  104701. scene: {
  104702. imageProcessingConfiguration: {
  104703. exposure: 1.4,
  104704. contrast: 1.66,
  104705. toneMappingEnabled: true
  104706. }
  104707. }
  104708. };
  104709. /***/ }),
  104710. /* 26 */
  104711. /***/ (function(module, exports) {
  104712. 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>";
  104713. /***/ }),
  104714. /* 27 */
  104715. /***/ (function(module, exports) {
  104716. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  104717. /***/ }),
  104718. /* 28 */
  104719. /***/ (function(module, exports) {
  104720. module.exports = "HELP";
  104721. /***/ }),
  104722. /* 29 */
  104723. /***/ (function(module, exports) {
  104724. module.exports = "SHARE";
  104725. /***/ }),
  104726. /* 30 */
  104727. /***/ (function(module, exports, __webpack_require__) {
  104728. "use strict";
  104729. Object.defineProperty(exports, "__esModule", { value: true });
  104730. var babylonjs_1 = __webpack_require__(0);
  104731. var modelAnimation_1 = __webpack_require__(31);
  104732. var ViewerModel = (function () {
  104733. function ViewerModel(_modelConfiguration, _scene, disableAutoLoad) {
  104734. if (disableAutoLoad === void 0) { disableAutoLoad = false; }
  104735. this._modelConfiguration = _modelConfiguration;
  104736. this._scene = _scene;
  104737. this.onLoadedObservable = new babylonjs_1.Observable();
  104738. this.onLoadErrorObservable = new babylonjs_1.Observable();
  104739. this.onLoadProgressObservable = new babylonjs_1.Observable();
  104740. this._animations = [];
  104741. if (!disableAutoLoad) {
  104742. this._initLoad();
  104743. }
  104744. }
  104745. ViewerModel.prototype.load = function () {
  104746. if (this.loader) {
  104747. babylonjs_1.Tools.Error("Model was already loaded or in the process of loading.");
  104748. }
  104749. else {
  104750. this._initLoad();
  104751. }
  104752. };
  104753. ViewerModel.prototype.getAnimationNames = function () {
  104754. return this._animations.map(function (a) { return a.name; });
  104755. };
  104756. ViewerModel.prototype._getAnimationByName = function (name) {
  104757. var filtered = this._animations.filter(function (a) { return a.name === name; });
  104758. if (filtered.length === 1) {
  104759. return filtered[0];
  104760. }
  104761. else {
  104762. return null;
  104763. }
  104764. };
  104765. ViewerModel.prototype.playAnimation = function (name) {
  104766. var animation = this._getAnimationByName(name);
  104767. if (animation) {
  104768. if (this.currentAnimation) {
  104769. this.currentAnimation.stop();
  104770. }
  104771. this.currentAnimation = animation;
  104772. animation.start();
  104773. return animation;
  104774. }
  104775. else {
  104776. throw new Error("animation not found - " + name);
  104777. }
  104778. };
  104779. ViewerModel.prototype._initLoad = function () {
  104780. var _this = this;
  104781. if (!this._modelConfiguration || !this._modelConfiguration.url) {
  104782. return babylonjs_1.Tools.Error("No model URL to load.");
  104783. }
  104784. var parts = this._modelConfiguration.url.split('/');
  104785. var filename = parts.pop() || this._modelConfiguration.url;
  104786. var base = parts.length ? parts.join('/') + '/' : './';
  104787. var plugin = this._modelConfiguration.loader;
  104788. var animationsArray = this._scene.animationGroups.slice();
  104789. this.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, this._scene, function (meshes, particleSystems, skeletons) {
  104790. meshes.forEach(function (mesh) {
  104791. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  104792. });
  104793. _this.meshes = meshes;
  104794. _this.particleSystems = particleSystems;
  104795. _this.skeletons = skeletons;
  104796. if (_this.loader.name === 'gltf') {
  104797. _this._scene.animationGroups.forEach(function (ag) {
  104798. if (animationsArray.indexOf(ag) === -1) {
  104799. _this._animations.push(new modelAnimation_1.GroupModelAnimation(ag));
  104800. }
  104801. });
  104802. }
  104803. else {
  104804. skeletons.forEach(function (skeleton, idx) {
  104805. var ag = new BABYLON.AnimationGroup("animation-" + idx, _this._scene);
  104806. skeleton.getAnimatables().forEach(function (a) {
  104807. if (a.animations[0]) {
  104808. ag.addTargetedAnimation(a.animations[0], a);
  104809. }
  104810. });
  104811. _this._animations.push(new modelAnimation_1.GroupModelAnimation(ag));
  104812. });
  104813. }
  104814. if (_this._modelConfiguration.animation) {
  104815. if (_this._modelConfiguration.animation.playOnce) {
  104816. _this._animations.forEach(function (a) {
  104817. a.playMode = modelAnimation_1.AnimationPlayMode.ONCE;
  104818. });
  104819. }
  104820. if (_this._modelConfiguration.animation.autoStart && _this._animations.length) {
  104821. var animationName = _this._modelConfiguration.animation.autoStart === true ?
  104822. _this._animations[0].name : _this._modelConfiguration.animation.autoStart;
  104823. _this.playAnimation(animationName);
  104824. }
  104825. }
  104826. _this.onLoadedObservable.notifyObserversWithPromise(_this);
  104827. }, function (progressEvent) {
  104828. _this.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  104829. }, function (e, m, exception) {
  104830. _this.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  104831. }, plugin);
  104832. this.loader['animationStartMode'] = 0;
  104833. };
  104834. ViewerModel.prototype.dispose = function () {
  104835. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  104836. this.skeletons.forEach(function (s) { return s.dispose(); });
  104837. this._animations.forEach(function (ag) { return ag.dispose(); });
  104838. this.meshes.forEach(function (m) { return m.dispose(); });
  104839. };
  104840. return ViewerModel;
  104841. }());
  104842. exports.ViewerModel = ViewerModel;
  104843. /***/ }),
  104844. /* 31 */
  104845. /***/ (function(module, exports, __webpack_require__) {
  104846. "use strict";
  104847. Object.defineProperty(exports, "__esModule", { value: true });
  104848. var AnimationPlayMode;
  104849. (function (AnimationPlayMode) {
  104850. AnimationPlayMode[AnimationPlayMode["ONCE"] = 0] = "ONCE";
  104851. AnimationPlayMode[AnimationPlayMode["LOOP"] = 1] = "LOOP";
  104852. })(AnimationPlayMode = exports.AnimationPlayMode || (exports.AnimationPlayMode = {}));
  104853. var AnimationState;
  104854. (function (AnimationState) {
  104855. AnimationState[AnimationState["INIT"] = 0] = "INIT";
  104856. AnimationState[AnimationState["PLAYING"] = 1] = "PLAYING";
  104857. AnimationState[AnimationState["PAUSED"] = 2] = "PAUSED";
  104858. AnimationState[AnimationState["STOPPED"] = 3] = "STOPPED";
  104859. AnimationState[AnimationState["ENDED"] = 4] = "ENDED";
  104860. })(AnimationState = exports.AnimationState || (exports.AnimationState = {}));
  104861. var GroupModelAnimation = (function () {
  104862. function GroupModelAnimation(_animationGroup) {
  104863. var _this = this;
  104864. this._animationGroup = _animationGroup;
  104865. this._state = AnimationState.INIT;
  104866. this._playMode = AnimationPlayMode.LOOP;
  104867. this._animationGroup.onAnimationEndObservable.add(function () {
  104868. _this.stop();
  104869. _this._state = AnimationState.ENDED;
  104870. });
  104871. }
  104872. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  104873. get: function () {
  104874. return this._animationGroup.name;
  104875. },
  104876. enumerable: true,
  104877. configurable: true
  104878. });
  104879. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  104880. get: function () {
  104881. return this._state;
  104882. },
  104883. enumerable: true,
  104884. configurable: true
  104885. });
  104886. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  104887. get: function () {
  104888. return this._animationGroup.speedRatio;
  104889. },
  104890. set: function (value) {
  104891. this._animationGroup.speedRatio = value;
  104892. },
  104893. enumerable: true,
  104894. configurable: true
  104895. });
  104896. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  104897. get: function () {
  104898. var animationFrames = this._animationGroup.targetedAnimations.map(function (ta) {
  104899. var keys = ta.animation.getKeys();
  104900. return keys[keys.length - 1].frame;
  104901. });
  104902. return Math.max.apply(null, animationFrames);
  104903. },
  104904. enumerable: true,
  104905. configurable: true
  104906. });
  104907. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  104908. get: function () {
  104909. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  104910. var animatable = this._animationGroup.animatables[i];
  104911. var animations = animatable.getAnimations();
  104912. if (!animations || !animations.length) {
  104913. continue;
  104914. }
  104915. for (var idx = 0; idx < animations.length; ++idx) {
  104916. if (animations[idx].currentFrame) {
  104917. return animations[idx].currentFrame;
  104918. }
  104919. }
  104920. }
  104921. return 0;
  104922. },
  104923. enumerable: true,
  104924. configurable: true
  104925. });
  104926. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  104927. get: function () {
  104928. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  104929. var animatable = this._animationGroup.animatables[i];
  104930. var animations = animatable.getAnimations();
  104931. if (!animations || !animations.length) {
  104932. continue;
  104933. }
  104934. for (var idx = 0; idx < animations.length; ++idx) {
  104935. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  104936. return animations[idx].animation.framePerSecond;
  104937. }
  104938. }
  104939. }
  104940. return 0;
  104941. },
  104942. enumerable: true,
  104943. configurable: true
  104944. });
  104945. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  104946. get: function () {
  104947. return this._playMode;
  104948. },
  104949. set: function (value) {
  104950. if (value === this._playMode) {
  104951. return;
  104952. }
  104953. this._playMode = value;
  104954. if (this.state === AnimationState.PLAYING) {
  104955. this._animationGroup.play(this._playMode === AnimationPlayMode.LOOP);
  104956. }
  104957. else {
  104958. this._animationGroup.reset();
  104959. this._state = AnimationState.INIT;
  104960. }
  104961. },
  104962. enumerable: true,
  104963. configurable: true
  104964. });
  104965. GroupModelAnimation.prototype.reset = function () {
  104966. this._animationGroup.reset();
  104967. };
  104968. GroupModelAnimation.prototype.restart = function () {
  104969. this._animationGroup.restart();
  104970. };
  104971. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  104972. this._animationGroup['_animatables'].forEach(function (a) {
  104973. a.goToFrame(frameNumber);
  104974. });
  104975. };
  104976. GroupModelAnimation.prototype.start = function () {
  104977. this._animationGroup.start(this.playMode === AnimationPlayMode.LOOP, this.speedRatio);
  104978. if (this._animationGroup.isStarted) {
  104979. this._state = AnimationState.PLAYING;
  104980. }
  104981. };
  104982. GroupModelAnimation.prototype.pause = function () {
  104983. this._animationGroup.pause();
  104984. this._state = AnimationState.PAUSED;
  104985. };
  104986. GroupModelAnimation.prototype.stop = function () {
  104987. this._animationGroup.stop();
  104988. if (!this._animationGroup.isStarted) {
  104989. this._state = AnimationState.STOPPED;
  104990. }
  104991. };
  104992. GroupModelAnimation.prototype.dispose = function () {
  104993. this._animationGroup.dispose();
  104994. };
  104995. return GroupModelAnimation;
  104996. }());
  104997. exports.GroupModelAnimation = GroupModelAnimation;
  104998. /***/ }),
  104999. /* 32 */
  105000. /***/ (function(module, exports, __webpack_require__) {
  105001. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  105002. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  105003. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  105004. 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;
  105005. return c > 3 && r && Object.defineProperty(target, key, r), r;
  105006. };
  105007. var __extends = (this && this.__extends) || (function () {
  105008. var extendStatics = Object.setPrototypeOf ||
  105009. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  105010. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  105011. return function (d, b) {
  105012. extendStatics(d, b);
  105013. function __() { this.constructor = d; }
  105014. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  105015. };
  105016. })();
  105017. (function universalModuleDefinition(root, factory) {
  105018. if(true)
  105019. module.exports = factory(__webpack_require__(0));
  105020. else if(typeof define === 'function' && define.amd)
  105021. define("babylonjs-loaders", ["babylonjs"], factory);
  105022. else if(typeof exports === 'object')
  105023. exports["babylonjs-loaders"] = factory(require("babylonjs"));
  105024. else {
  105025. root["BABYLON"] = factory(root["BABYLON"]);
  105026. }
  105027. })(this, function(BABYLON) {
  105028. var BABYLON;
  105029. (function (BABYLON) {
  105030. var STLFileLoader = /** @class */ (function () {
  105031. function STLFileLoader() {
  105032. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  105033. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  105034. 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;
  105035. 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;
  105036. this.name = "stl";
  105037. // force data to come in as an ArrayBuffer
  105038. // we'll convert to string if it looks like it's an ASCII .stl
  105039. this.extensions = {
  105040. ".stl": { isBinary: true },
  105041. };
  105042. }
  105043. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  105044. var matches;
  105045. if (this.isBinary(data)) {
  105046. // binary .stl
  105047. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  105048. this.parseBinary(babylonMesh, data);
  105049. if (meshes) {
  105050. meshes.push(babylonMesh);
  105051. }
  105052. return true;
  105053. }
  105054. // ASCII .stl
  105055. // convert to string
  105056. var array_buffer = new Uint8Array(data);
  105057. var str = '';
  105058. for (var i = 0; i < data.byteLength; i++) {
  105059. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  105060. }
  105061. data = str;
  105062. while (matches = this.solidPattern.exec(data)) {
  105063. var meshName = matches[1];
  105064. var meshNameFromEnd = matches[3];
  105065. if (meshName != meshNameFromEnd) {
  105066. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  105067. return false;
  105068. }
  105069. // check meshesNames
  105070. if (meshesNames && meshName) {
  105071. if (meshesNames instanceof Array) {
  105072. if (!meshesNames.indexOf(meshName)) {
  105073. continue;
  105074. }
  105075. }
  105076. else {
  105077. if (meshName !== meshesNames) {
  105078. continue;
  105079. }
  105080. }
  105081. }
  105082. // stl mesh name can be empty as well
  105083. meshName = meshName || "stlmesh";
  105084. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  105085. this.parseASCII(babylonMesh, matches[2]);
  105086. if (meshes) {
  105087. meshes.push(babylonMesh);
  105088. }
  105089. }
  105090. return true;
  105091. };
  105092. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  105093. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  105094. if (result) {
  105095. scene.createDefaultCameraOrLight();
  105096. }
  105097. return result;
  105098. };
  105099. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  105100. var container = new BABYLON.AssetContainer(scene);
  105101. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  105102. container.removeAllFromScene();
  105103. return container;
  105104. };
  105105. STLFileLoader.prototype.isBinary = function (data) {
  105106. // check if file size is correct for binary stl
  105107. var faceSize, nFaces, reader;
  105108. reader = new DataView(data);
  105109. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  105110. nFaces = reader.getUint32(80, true);
  105111. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  105112. return true;
  105113. }
  105114. // check characters higher than ASCII to confirm binary
  105115. var fileLength = reader.byteLength;
  105116. for (var index = 0; index < fileLength; index++) {
  105117. if (reader.getUint8(index) > 127) {
  105118. return true;
  105119. }
  105120. }
  105121. return false;
  105122. };
  105123. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  105124. var reader = new DataView(data);
  105125. var faces = reader.getUint32(80, true);
  105126. var dataOffset = 84;
  105127. var faceLength = 12 * 4 + 2;
  105128. var offset = 0;
  105129. var positions = new Float32Array(faces * 3 * 3);
  105130. var normals = new Float32Array(faces * 3 * 3);
  105131. var indices = new Uint32Array(faces * 3);
  105132. var indicesCount = 0;
  105133. for (var face = 0; face < faces; face++) {
  105134. var start = dataOffset + face * faceLength;
  105135. var normalX = reader.getFloat32(start, true);
  105136. var normalY = reader.getFloat32(start + 4, true);
  105137. var normalZ = reader.getFloat32(start + 8, true);
  105138. for (var i = 1; i <= 3; i++) {
  105139. var vertexstart = start + i * 12;
  105140. // ordering is intentional to match ascii import
  105141. positions[offset] = reader.getFloat32(vertexstart, true);
  105142. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  105143. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  105144. normals[offset] = normalX;
  105145. normals[offset + 2] = normalY;
  105146. normals[offset + 1] = normalZ;
  105147. offset += 3;
  105148. }
  105149. indices[indicesCount] = indicesCount++;
  105150. indices[indicesCount] = indicesCount++;
  105151. indices[indicesCount] = indicesCount++;
  105152. }
  105153. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  105154. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  105155. mesh.setIndices(indices);
  105156. mesh.computeWorldMatrix(true);
  105157. };
  105158. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  105159. var positions = [];
  105160. var normals = [];
  105161. var indices = [];
  105162. var indicesCount = 0;
  105163. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  105164. var matches;
  105165. while (matches = this.facetsPattern.exec(solidData)) {
  105166. var facet = matches[1];
  105167. //one normal per face
  105168. var normalMatches = this.normalPattern.exec(facet);
  105169. this.normalPattern.lastIndex = 0;
  105170. if (!normalMatches) {
  105171. continue;
  105172. }
  105173. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  105174. var vertexMatch;
  105175. while (vertexMatch = this.vertexPattern.exec(facet)) {
  105176. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  105177. normals.push(normal[0], normal[1], normal[2]);
  105178. }
  105179. indices.push(indicesCount++, indicesCount++, indicesCount++);
  105180. this.vertexPattern.lastIndex = 0;
  105181. }
  105182. this.facetsPattern.lastIndex = 0;
  105183. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  105184. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  105185. mesh.setIndices(indices);
  105186. mesh.computeWorldMatrix(true);
  105187. };
  105188. return STLFileLoader;
  105189. }());
  105190. BABYLON.STLFileLoader = STLFileLoader;
  105191. if (BABYLON.SceneLoader) {
  105192. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  105193. }
  105194. })(BABYLON || (BABYLON = {}));
  105195. //# sourceMappingURL=babylon.stlFileLoader.js.map
  105196. var BABYLON;
  105197. (function (BABYLON) {
  105198. /**
  105199. * Class reading and parsing the MTL file bundled with the obj file.
  105200. */
  105201. var MTLFileLoader = /** @class */ (function () {
  105202. function MTLFileLoader() {
  105203. // All material loaded from the mtl will be set here
  105204. this.materials = [];
  105205. }
  105206. /**
  105207. * This function will read the mtl file and create each material described inside
  105208. * This function could be improve by adding :
  105209. * -some component missing (Ni, Tf...)
  105210. * -including the specific options available
  105211. *
  105212. * @param scene
  105213. * @param data
  105214. * @param rootUrl
  105215. */
  105216. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  105217. //Split the lines from the file
  105218. var lines = data.split('\n');
  105219. //Space char
  105220. var delimiter_pattern = /\s+/;
  105221. //Array with RGB colors
  105222. var color;
  105223. //New material
  105224. var material = null;
  105225. //Look at each line
  105226. for (var i = 0; i < lines.length; i++) {
  105227. var line = lines[i].trim();
  105228. // Blank line or comment
  105229. if (line.length === 0 || line.charAt(0) === '#') {
  105230. continue;
  105231. }
  105232. //Get the first parameter (keyword)
  105233. var pos = line.indexOf(' ');
  105234. var key = (pos >= 0) ? line.substring(0, pos) : line;
  105235. key = key.toLowerCase();
  105236. //Get the data following the key
  105237. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  105238. //This mtl keyword will create the new material
  105239. if (key === "newmtl") {
  105240. //Check if it is the first material.
  105241. // Materials specifications are described after this keyword.
  105242. if (material) {
  105243. //Add the previous material in the material array.
  105244. this.materials.push(material);
  105245. }
  105246. //Create a new material.
  105247. // value is the name of the material read in the mtl file
  105248. material = new BABYLON.StandardMaterial(value, scene);
  105249. }
  105250. else if (key === "kd" && material) {
  105251. // Diffuse color (color under white light) using RGB values
  105252. //value = "r g b"
  105253. color = value.split(delimiter_pattern, 3).map(parseFloat);
  105254. //color = [r,g,b]
  105255. //Set tghe color into the material
  105256. material.diffuseColor = BABYLON.Color3.FromArray(color);
  105257. }
  105258. else if (key === "ka" && material) {
  105259. // Ambient color (color under shadow) using RGB values
  105260. //value = "r g b"
  105261. color = value.split(delimiter_pattern, 3).map(parseFloat);
  105262. //color = [r,g,b]
  105263. //Set tghe color into the material
  105264. material.ambientColor = BABYLON.Color3.FromArray(color);
  105265. }
  105266. else if (key === "ks" && material) {
  105267. // Specular color (color when light is reflected from shiny surface) using RGB values
  105268. //value = "r g b"
  105269. color = value.split(delimiter_pattern, 3).map(parseFloat);
  105270. //color = [r,g,b]
  105271. //Set the color into the material
  105272. material.specularColor = BABYLON.Color3.FromArray(color);
  105273. }
  105274. else if (key === "ke" && material) {
  105275. // Emissive color using RGB values
  105276. color = value.split(delimiter_pattern, 3).map(parseFloat);
  105277. material.emissiveColor = BABYLON.Color3.FromArray(color);
  105278. }
  105279. else if (key === "ns" && material) {
  105280. //value = "Integer"
  105281. material.specularPower = parseFloat(value);
  105282. }
  105283. else if (key === "d" && material) {
  105284. //d is dissolve for current material. It mean alpha for BABYLON
  105285. material.alpha = parseFloat(value);
  105286. //Texture
  105287. //This part can be improved by adding the possible options of texture
  105288. }
  105289. else if (key === "map_ka" && material) {
  105290. // ambient texture map with a loaded image
  105291. //We must first get the folder of the image
  105292. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105293. }
  105294. else if (key === "map_kd" && material) {
  105295. // Diffuse texture map with a loaded image
  105296. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105297. }
  105298. else if (key === "map_ks" && material) {
  105299. // Specular texture map with a loaded image
  105300. //We must first get the folder of the image
  105301. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105302. }
  105303. else if (key === "map_ns") {
  105304. //Specular
  105305. //Specular highlight component
  105306. //We must first get the folder of the image
  105307. //
  105308. //Not supported by BABYLON
  105309. //
  105310. // continue;
  105311. }
  105312. else if (key === "map_bump" && material) {
  105313. //The bump texture
  105314. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105315. }
  105316. else if (key === "map_d" && material) {
  105317. // The dissolve of the material
  105318. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105319. //Options for illumination
  105320. }
  105321. else if (key === "illum") {
  105322. //Illumination
  105323. if (value === "0") {
  105324. //That mean Kd == Kd
  105325. }
  105326. else if (value === "1") {
  105327. //Color on and Ambient on
  105328. }
  105329. else if (value === "2") {
  105330. //Highlight on
  105331. }
  105332. else if (value === "3") {
  105333. //Reflection on and Ray trace on
  105334. }
  105335. else if (value === "4") {
  105336. //Transparency: Glass on, Reflection: Ray trace on
  105337. }
  105338. else if (value === "5") {
  105339. //Reflection: Fresnel on and Ray trace on
  105340. }
  105341. else if (value === "6") {
  105342. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  105343. }
  105344. else if (value === "7") {
  105345. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  105346. }
  105347. else if (value === "8") {
  105348. //Reflection on and Ray trace off
  105349. }
  105350. else if (value === "9") {
  105351. //Transparency: Glass on, Reflection: Ray trace off
  105352. }
  105353. else if (value === "10") {
  105354. //Casts shadows onto invisible surfaces
  105355. }
  105356. }
  105357. else {
  105358. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  105359. }
  105360. }
  105361. //At the end of the file, add the last material
  105362. if (material) {
  105363. this.materials.push(material);
  105364. }
  105365. };
  105366. /**
  105367. * Gets the texture for the material.
  105368. *
  105369. * If the material is imported from input file,
  105370. * We sanitize the url to ensure it takes the textre from aside the material.
  105371. *
  105372. * @param rootUrl The root url to load from
  105373. * @param value The value stored in the mtl
  105374. * @return The Texture
  105375. */
  105376. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  105377. if (!value) {
  105378. return null;
  105379. }
  105380. var url = rootUrl;
  105381. // Load from input file.
  105382. if (rootUrl === "file:") {
  105383. var lastDelimiter = value.lastIndexOf("\\");
  105384. if (lastDelimiter === -1) {
  105385. lastDelimiter = value.lastIndexOf("/");
  105386. }
  105387. if (lastDelimiter > -1) {
  105388. url += value.substr(lastDelimiter + 1);
  105389. }
  105390. else {
  105391. url += value;
  105392. }
  105393. }
  105394. else {
  105395. url += value;
  105396. }
  105397. return new BABYLON.Texture(url, scene);
  105398. };
  105399. return MTLFileLoader;
  105400. }());
  105401. BABYLON.MTLFileLoader = MTLFileLoader;
  105402. var OBJFileLoader = /** @class */ (function () {
  105403. function OBJFileLoader() {
  105404. this.name = "obj";
  105405. this.extensions = ".obj";
  105406. this.obj = /^o/;
  105407. this.group = /^g/;
  105408. this.mtllib = /^mtllib /;
  105409. this.usemtl = /^usemtl /;
  105410. this.smooth = /^s /;
  105411. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  105412. // vn float float float
  105413. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  105414. // vt float float
  105415. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  105416. // f vertex vertex vertex ...
  105417. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  105418. // f vertex/uvs vertex/uvs vertex/uvs ...
  105419. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  105420. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  105421. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  105422. // f vertex//normal vertex//normal vertex//normal ...
  105423. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  105424. }
  105425. /**
  105426. * Calls synchronously the MTL file attached to this obj.
  105427. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  105428. * Without this function materials are not displayed in the first frame (but displayed after).
  105429. * In consequence it is impossible to get material information in your HTML file
  105430. *
  105431. * @param url The URL of the MTL file
  105432. * @param rootUrl
  105433. * @param onSuccess Callback function to be called when the MTL file is loaded
  105434. * @private
  105435. */
  105436. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  105437. //The complete path to the mtl file
  105438. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  105439. // Loads through the babylon tools to allow fileInput search.
  105440. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  105441. };
  105442. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  105443. //get the meshes from OBJ file
  105444. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  105445. //Push meshes from OBJ file into the variable mesh of this function
  105446. if (meshes) {
  105447. loadedMeshes.forEach(function (mesh) {
  105448. meshes.push(mesh);
  105449. });
  105450. }
  105451. return true;
  105452. };
  105453. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  105454. //Get the 3D model
  105455. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  105456. };
  105457. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  105458. var container = new BABYLON.AssetContainer(scene);
  105459. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  105460. container.removeAllFromScene();
  105461. return container;
  105462. };
  105463. /**
  105464. * Read the OBJ file and create an Array of meshes.
  105465. * Each mesh contains all information given by the OBJ and the MTL file.
  105466. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  105467. *
  105468. * @param meshesNames
  105469. * @param scene BABYLON.Scene The scene where are displayed the data
  105470. * @param data String The content of the obj file
  105471. * @param rootUrl String The path to the folder
  105472. * @returns Array<AbstractMesh>
  105473. * @private
  105474. */
  105475. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  105476. var positions = []; //values for the positions of vertices
  105477. var normals = []; //Values for the normals
  105478. var uvs = []; //Values for the textures
  105479. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  105480. var handledMesh; //The current mesh of meshes array
  105481. var indicesForBabylon = []; //The list of indices for VertexData
  105482. var wrappedPositionForBabylon = []; //The list of position in vectors
  105483. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  105484. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  105485. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  105486. var curPositionInIndices = 0;
  105487. var hasMeshes = false; //Meshes are defined in the file
  105488. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  105489. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  105490. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  105491. var triangles = []; //Indices from new triangles coming from polygons
  105492. var materialNameFromObj = ""; //The name of the current material
  105493. var fileToLoad = ""; //The name of the mtlFile to load
  105494. var materialsFromMTLFile = new MTLFileLoader();
  105495. var objMeshName = ""; //The name of the current obj mesh
  105496. var increment = 1; //Id for meshes created by the multimaterial
  105497. var isFirstMaterial = true;
  105498. /**
  105499. * Search for obj in the given array.
  105500. * This function is called to check if a couple of data already exists in an array.
  105501. *
  105502. * If found, returns the index of the founded tuple index. Returns -1 if not found
  105503. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  105504. * @param obj Array<number>
  105505. * @returns {boolean}
  105506. */
  105507. var isInArray = function (arr, obj) {
  105508. if (!arr[obj[0]])
  105509. arr[obj[0]] = { normals: [], idx: [] };
  105510. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  105511. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  105512. };
  105513. var isInArrayUV = function (arr, obj) {
  105514. if (!arr[obj[0]])
  105515. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  105516. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  105517. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  105518. return arr[obj[0]].idx[idx];
  105519. }
  105520. return -1;
  105521. };
  105522. /**
  105523. * This function set the data for each triangle.
  105524. * Data are position, normals and uvs
  105525. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  105526. * If the tuple already exist, add only their indice
  105527. *
  105528. * @param indicePositionFromObj Integer The index in positions array
  105529. * @param indiceUvsFromObj Integer The index in uvs array
  105530. * @param indiceNormalFromObj Integer The index in normals array
  105531. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  105532. * @param textureVectorFromOBJ Vector3 The value of uvs
  105533. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  105534. */
  105535. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  105536. //Check if this tuple already exists in the list of tuples
  105537. var _index;
  105538. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  105539. _index = isInArrayUV(tuplePosNorm, [
  105540. indicePositionFromObj,
  105541. indiceNormalFromObj,
  105542. indiceUvsFromObj
  105543. ]);
  105544. }
  105545. else {
  105546. _index = isInArray(tuplePosNorm, [
  105547. indicePositionFromObj,
  105548. indiceNormalFromObj
  105549. ]);
  105550. }
  105551. //If it not exists
  105552. if (_index == -1) {
  105553. //Add an new indice.
  105554. //The array of indices is only an array with his length equal to the number of triangles - 1.
  105555. //We add vertices data in this order
  105556. indicesForBabylon.push(wrappedPositionForBabylon.length);
  105557. //Push the position of vertice for Babylon
  105558. //Each element is a BABYLON.Vector3(x,y,z)
  105559. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  105560. //Push the uvs for Babylon
  105561. //Each element is a BABYLON.Vector3(u,v)
  105562. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  105563. //Push the normals for Babylon
  105564. //Each element is a BABYLON.Vector3(x,y,z)
  105565. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  105566. //Add the tuple in the comparison list
  105567. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  105568. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  105569. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  105570. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  105571. }
  105572. else {
  105573. //The tuple already exists
  105574. //Add the index of the already existing tuple
  105575. //At this index we can get the value of position, normal and uvs of vertex
  105576. indicesForBabylon.push(_index);
  105577. }
  105578. };
  105579. /**
  105580. * Transform BABYLON.Vector() object onto 3 digits in an array
  105581. */
  105582. var unwrapData = function () {
  105583. //Every array has the same length
  105584. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  105585. //Push the x, y, z values of each element in the unwrapped array
  105586. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  105587. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  105588. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  105589. }
  105590. // Reset arrays for the next new meshes
  105591. wrappedPositionForBabylon = [];
  105592. wrappedNormalsForBabylon = [];
  105593. wrappedUvsForBabylon = [];
  105594. tuplePosNorm = [];
  105595. curPositionInIndices = 0;
  105596. };
  105597. /**
  105598. * Create triangles from polygons by recursion
  105599. * The best to understand how it works is to draw it in the same time you get the recursion.
  105600. * It is important to notice that a triangle is a polygon
  105601. * We get 4 patterns of face defined in OBJ File :
  105602. * facePattern1 = ["1","2","3","4","5","6"]
  105603. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  105604. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  105605. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  105606. * Each pattern is divided by the same method
  105607. * @param face Array[String] The indices of elements
  105608. * @param v Integer The variable to increment
  105609. */
  105610. var getTriangles = function (face, v) {
  105611. //Work for each element of the array
  105612. if (v + 1 < face.length) {
  105613. //Add on the triangle variable the indexes to obtain triangles
  105614. triangles.push(face[0], face[v], face[v + 1]);
  105615. //Incrementation for recursion
  105616. v += 1;
  105617. //Recursion
  105618. getTriangles(face, v);
  105619. }
  105620. //Result obtained after 2 iterations:
  105621. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  105622. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  105623. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  105624. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  105625. };
  105626. /**
  105627. * Create triangles and push the data for each polygon for the pattern 1
  105628. * In this pattern we get vertice positions
  105629. * @param face
  105630. * @param v
  105631. */
  105632. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  105633. //Get the indices of triangles for each polygon
  105634. getTriangles(face, v);
  105635. //For each element in the triangles array.
  105636. //This var could contains 1 to an infinity of triangles
  105637. for (var k = 0; k < triangles.length; k++) {
  105638. // Set position indice
  105639. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  105640. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  105641. positions[indicePositionFromObj], //Get the vectors data
  105642. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  105643. );
  105644. }
  105645. //Reset variable for the next line
  105646. triangles = [];
  105647. };
  105648. /**
  105649. * Create triangles and push the data for each polygon for the pattern 2
  105650. * In this pattern we get vertice positions and uvsu
  105651. * @param face
  105652. * @param v
  105653. */
  105654. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  105655. //Get the indices of triangles for each polygon
  105656. getTriangles(face, v);
  105657. for (var k = 0; k < triangles.length; k++) {
  105658. //triangle[k] = "1/1"
  105659. //Split the data for getting position and uv
  105660. var point = triangles[k].split("/"); // ["1", "1"]
  105661. //Set position indice
  105662. var indicePositionFromObj = parseInt(point[0]) - 1;
  105663. //Set uv indice
  105664. var indiceUvsFromObj = parseInt(point[1]) - 1;
  105665. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  105666. positions[indicePositionFromObj], //Get the values for each element
  105667. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  105668. );
  105669. }
  105670. //Reset variable for the next line
  105671. triangles = [];
  105672. };
  105673. /**
  105674. * Create triangles and push the data for each polygon for the pattern 3
  105675. * In this pattern we get vertice positions, uvs and normals
  105676. * @param face
  105677. * @param v
  105678. */
  105679. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  105680. //Get the indices of triangles for each polygon
  105681. getTriangles(face, v);
  105682. for (var k = 0; k < triangles.length; k++) {
  105683. //triangle[k] = "1/1/1"
  105684. //Split the data for getting position, uv, and normals
  105685. var point = triangles[k].split("/"); // ["1", "1", "1"]
  105686. // Set position indice
  105687. var indicePositionFromObj = parseInt(point[0]) - 1;
  105688. // Set uv indice
  105689. var indiceUvsFromObj = parseInt(point[1]) - 1;
  105690. // Set normal indice
  105691. var indiceNormalFromObj = parseInt(point[2]) - 1;
  105692. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  105693. );
  105694. }
  105695. //Reset variable for the next line
  105696. triangles = [];
  105697. };
  105698. /**
  105699. * Create triangles and push the data for each polygon for the pattern 4
  105700. * In this pattern we get vertice positions and normals
  105701. * @param face
  105702. * @param v
  105703. */
  105704. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  105705. getTriangles(face, v);
  105706. for (var k = 0; k < triangles.length; k++) {
  105707. //triangle[k] = "1//1"
  105708. //Split the data for getting position and normals
  105709. var point = triangles[k].split("//"); // ["1", "1"]
  105710. // We check indices, and normals
  105711. var indicePositionFromObj = parseInt(point[0]) - 1;
  105712. var indiceNormalFromObj = parseInt(point[1]) - 1;
  105713. setData(indicePositionFromObj, 1, //Default value for uv
  105714. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  105715. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  105716. }
  105717. //Reset variable for the next line
  105718. triangles = [];
  105719. };
  105720. var addPreviousObjMesh = function () {
  105721. //Check if it is not the first mesh. Otherwise we don't have data.
  105722. if (meshesFromObj.length > 0) {
  105723. //Get the previous mesh for applying the data about the faces
  105724. //=> in obj file, faces definition append after the name of the mesh
  105725. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  105726. //Set the data into Array for the mesh
  105727. unwrapData();
  105728. // Reverse tab. Otherwise face are displayed in the wrong sens
  105729. indicesForBabylon.reverse();
  105730. //Set the information for the mesh
  105731. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  105732. handledMesh.indices = indicesForBabylon.slice();
  105733. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  105734. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  105735. handledMesh.uvs = unwrappedUVForBabylon.slice();
  105736. //Reset the array for the next mesh
  105737. indicesForBabylon = [];
  105738. unwrappedPositionsForBabylon = [];
  105739. unwrappedNormalsForBabylon = [];
  105740. unwrappedUVForBabylon = [];
  105741. }
  105742. };
  105743. //Main function
  105744. //Split the file into lines
  105745. var lines = data.split('\n');
  105746. //Look at each line
  105747. for (var i = 0; i < lines.length; i++) {
  105748. var line = lines[i].trim();
  105749. var result;
  105750. //Comment or newLine
  105751. if (line.length === 0 || line.charAt(0) === '#') {
  105752. continue;
  105753. //Get information about one position possible for the vertices
  105754. }
  105755. else if ((result = this.vertexPattern.exec(line)) !== null) {
  105756. //Create a Vector3 with the position x, y, z
  105757. //Value of result:
  105758. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  105759. //Add the Vector in the list of positions
  105760. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  105761. }
  105762. else if ((result = this.normalPattern.exec(line)) !== null) {
  105763. //Create a Vector3 with the normals x, y, z
  105764. //Value of result
  105765. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  105766. //Add the Vector in the list of normals
  105767. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  105768. }
  105769. else if ((result = this.uvPattern.exec(line)) !== null) {
  105770. //Create a Vector2 with the normals u, v
  105771. //Value of result
  105772. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  105773. //Add the Vector in the list of uvs
  105774. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  105775. //Identify patterns of faces
  105776. //Face could be defined in different type of pattern
  105777. }
  105778. else if ((result = this.facePattern3.exec(line)) !== null) {
  105779. //Value of result:
  105780. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  105781. //Set the data for this face
  105782. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  105783. 1);
  105784. }
  105785. else if ((result = this.facePattern4.exec(line)) !== null) {
  105786. //Value of result:
  105787. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  105788. //Set the data for this face
  105789. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  105790. 1);
  105791. }
  105792. else if ((result = this.facePattern2.exec(line)) !== null) {
  105793. //Value of result:
  105794. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  105795. //Set the data for this face
  105796. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  105797. 1);
  105798. }
  105799. else if ((result = this.facePattern1.exec(line)) !== null) {
  105800. //Value of result
  105801. //["f 1 2 3", "1 2 3"...]
  105802. //Set the data for this face
  105803. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  105804. 1);
  105805. //Define a mesh or an object
  105806. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  105807. }
  105808. else if (this.group.test(line) || this.obj.test(line)) {
  105809. //Create a new mesh corresponding to the name of the group.
  105810. //Definition of the mesh
  105811. var objMesh =
  105812. //Set the name of the current obj mesh
  105813. {
  105814. name: line.substring(2).trim(),
  105815. indices: undefined,
  105816. positions: undefined,
  105817. normals: undefined,
  105818. uvs: undefined,
  105819. materialName: ""
  105820. };
  105821. addPreviousObjMesh();
  105822. //Push the last mesh created with only the name
  105823. meshesFromObj.push(objMesh);
  105824. //Set this variable to indicate that now meshesFromObj has objects defined inside
  105825. hasMeshes = true;
  105826. isFirstMaterial = true;
  105827. increment = 1;
  105828. //Keyword for applying a material
  105829. }
  105830. else if (this.usemtl.test(line)) {
  105831. //Get the name of the material
  105832. materialNameFromObj = line.substring(7).trim();
  105833. //If this new material is in the same mesh
  105834. if (!isFirstMaterial) {
  105835. //Set the data for the previous mesh
  105836. addPreviousObjMesh();
  105837. //Create a new mesh
  105838. var objMesh =
  105839. //Set the name of the current obj mesh
  105840. {
  105841. name: objMeshName + "_mm" + increment.toString(),
  105842. indices: undefined,
  105843. positions: undefined,
  105844. normals: undefined,
  105845. uvs: undefined,
  105846. materialName: materialNameFromObj
  105847. };
  105848. increment++;
  105849. //If meshes are already defined
  105850. meshesFromObj.push(objMesh);
  105851. }
  105852. //Set the material name if the previous line define a mesh
  105853. if (hasMeshes && isFirstMaterial) {
  105854. //Set the material name to the previous mesh (1 material per mesh)
  105855. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  105856. isFirstMaterial = false;
  105857. }
  105858. //Keyword for loading the mtl file
  105859. }
  105860. else if (this.mtllib.test(line)) {
  105861. //Get the name of mtl file
  105862. fileToLoad = line.substring(7).trim();
  105863. //Apply smoothing
  105864. }
  105865. else if (this.smooth.test(line)) {
  105866. // smooth shading => apply smoothing
  105867. //Toda y I don't know it work with babylon and with obj.
  105868. //With the obj file an integer is set
  105869. }
  105870. else {
  105871. //If there is another possibility
  105872. console.log("Unhandled expression at line : " + line);
  105873. }
  105874. }
  105875. //At the end of the file, add the last mesh into the meshesFromObj array
  105876. if (hasMeshes) {
  105877. //Set the data for the last mesh
  105878. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  105879. //Reverse indices for displaying faces in the good sens
  105880. indicesForBabylon.reverse();
  105881. //Get the good array
  105882. unwrapData();
  105883. //Set array
  105884. handledMesh.indices = indicesForBabylon;
  105885. handledMesh.positions = unwrappedPositionsForBabylon;
  105886. handledMesh.normals = unwrappedNormalsForBabylon;
  105887. handledMesh.uvs = unwrappedUVForBabylon;
  105888. }
  105889. //If any o or g keyword found, create a mesj with a random id
  105890. if (!hasMeshes) {
  105891. // reverse tab of indices
  105892. indicesForBabylon.reverse();
  105893. //Get positions normals uvs
  105894. unwrapData();
  105895. //Set data for one mesh
  105896. meshesFromObj.push({
  105897. name: BABYLON.Geometry.RandomId(),
  105898. indices: indicesForBabylon,
  105899. positions: unwrappedPositionsForBabylon,
  105900. normals: unwrappedNormalsForBabylon,
  105901. uvs: unwrappedUVForBabylon,
  105902. materialName: materialNameFromObj
  105903. });
  105904. }
  105905. //Create a BABYLON.Mesh list
  105906. var babylonMeshesArray = []; //The mesh for babylon
  105907. var materialToUse = new Array();
  105908. //Set data for each mesh
  105909. for (var j = 0; j < meshesFromObj.length; j++) {
  105910. //check meshesNames (stlFileLoader)
  105911. if (meshesNames && meshesFromObj[j].name) {
  105912. if (meshesNames instanceof Array) {
  105913. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  105914. continue;
  105915. }
  105916. }
  105917. else {
  105918. if (meshesFromObj[j].name !== meshesNames) {
  105919. continue;
  105920. }
  105921. }
  105922. }
  105923. //Get the current mesh
  105924. //Set the data with VertexBuffer for each mesh
  105925. handledMesh = meshesFromObj[j];
  105926. //Create a BABYLON.Mesh with the name of the obj mesh
  105927. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  105928. //Push the name of the material to an array
  105929. //This is indispensable for the importMesh function
  105930. materialToUse.push(meshesFromObj[j].materialName);
  105931. var vertexData = new BABYLON.VertexData(); //The container for the values
  105932. //Set the data for the babylonMesh
  105933. vertexData.positions = handledMesh.positions;
  105934. vertexData.normals = handledMesh.normals;
  105935. vertexData.uvs = handledMesh.uvs;
  105936. vertexData.indices = handledMesh.indices;
  105937. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  105938. vertexData.applyToMesh(babylonMesh);
  105939. //Push the mesh into an array
  105940. babylonMeshesArray.push(babylonMesh);
  105941. }
  105942. //load the materials
  105943. //Check if we have a file to load
  105944. if (fileToLoad !== "") {
  105945. //Load the file synchronously
  105946. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  105947. //Create materials thanks MTLLoader function
  105948. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  105949. //Look at each material loaded in the mtl file
  105950. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  105951. //Three variables to get all meshes with the same material
  105952. var startIndex = 0;
  105953. var _indices = [];
  105954. var _index;
  105955. //The material from MTL file is used in the meshes loaded
  105956. //Push the indice in an array
  105957. //Check if the material is not used for another mesh
  105958. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  105959. _indices.push(_index);
  105960. startIndex = _index + 1;
  105961. }
  105962. //If the material is not used dispose it
  105963. if (_index == -1 && _indices.length == 0) {
  105964. //If the material is not needed, remove it
  105965. materialsFromMTLFile.materials[n].dispose();
  105966. }
  105967. else {
  105968. for (var o = 0; o < _indices.length; o++) {
  105969. //Apply the material to the BABYLON.Mesh for each mesh with the material
  105970. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  105971. }
  105972. }
  105973. }
  105974. });
  105975. }
  105976. //Return an array with all BABYLON.Mesh
  105977. return babylonMeshesArray;
  105978. };
  105979. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  105980. return OBJFileLoader;
  105981. }());
  105982. BABYLON.OBJFileLoader = OBJFileLoader;
  105983. if (BABYLON.SceneLoader) {
  105984. //Add this loader into the register plugin
  105985. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  105986. }
  105987. })(BABYLON || (BABYLON = {}));
  105988. //# sourceMappingURL=babylon.objFileLoader.js.map
  105989. var BABYLON;
  105990. (function (BABYLON) {
  105991. var GLTFLoaderCoordinateSystemMode;
  105992. (function (GLTFLoaderCoordinateSystemMode) {
  105993. /**
  105994. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  105995. */
  105996. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  105997. /**
  105998. * Sets the useRightHandedSystem flag on the scene.
  105999. */
  106000. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  106001. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  106002. var GLTFLoaderAnimationStartMode;
  106003. (function (GLTFLoaderAnimationStartMode) {
  106004. /**
  106005. * No animation will start.
  106006. */
  106007. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  106008. /**
  106009. * The first animation will start.
  106010. */
  106011. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  106012. /**
  106013. * All animations will start.
  106014. */
  106015. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  106016. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  106017. var GLTFLoaderState;
  106018. (function (GLTFLoaderState) {
  106019. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  106020. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  106021. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  106022. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  106023. var GLTFFileLoader = /** @class */ (function () {
  106024. function GLTFFileLoader() {
  106025. // #region Common options
  106026. /**
  106027. * Raised when the asset has been parsed.
  106028. * The data.json property stores the glTF JSON.
  106029. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  106030. */
  106031. this.onParsedObservable = new BABYLON.Observable();
  106032. // #endregion
  106033. // #region V2 options
  106034. /**
  106035. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  106036. */
  106037. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  106038. /**
  106039. * The animation start mode (NONE, FIRST, ALL).
  106040. */
  106041. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  106042. /**
  106043. * Set to true to compile materials before raising the success callback.
  106044. */
  106045. this.compileMaterials = false;
  106046. /**
  106047. * Set to true to also compile materials with clip planes.
  106048. */
  106049. this.useClipPlane = false;
  106050. /**
  106051. * Set to true to compile shadow generators before raising the success callback.
  106052. */
  106053. this.compileShadowGenerators = false;
  106054. /**
  106055. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  106056. */
  106057. this.onMeshLoadedObservable = new BABYLON.Observable();
  106058. /**
  106059. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  106060. */
  106061. this.onTextureLoadedObservable = new BABYLON.Observable();
  106062. /**
  106063. * Raised when the loader creates a material after parsing the glTF properties of the material.
  106064. */
  106065. this.onMaterialLoadedObservable = new BABYLON.Observable();
  106066. /**
  106067. * Raised when the loader creates an animation group after parsing the glTF properties of the animation.
  106068. */
  106069. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  106070. /**
  106071. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  106072. * For assets with LODs, raised when all of the LODs are complete.
  106073. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  106074. */
  106075. this.onCompleteObservable = new BABYLON.Observable();
  106076. /**
  106077. * Raised when the loader is disposed.
  106078. */
  106079. this.onDisposeObservable = new BABYLON.Observable();
  106080. /**
  106081. * Raised after a loader extension is created.
  106082. * Set additional options for a loader extension in this event.
  106083. */
  106084. this.onExtensionLoadedObservable = new BABYLON.Observable();
  106085. // #endregion
  106086. this._loader = null;
  106087. this.name = "gltf";
  106088. this.extensions = {
  106089. ".gltf": { isBinary: false },
  106090. ".glb": { isBinary: true }
  106091. };
  106092. }
  106093. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  106094. set: function (callback) {
  106095. if (this._onParsedObserver) {
  106096. this.onParsedObservable.remove(this._onParsedObserver);
  106097. }
  106098. this._onParsedObserver = this.onParsedObservable.add(callback);
  106099. },
  106100. enumerable: true,
  106101. configurable: true
  106102. });
  106103. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  106104. set: function (callback) {
  106105. if (this._onMeshLoadedObserver) {
  106106. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  106107. }
  106108. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  106109. },
  106110. enumerable: true,
  106111. configurable: true
  106112. });
  106113. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  106114. set: function (callback) {
  106115. if (this._onTextureLoadedObserver) {
  106116. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  106117. }
  106118. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  106119. },
  106120. enumerable: true,
  106121. configurable: true
  106122. });
  106123. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  106124. set: function (callback) {
  106125. if (this._onMaterialLoadedObserver) {
  106126. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  106127. }
  106128. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  106129. },
  106130. enumerable: true,
  106131. configurable: true
  106132. });
  106133. Object.defineProperty(GLTFFileLoader.prototype, "onAnimationGroupLoaded", {
  106134. set: function (callback) {
  106135. if (this._onAnimationGroupLoadedObserver) {
  106136. this.onAnimationGroupLoadedObservable.remove(this._onAnimationGroupLoadedObserver);
  106137. }
  106138. this._onAnimationGroupLoadedObserver = this.onAnimationGroupLoadedObservable.add(callback);
  106139. },
  106140. enumerable: true,
  106141. configurable: true
  106142. });
  106143. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  106144. set: function (callback) {
  106145. if (this._onCompleteObserver) {
  106146. this.onCompleteObservable.remove(this._onCompleteObserver);
  106147. }
  106148. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  106149. },
  106150. enumerable: true,
  106151. configurable: true
  106152. });
  106153. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  106154. set: function (callback) {
  106155. if (this._onDisposeObserver) {
  106156. this.onDisposeObservable.remove(this._onDisposeObserver);
  106157. }
  106158. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  106159. },
  106160. enumerable: true,
  106161. configurable: true
  106162. });
  106163. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  106164. set: function (callback) {
  106165. if (this._onExtensionLoadedObserver) {
  106166. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  106167. }
  106168. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  106169. },
  106170. enumerable: true,
  106171. configurable: true
  106172. });
  106173. /**
  106174. * Gets a promise that resolves when the asset is completely loaded.
  106175. * @returns A promise that resolves when the asset is completely loaded.
  106176. */
  106177. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  106178. var _this = this;
  106179. return new Promise(function (resolve) {
  106180. _this.onCompleteObservable.add(function () {
  106181. resolve();
  106182. }, undefined, undefined, undefined, true);
  106183. });
  106184. };
  106185. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  106186. /**
  106187. * The loader state or null if not active.
  106188. */
  106189. get: function () {
  106190. return this._loader ? this._loader.state : null;
  106191. },
  106192. enumerable: true,
  106193. configurable: true
  106194. });
  106195. /**
  106196. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  106197. */
  106198. GLTFFileLoader.prototype.dispose = function () {
  106199. if (this._loader) {
  106200. this._loader.dispose();
  106201. this._loader = null;
  106202. }
  106203. this.onMeshLoadedObservable.clear();
  106204. this.onTextureLoadedObservable.clear();
  106205. this.onMaterialLoadedObservable.clear();
  106206. this.onDisposeObservable.notifyObservers(this);
  106207. this.onDisposeObservable.clear();
  106208. };
  106209. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  106210. var _this = this;
  106211. return Promise.resolve().then(function () {
  106212. var loaderData = _this._parse(data);
  106213. _this._loader = _this._getLoader(loaderData);
  106214. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  106215. });
  106216. };
  106217. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  106218. var _this = this;
  106219. return Promise.resolve().then(function () {
  106220. var loaderData = _this._parse(data);
  106221. _this._loader = _this._getLoader(loaderData);
  106222. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  106223. });
  106224. };
  106225. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  106226. var _this = this;
  106227. return Promise.resolve().then(function () {
  106228. var loaderData = _this._parse(data);
  106229. _this._loader = _this._getLoader(loaderData);
  106230. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  106231. var container = new BABYLON.AssetContainer(scene);
  106232. Array.prototype.push.apply(container.meshes, result.meshes);
  106233. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  106234. Array.prototype.push.apply(container.skeletons, result.skeletons);
  106235. container.removeAllFromScene();
  106236. return container;
  106237. });
  106238. });
  106239. };
  106240. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  106241. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  106242. };
  106243. GLTFFileLoader.prototype.createPlugin = function () {
  106244. return new GLTFFileLoader();
  106245. };
  106246. GLTFFileLoader.prototype._parse = function (data) {
  106247. var parsedData;
  106248. if (data instanceof ArrayBuffer) {
  106249. parsedData = GLTFFileLoader._parseBinary(data);
  106250. }
  106251. else {
  106252. parsedData = {
  106253. json: JSON.parse(data),
  106254. bin: null
  106255. };
  106256. }
  106257. this.onParsedObservable.notifyObservers(parsedData);
  106258. this.onParsedObservable.clear();
  106259. return parsedData;
  106260. };
  106261. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  106262. var _this = this;
  106263. var loaderVersion = { major: 2, minor: 0 };
  106264. var asset = loaderData.json.asset || {};
  106265. var version = GLTFFileLoader._parseVersion(asset.version);
  106266. if (!version) {
  106267. throw new Error("Invalid version: " + asset.version);
  106268. }
  106269. if (asset.minVersion !== undefined) {
  106270. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  106271. if (!minVersion) {
  106272. throw new Error("Invalid minimum version: " + asset.minVersion);
  106273. }
  106274. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  106275. throw new Error("Incompatible minimum version: " + asset.minVersion);
  106276. }
  106277. }
  106278. var createLoaders = {
  106279. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  106280. 2: GLTFFileLoader.CreateGLTFLoaderV2
  106281. };
  106282. var createLoader = createLoaders[version.major];
  106283. if (!createLoader) {
  106284. throw new Error("Unsupported version: " + asset.version);
  106285. }
  106286. var loader = createLoader();
  106287. loader.coordinateSystemMode = this.coordinateSystemMode;
  106288. loader.animationStartMode = this.animationStartMode;
  106289. loader.compileMaterials = this.compileMaterials;
  106290. loader.useClipPlane = this.useClipPlane;
  106291. loader.compileShadowGenerators = this.compileShadowGenerators;
  106292. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  106293. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  106294. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  106295. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  106296. loader.onCompleteObservable.add(function () {
  106297. _this.onMeshLoadedObservable.clear();
  106298. _this.onTextureLoadedObservable.clear();
  106299. _this.onMaterialLoadedObservable.clear();
  106300. _this.onCompleteObservable.notifyObservers(_this);
  106301. _this.onCompleteObservable.clear();
  106302. });
  106303. return loader;
  106304. };
  106305. GLTFFileLoader._parseBinary = function (data) {
  106306. var Binary = {
  106307. Magic: 0x46546C67
  106308. };
  106309. var binaryReader = new BinaryReader(data);
  106310. var magic = binaryReader.readUint32();
  106311. if (magic !== Binary.Magic) {
  106312. throw new Error("Unexpected magic: " + magic);
  106313. }
  106314. var version = binaryReader.readUint32();
  106315. switch (version) {
  106316. case 1: return GLTFFileLoader._parseV1(binaryReader);
  106317. case 2: return GLTFFileLoader._parseV2(binaryReader);
  106318. }
  106319. throw new Error("Unsupported version: " + version);
  106320. };
  106321. GLTFFileLoader._parseV1 = function (binaryReader) {
  106322. var ContentFormat = {
  106323. JSON: 0
  106324. };
  106325. var length = binaryReader.readUint32();
  106326. if (length != binaryReader.getLength()) {
  106327. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  106328. }
  106329. var contentLength = binaryReader.readUint32();
  106330. var contentFormat = binaryReader.readUint32();
  106331. var content;
  106332. switch (contentFormat) {
  106333. case ContentFormat.JSON: {
  106334. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  106335. break;
  106336. }
  106337. default: {
  106338. throw new Error("Unexpected content format: " + contentFormat);
  106339. }
  106340. }
  106341. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  106342. var body = binaryReader.readUint8Array(bytesRemaining);
  106343. return {
  106344. json: content,
  106345. bin: body
  106346. };
  106347. };
  106348. GLTFFileLoader._parseV2 = function (binaryReader) {
  106349. var ChunkFormat = {
  106350. JSON: 0x4E4F534A,
  106351. BIN: 0x004E4942
  106352. };
  106353. var length = binaryReader.readUint32();
  106354. if (length !== binaryReader.getLength()) {
  106355. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  106356. }
  106357. // JSON chunk
  106358. var chunkLength = binaryReader.readUint32();
  106359. var chunkFormat = binaryReader.readUint32();
  106360. if (chunkFormat !== ChunkFormat.JSON) {
  106361. throw new Error("First chunk format is not JSON");
  106362. }
  106363. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  106364. // Look for BIN chunk
  106365. var bin = null;
  106366. while (binaryReader.getPosition() < binaryReader.getLength()) {
  106367. var chunkLength_1 = binaryReader.readUint32();
  106368. var chunkFormat_1 = binaryReader.readUint32();
  106369. switch (chunkFormat_1) {
  106370. case ChunkFormat.JSON: {
  106371. throw new Error("Unexpected JSON chunk");
  106372. }
  106373. case ChunkFormat.BIN: {
  106374. bin = binaryReader.readUint8Array(chunkLength_1);
  106375. break;
  106376. }
  106377. default: {
  106378. // ignore unrecognized chunkFormat
  106379. binaryReader.skipBytes(chunkLength_1);
  106380. break;
  106381. }
  106382. }
  106383. }
  106384. return {
  106385. json: json,
  106386. bin: bin
  106387. };
  106388. };
  106389. GLTFFileLoader._parseVersion = function (version) {
  106390. if (version === "1.0" || version === "1.0.1") {
  106391. return {
  106392. major: 1,
  106393. minor: 0
  106394. };
  106395. }
  106396. var match = (version + "").match(/^(\d+)\.(\d+)/);
  106397. if (!match) {
  106398. return null;
  106399. }
  106400. return {
  106401. major: parseInt(match[1]),
  106402. minor: parseInt(match[2])
  106403. };
  106404. };
  106405. GLTFFileLoader._compareVersion = function (a, b) {
  106406. if (a.major > b.major)
  106407. return 1;
  106408. if (a.major < b.major)
  106409. return -1;
  106410. if (a.minor > b.minor)
  106411. return 1;
  106412. if (a.minor < b.minor)
  106413. return -1;
  106414. return 0;
  106415. };
  106416. GLTFFileLoader._decodeBufferToText = function (buffer) {
  106417. var result = "";
  106418. var length = buffer.byteLength;
  106419. for (var i = 0; i < length; i++) {
  106420. result += String.fromCharCode(buffer[i]);
  106421. }
  106422. return result;
  106423. };
  106424. // #endregion
  106425. // #region V1 options
  106426. GLTFFileLoader.IncrementalLoading = true;
  106427. GLTFFileLoader.HomogeneousCoordinates = false;
  106428. return GLTFFileLoader;
  106429. }());
  106430. BABYLON.GLTFFileLoader = GLTFFileLoader;
  106431. var BinaryReader = /** @class */ (function () {
  106432. function BinaryReader(arrayBuffer) {
  106433. this._arrayBuffer = arrayBuffer;
  106434. this._dataView = new DataView(arrayBuffer);
  106435. this._byteOffset = 0;
  106436. }
  106437. BinaryReader.prototype.getPosition = function () {
  106438. return this._byteOffset;
  106439. };
  106440. BinaryReader.prototype.getLength = function () {
  106441. return this._arrayBuffer.byteLength;
  106442. };
  106443. BinaryReader.prototype.readUint32 = function () {
  106444. var value = this._dataView.getUint32(this._byteOffset, true);
  106445. this._byteOffset += 4;
  106446. return value;
  106447. };
  106448. BinaryReader.prototype.readUint8Array = function (length) {
  106449. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  106450. this._byteOffset += length;
  106451. return value;
  106452. };
  106453. BinaryReader.prototype.skipBytes = function (length) {
  106454. this._byteOffset += length;
  106455. };
  106456. return BinaryReader;
  106457. }());
  106458. if (BABYLON.SceneLoader) {
  106459. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  106460. }
  106461. })(BABYLON || (BABYLON = {}));
  106462. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  106463. var BABYLON;
  106464. (function (BABYLON) {
  106465. var GLTF1;
  106466. (function (GLTF1) {
  106467. /**
  106468. * Enums
  106469. */
  106470. var EComponentType;
  106471. (function (EComponentType) {
  106472. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  106473. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  106474. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  106475. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  106476. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  106477. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  106478. var EShaderType;
  106479. (function (EShaderType) {
  106480. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  106481. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  106482. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  106483. var EParameterType;
  106484. (function (EParameterType) {
  106485. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  106486. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  106487. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  106488. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  106489. EParameterType[EParameterType["INT"] = 5124] = "INT";
  106490. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  106491. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  106492. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  106493. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  106494. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  106495. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  106496. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  106497. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  106498. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  106499. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  106500. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  106501. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  106502. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  106503. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  106504. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  106505. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  106506. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  106507. var ETextureWrapMode;
  106508. (function (ETextureWrapMode) {
  106509. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  106510. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  106511. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  106512. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  106513. var ETextureFilterType;
  106514. (function (ETextureFilterType) {
  106515. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  106516. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  106517. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  106518. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  106519. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  106520. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  106521. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  106522. var ETextureFormat;
  106523. (function (ETextureFormat) {
  106524. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  106525. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  106526. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  106527. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  106528. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  106529. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  106530. var ECullingType;
  106531. (function (ECullingType) {
  106532. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  106533. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  106534. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  106535. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  106536. var EBlendingFunction;
  106537. (function (EBlendingFunction) {
  106538. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  106539. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  106540. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  106541. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  106542. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  106543. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  106544. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  106545. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  106546. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  106547. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  106548. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  106549. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  106550. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  106551. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  106552. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  106553. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  106554. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106555. })(BABYLON || (BABYLON = {}));
  106556. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  106557. var BABYLON;
  106558. (function (BABYLON) {
  106559. var GLTF1;
  106560. (function (GLTF1) {
  106561. /**
  106562. * Tokenizer. Used for shaders compatibility
  106563. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  106564. */
  106565. var ETokenType;
  106566. (function (ETokenType) {
  106567. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  106568. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  106569. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  106570. })(ETokenType || (ETokenType = {}));
  106571. var Tokenizer = /** @class */ (function () {
  106572. function Tokenizer(toParse) {
  106573. this._pos = 0;
  106574. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  106575. this._toParse = toParse;
  106576. this._maxPos = toParse.length;
  106577. }
  106578. Tokenizer.prototype.getNextToken = function () {
  106579. if (this.isEnd())
  106580. return ETokenType.END_OF_INPUT;
  106581. this.currentString = this.read();
  106582. this.currentToken = ETokenType.UNKNOWN;
  106583. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  106584. this.currentToken = ETokenType.IDENTIFIER;
  106585. this.currentIdentifier = this.currentString;
  106586. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  106587. this.currentIdentifier += this.currentString;
  106588. this.forward();
  106589. }
  106590. }
  106591. return this.currentToken;
  106592. };
  106593. Tokenizer.prototype.peek = function () {
  106594. return this._toParse[this._pos];
  106595. };
  106596. Tokenizer.prototype.read = function () {
  106597. return this._toParse[this._pos++];
  106598. };
  106599. Tokenizer.prototype.forward = function () {
  106600. this._pos++;
  106601. };
  106602. Tokenizer.prototype.isEnd = function () {
  106603. return this._pos >= this._maxPos;
  106604. };
  106605. return Tokenizer;
  106606. }());
  106607. /**
  106608. * Values
  106609. */
  106610. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  106611. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  106612. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  106613. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  106614. /**
  106615. * Parse
  106616. */
  106617. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  106618. for (var buf in parsedBuffers) {
  106619. var parsedBuffer = parsedBuffers[buf];
  106620. gltfRuntime.buffers[buf] = parsedBuffer;
  106621. gltfRuntime.buffersCount++;
  106622. }
  106623. };
  106624. var parseShaders = function (parsedShaders, gltfRuntime) {
  106625. for (var sha in parsedShaders) {
  106626. var parsedShader = parsedShaders[sha];
  106627. gltfRuntime.shaders[sha] = parsedShader;
  106628. gltfRuntime.shaderscount++;
  106629. }
  106630. };
  106631. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  106632. for (var object in parsedObjects) {
  106633. var parsedObject = parsedObjects[object];
  106634. gltfRuntime[runtimeProperty][object] = parsedObject;
  106635. }
  106636. };
  106637. /**
  106638. * Utils
  106639. */
  106640. var normalizeUVs = function (buffer) {
  106641. if (!buffer) {
  106642. return;
  106643. }
  106644. for (var i = 0; i < buffer.length / 2; i++) {
  106645. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  106646. }
  106647. };
  106648. var getAttribute = function (attributeParameter) {
  106649. if (attributeParameter.semantic === "NORMAL") {
  106650. return "normal";
  106651. }
  106652. else if (attributeParameter.semantic === "POSITION") {
  106653. return "position";
  106654. }
  106655. else if (attributeParameter.semantic === "JOINT") {
  106656. return "matricesIndices";
  106657. }
  106658. else if (attributeParameter.semantic === "WEIGHT") {
  106659. return "matricesWeights";
  106660. }
  106661. else if (attributeParameter.semantic === "COLOR") {
  106662. return "color";
  106663. }
  106664. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  106665. var channel = Number(attributeParameter.semantic.split("_")[1]);
  106666. return "uv" + (channel === 0 ? "" : channel + 1);
  106667. }
  106668. return null;
  106669. };
  106670. /**
  106671. * Loads and creates animations
  106672. */
  106673. var loadAnimations = function (gltfRuntime) {
  106674. for (var anim in gltfRuntime.animations) {
  106675. var animation = gltfRuntime.animations[anim];
  106676. if (!animation.channels || !animation.samplers) {
  106677. continue;
  106678. }
  106679. var lastAnimation = null;
  106680. for (var i = 0; i < animation.channels.length; i++) {
  106681. // Get parameters and load buffers
  106682. var channel = animation.channels[i];
  106683. var sampler = animation.samplers[channel.sampler];
  106684. if (!sampler) {
  106685. continue;
  106686. }
  106687. var inputData = null;
  106688. var outputData = null;
  106689. if (animation.parameters) {
  106690. inputData = animation.parameters[sampler.input];
  106691. outputData = animation.parameters[sampler.output];
  106692. }
  106693. else {
  106694. inputData = sampler.input;
  106695. outputData = sampler.output;
  106696. }
  106697. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  106698. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  106699. var targetID = channel.target.id;
  106700. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  106701. if (targetNode === null) {
  106702. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  106703. }
  106704. if (targetNode === null) {
  106705. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  106706. continue;
  106707. }
  106708. var isBone = targetNode instanceof BABYLON.Bone;
  106709. // Get target path (position, rotation or scaling)
  106710. var targetPath = channel.target.path;
  106711. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  106712. if (targetPathIndex !== -1) {
  106713. targetPath = babylonAnimationPaths[targetPathIndex];
  106714. }
  106715. // Determine animation type
  106716. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  106717. if (!isBone) {
  106718. if (targetPath === "rotationQuaternion") {
  106719. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  106720. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  106721. }
  106722. else {
  106723. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  106724. }
  106725. }
  106726. // Create animation and key frames
  106727. var babylonAnimation = null;
  106728. var keys = [];
  106729. var arrayOffset = 0;
  106730. var modifyKey = false;
  106731. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  106732. babylonAnimation = lastAnimation;
  106733. modifyKey = true;
  106734. }
  106735. if (!modifyKey) {
  106736. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  106737. }
  106738. // For each frame
  106739. for (var j = 0; j < bufferInput.length; j++) {
  106740. var value = null;
  106741. if (targetPath === "rotationQuaternion") {
  106742. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  106743. arrayOffset += 4;
  106744. }
  106745. else {
  106746. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  106747. arrayOffset += 3;
  106748. }
  106749. if (isBone) {
  106750. var bone = targetNode;
  106751. var translation = BABYLON.Vector3.Zero();
  106752. var rotationQuaternion = new BABYLON.Quaternion();
  106753. var scaling = BABYLON.Vector3.Zero();
  106754. // Warning on decompose
  106755. var mat = bone.getBaseMatrix();
  106756. if (modifyKey && lastAnimation) {
  106757. mat = lastAnimation.getKeys()[j].value;
  106758. }
  106759. mat.decompose(scaling, rotationQuaternion, translation);
  106760. if (targetPath === "position") {
  106761. translation = value;
  106762. }
  106763. else if (targetPath === "rotationQuaternion") {
  106764. rotationQuaternion = value;
  106765. }
  106766. else {
  106767. scaling = value;
  106768. }
  106769. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  106770. }
  106771. if (!modifyKey) {
  106772. keys.push({
  106773. frame: bufferInput[j],
  106774. value: value
  106775. });
  106776. }
  106777. else if (lastAnimation) {
  106778. lastAnimation.getKeys()[j].value = value;
  106779. }
  106780. }
  106781. // Finish
  106782. if (!modifyKey && babylonAnimation) {
  106783. babylonAnimation.setKeys(keys);
  106784. targetNode.animations.push(babylonAnimation);
  106785. }
  106786. lastAnimation = babylonAnimation;
  106787. gltfRuntime.scene.stopAnimation(targetNode);
  106788. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  106789. }
  106790. }
  106791. };
  106792. /**
  106793. * Returns the bones transformation matrix
  106794. */
  106795. var configureBoneTransformation = function (node) {
  106796. var mat = null;
  106797. if (node.translation || node.rotation || node.scale) {
  106798. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  106799. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  106800. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  106801. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  106802. }
  106803. else {
  106804. mat = BABYLON.Matrix.FromArray(node.matrix);
  106805. }
  106806. return mat;
  106807. };
  106808. /**
  106809. * Returns the parent bone
  106810. */
  106811. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  106812. // Try to find
  106813. for (var i = 0; i < newSkeleton.bones.length; i++) {
  106814. if (newSkeleton.bones[i].name === jointName) {
  106815. return newSkeleton.bones[i];
  106816. }
  106817. }
  106818. // Not found, search in gltf nodes
  106819. var nodes = gltfRuntime.nodes;
  106820. for (var nde in nodes) {
  106821. var node = nodes[nde];
  106822. if (!node.jointName) {
  106823. continue;
  106824. }
  106825. var children = node.children;
  106826. for (var i = 0; i < children.length; i++) {
  106827. var child = gltfRuntime.nodes[children[i]];
  106828. if (!child.jointName) {
  106829. continue;
  106830. }
  106831. if (child.jointName === jointName) {
  106832. var mat = configureBoneTransformation(node);
  106833. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  106834. bone.id = nde;
  106835. return bone;
  106836. }
  106837. }
  106838. }
  106839. return null;
  106840. };
  106841. /**
  106842. * Returns the appropriate root node
  106843. */
  106844. var getNodeToRoot = function (nodesToRoot, id) {
  106845. for (var i = 0; i < nodesToRoot.length; i++) {
  106846. var nodeToRoot = nodesToRoot[i];
  106847. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  106848. var child = nodeToRoot.node.children[j];
  106849. if (child === id) {
  106850. return nodeToRoot.bone;
  106851. }
  106852. }
  106853. }
  106854. return null;
  106855. };
  106856. /**
  106857. * Returns the node with the joint name
  106858. */
  106859. var getJointNode = function (gltfRuntime, jointName) {
  106860. var nodes = gltfRuntime.nodes;
  106861. var node = nodes[jointName];
  106862. if (node) {
  106863. return {
  106864. node: node,
  106865. id: jointName
  106866. };
  106867. }
  106868. for (var nde in nodes) {
  106869. node = nodes[nde];
  106870. if (node.jointName === jointName) {
  106871. return {
  106872. node: node,
  106873. id: nde
  106874. };
  106875. }
  106876. }
  106877. return null;
  106878. };
  106879. /**
  106880. * Checks if a nodes is in joints
  106881. */
  106882. var nodeIsInJoints = function (skins, id) {
  106883. for (var i = 0; i < skins.jointNames.length; i++) {
  106884. if (skins.jointNames[i] === id) {
  106885. return true;
  106886. }
  106887. }
  106888. return false;
  106889. };
  106890. /**
  106891. * Fills the nodes to root for bones and builds hierarchy
  106892. */
  106893. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  106894. // Creates nodes for root
  106895. for (var nde in gltfRuntime.nodes) {
  106896. var node = gltfRuntime.nodes[nde];
  106897. var id = nde;
  106898. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  106899. continue;
  106900. }
  106901. // Create node to root bone
  106902. var mat = configureBoneTransformation(node);
  106903. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  106904. bone.id = id;
  106905. nodesToRoot.push({ bone: bone, node: node, id: id });
  106906. }
  106907. // Parenting
  106908. for (var i = 0; i < nodesToRoot.length; i++) {
  106909. var nodeToRoot = nodesToRoot[i];
  106910. var children = nodeToRoot.node.children;
  106911. for (var j = 0; j < children.length; j++) {
  106912. var child = null;
  106913. for (var k = 0; k < nodesToRoot.length; k++) {
  106914. if (nodesToRoot[k].id === children[j]) {
  106915. child = nodesToRoot[k];
  106916. break;
  106917. }
  106918. }
  106919. if (child) {
  106920. child.bone._parent = nodeToRoot.bone;
  106921. nodeToRoot.bone.children.push(child.bone);
  106922. }
  106923. }
  106924. }
  106925. };
  106926. /**
  106927. * Imports a skeleton
  106928. */
  106929. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  106930. if (!newSkeleton) {
  106931. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  106932. }
  106933. if (!skins.babylonSkeleton) {
  106934. return newSkeleton;
  106935. }
  106936. // Find the root bones
  106937. var nodesToRoot = [];
  106938. var nodesToRootToAdd = [];
  106939. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  106940. newSkeleton.bones = [];
  106941. // Joints
  106942. for (var i = 0; i < skins.jointNames.length; i++) {
  106943. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  106944. if (!jointNode) {
  106945. continue;
  106946. }
  106947. var node = jointNode.node;
  106948. if (!node) {
  106949. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  106950. continue;
  106951. }
  106952. var id = jointNode.id;
  106953. // Optimize, if the bone already exists...
  106954. var existingBone = gltfRuntime.scene.getBoneByID(id);
  106955. if (existingBone) {
  106956. newSkeleton.bones.push(existingBone);
  106957. continue;
  106958. }
  106959. // Search for parent bone
  106960. var foundBone = false;
  106961. var parentBone = null;
  106962. for (var j = 0; j < i; j++) {
  106963. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  106964. if (!jointNode_1) {
  106965. continue;
  106966. }
  106967. var joint = jointNode_1.node;
  106968. if (!joint) {
  106969. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  106970. continue;
  106971. }
  106972. var children = joint.children;
  106973. if (!children) {
  106974. continue;
  106975. }
  106976. foundBone = false;
  106977. for (var k = 0; k < children.length; k++) {
  106978. if (children[k] === id) {
  106979. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  106980. foundBone = true;
  106981. break;
  106982. }
  106983. }
  106984. if (foundBone) {
  106985. break;
  106986. }
  106987. }
  106988. // Create bone
  106989. var mat = configureBoneTransformation(node);
  106990. if (!parentBone && nodesToRoot.length > 0) {
  106991. parentBone = getNodeToRoot(nodesToRoot, id);
  106992. if (parentBone) {
  106993. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  106994. nodesToRootToAdd.push(parentBone);
  106995. }
  106996. }
  106997. }
  106998. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  106999. bone.id = id;
  107000. }
  107001. // Polish
  107002. var bones = newSkeleton.bones;
  107003. newSkeleton.bones = [];
  107004. for (var i = 0; i < skins.jointNames.length; i++) {
  107005. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  107006. if (!jointNode) {
  107007. continue;
  107008. }
  107009. for (var j = 0; j < bones.length; j++) {
  107010. if (bones[j].id === jointNode.id) {
  107011. newSkeleton.bones.push(bones[j]);
  107012. break;
  107013. }
  107014. }
  107015. }
  107016. newSkeleton.prepare();
  107017. // Finish
  107018. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  107019. newSkeleton.bones.push(nodesToRootToAdd[i]);
  107020. }
  107021. return newSkeleton;
  107022. };
  107023. /**
  107024. * Imports a mesh and its geometries
  107025. */
  107026. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  107027. if (!newMesh) {
  107028. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  107029. newMesh.id = id;
  107030. }
  107031. if (!node.babylonNode) {
  107032. return newMesh;
  107033. }
  107034. var subMaterials = [];
  107035. var vertexData = null;
  107036. var verticesStarts = new Array();
  107037. var verticesCounts = new Array();
  107038. var indexStarts = new Array();
  107039. var indexCounts = new Array();
  107040. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  107041. var meshID = meshes[meshIndex];
  107042. var mesh = gltfRuntime.meshes[meshID];
  107043. if (!mesh) {
  107044. continue;
  107045. }
  107046. // Positions, normals and UVs
  107047. for (var i = 0; i < mesh.primitives.length; i++) {
  107048. // Temporary vertex data
  107049. var tempVertexData = new BABYLON.VertexData();
  107050. var primitive = mesh.primitives[i];
  107051. if (primitive.mode !== 4) {
  107052. // continue;
  107053. }
  107054. var attributes = primitive.attributes;
  107055. var accessor = null;
  107056. var buffer = null;
  107057. // Set positions, normal and uvs
  107058. for (var semantic in attributes) {
  107059. // Link accessor and buffer view
  107060. accessor = gltfRuntime.accessors[attributes[semantic]];
  107061. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  107062. if (semantic === "NORMAL") {
  107063. tempVertexData.normals = new Float32Array(buffer.length);
  107064. tempVertexData.normals.set(buffer);
  107065. }
  107066. else if (semantic === "POSITION") {
  107067. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  107068. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  107069. for (var j = 0; j < buffer.length; j += 4) {
  107070. tempVertexData.positions[j] = buffer[j];
  107071. tempVertexData.positions[j + 1] = buffer[j + 1];
  107072. tempVertexData.positions[j + 2] = buffer[j + 2];
  107073. }
  107074. }
  107075. else {
  107076. tempVertexData.positions = new Float32Array(buffer.length);
  107077. tempVertexData.positions.set(buffer);
  107078. }
  107079. verticesCounts.push(tempVertexData.positions.length);
  107080. }
  107081. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  107082. var channel = Number(semantic.split("_")[1]);
  107083. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  107084. var uvs = new Float32Array(buffer.length);
  107085. uvs.set(buffer);
  107086. normalizeUVs(uvs);
  107087. tempVertexData.set(uvs, uvKind);
  107088. }
  107089. else if (semantic === "JOINT") {
  107090. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  107091. tempVertexData.matricesIndices.set(buffer);
  107092. }
  107093. else if (semantic === "WEIGHT") {
  107094. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  107095. tempVertexData.matricesWeights.set(buffer);
  107096. }
  107097. else if (semantic === "COLOR") {
  107098. tempVertexData.colors = new Float32Array(buffer.length);
  107099. tempVertexData.colors.set(buffer);
  107100. }
  107101. }
  107102. // Indices
  107103. accessor = gltfRuntime.accessors[primitive.indices];
  107104. if (accessor) {
  107105. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  107106. tempVertexData.indices = new Int32Array(buffer.length);
  107107. tempVertexData.indices.set(buffer);
  107108. indexCounts.push(tempVertexData.indices.length);
  107109. }
  107110. else {
  107111. // Set indices on the fly
  107112. var indices = [];
  107113. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  107114. indices.push(j);
  107115. }
  107116. tempVertexData.indices = new Int32Array(indices);
  107117. indexCounts.push(tempVertexData.indices.length);
  107118. }
  107119. if (!vertexData) {
  107120. vertexData = tempVertexData;
  107121. }
  107122. else {
  107123. vertexData.merge(tempVertexData);
  107124. }
  107125. // Sub material
  107126. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  107127. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  107128. // Update vertices start and index start
  107129. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  107130. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  107131. }
  107132. }
  107133. var material;
  107134. if (subMaterials.length > 1) {
  107135. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  107136. material.subMaterials = subMaterials;
  107137. }
  107138. else {
  107139. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  107140. }
  107141. if (subMaterials.length === 1) {
  107142. material = subMaterials[0];
  107143. }
  107144. if (!newMesh.material) {
  107145. newMesh.material = material;
  107146. }
  107147. // Apply geometry
  107148. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  107149. newMesh.computeWorldMatrix(true);
  107150. // Apply submeshes
  107151. newMesh.subMeshes = [];
  107152. var index = 0;
  107153. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  107154. var meshID = meshes[meshIndex];
  107155. var mesh = gltfRuntime.meshes[meshID];
  107156. if (!mesh) {
  107157. continue;
  107158. }
  107159. for (var i = 0; i < mesh.primitives.length; i++) {
  107160. if (mesh.primitives[i].mode !== 4) {
  107161. //continue;
  107162. }
  107163. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  107164. index++;
  107165. }
  107166. }
  107167. // Finish
  107168. return newMesh;
  107169. };
  107170. /**
  107171. * Configure node transformation from position, rotation and scaling
  107172. */
  107173. var configureNode = function (newNode, position, rotation, scaling) {
  107174. if (newNode.position) {
  107175. newNode.position = position;
  107176. }
  107177. if (newNode.rotationQuaternion || newNode.rotation) {
  107178. newNode.rotationQuaternion = rotation;
  107179. }
  107180. if (newNode.scaling) {
  107181. newNode.scaling = scaling;
  107182. }
  107183. };
  107184. /**
  107185. * Configures node from transformation matrix
  107186. */
  107187. var configureNodeFromMatrix = function (newNode, node, parent) {
  107188. if (node.matrix) {
  107189. var position = new BABYLON.Vector3(0, 0, 0);
  107190. var rotation = new BABYLON.Quaternion();
  107191. var scaling = new BABYLON.Vector3(0, 0, 0);
  107192. var mat = BABYLON.Matrix.FromArray(node.matrix);
  107193. mat.decompose(scaling, rotation, position);
  107194. configureNode(newNode, position, rotation, scaling);
  107195. }
  107196. else if (node.translation && node.rotation && node.scale) {
  107197. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  107198. }
  107199. newNode.computeWorldMatrix(true);
  107200. };
  107201. /**
  107202. * Imports a node
  107203. */
  107204. var importNode = function (gltfRuntime, node, id, parent) {
  107205. var lastNode = null;
  107206. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  107207. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  107208. return null;
  107209. }
  107210. }
  107211. // Meshes
  107212. if (node.skin) {
  107213. if (node.meshes) {
  107214. var skin = gltfRuntime.skins[node.skin];
  107215. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  107216. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  107217. if (newMesh.skeleton === null) {
  107218. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  107219. if (!skin.babylonSkeleton) {
  107220. skin.babylonSkeleton = newMesh.skeleton;
  107221. }
  107222. }
  107223. lastNode = newMesh;
  107224. }
  107225. }
  107226. else if (node.meshes) {
  107227. /**
  107228. * Improve meshes property
  107229. */
  107230. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  107231. lastNode = newMesh;
  107232. }
  107233. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  107234. var light = gltfRuntime.lights[node.light];
  107235. if (light) {
  107236. if (light.type === "ambient") {
  107237. var ambienLight = light[light.type];
  107238. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107239. hemiLight.name = node.name || "";
  107240. if (ambienLight.color) {
  107241. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  107242. }
  107243. lastNode = hemiLight;
  107244. }
  107245. else if (light.type === "directional") {
  107246. var directionalLight = light[light.type];
  107247. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107248. dirLight.name = node.name || "";
  107249. if (directionalLight.color) {
  107250. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  107251. }
  107252. lastNode = dirLight;
  107253. }
  107254. else if (light.type === "point") {
  107255. var pointLight = light[light.type];
  107256. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107257. ptLight.name = node.name || "";
  107258. if (pointLight.color) {
  107259. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  107260. }
  107261. lastNode = ptLight;
  107262. }
  107263. else if (light.type === "spot") {
  107264. var spotLight = light[light.type];
  107265. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  107266. spLight.name = node.name || "";
  107267. if (spotLight.color) {
  107268. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  107269. }
  107270. if (spotLight.fallOfAngle) {
  107271. spLight.angle = spotLight.fallOfAngle;
  107272. }
  107273. if (spotLight.fallOffExponent) {
  107274. spLight.exponent = spotLight.fallOffExponent;
  107275. }
  107276. lastNode = spLight;
  107277. }
  107278. }
  107279. }
  107280. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  107281. var camera = gltfRuntime.cameras[node.camera];
  107282. if (camera) {
  107283. if (camera.type === "orthographic") {
  107284. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107285. orthoCamera.name = node.name || "";
  107286. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  107287. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  107288. lastNode = orthoCamera;
  107289. }
  107290. else if (camera.type === "perspective") {
  107291. var perspectiveCamera = camera[camera.type];
  107292. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107293. persCamera.name = node.name || "";
  107294. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  107295. if (!perspectiveCamera.aspectRatio) {
  107296. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  107297. }
  107298. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  107299. persCamera.maxZ = perspectiveCamera.zfar;
  107300. persCamera.minZ = perspectiveCamera.znear;
  107301. }
  107302. lastNode = persCamera;
  107303. }
  107304. }
  107305. }
  107306. // Empty node
  107307. if (!node.jointName) {
  107308. if (node.babylonNode) {
  107309. return node.babylonNode;
  107310. }
  107311. else if (lastNode === null) {
  107312. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  107313. node.babylonNode = dummy;
  107314. lastNode = dummy;
  107315. }
  107316. }
  107317. if (lastNode !== null) {
  107318. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  107319. configureNodeFromMatrix(lastNode, node, parent);
  107320. }
  107321. else {
  107322. var translation = node.translation || [0, 0, 0];
  107323. var rotation = node.rotation || [0, 0, 0, 1];
  107324. var scale = node.scale || [1, 1, 1];
  107325. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  107326. }
  107327. lastNode.updateCache(true);
  107328. node.babylonNode = lastNode;
  107329. }
  107330. return lastNode;
  107331. };
  107332. /**
  107333. * Traverses nodes and creates them
  107334. */
  107335. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  107336. if (meshIncluded === void 0) { meshIncluded = false; }
  107337. var node = gltfRuntime.nodes[id];
  107338. var newNode = null;
  107339. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  107340. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  107341. meshIncluded = true;
  107342. }
  107343. else {
  107344. meshIncluded = false;
  107345. }
  107346. }
  107347. else {
  107348. meshIncluded = true;
  107349. }
  107350. if (!node.jointName && meshIncluded) {
  107351. newNode = importNode(gltfRuntime, node, id, parent);
  107352. if (newNode !== null) {
  107353. newNode.id = id;
  107354. newNode.parent = parent;
  107355. }
  107356. }
  107357. if (node.children) {
  107358. for (var i = 0; i < node.children.length; i++) {
  107359. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  107360. }
  107361. }
  107362. };
  107363. /**
  107364. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  107365. */
  107366. var postLoad = function (gltfRuntime) {
  107367. // Nodes
  107368. var currentScene = gltfRuntime.currentScene;
  107369. if (currentScene) {
  107370. for (var i = 0; i < currentScene.nodes.length; i++) {
  107371. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107372. }
  107373. }
  107374. else {
  107375. for (var thing in gltfRuntime.scenes) {
  107376. currentScene = gltfRuntime.scenes[thing];
  107377. for (var i = 0; i < currentScene.nodes.length; i++) {
  107378. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107379. }
  107380. }
  107381. }
  107382. // Set animations
  107383. loadAnimations(gltfRuntime);
  107384. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  107385. var skeleton = gltfRuntime.scene.skeletons[i];
  107386. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  107387. }
  107388. };
  107389. /**
  107390. * onBind shaderrs callback to set uniforms and matrices
  107391. */
  107392. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  107393. var materialValues = material.values || technique.parameters;
  107394. for (var unif in unTreatedUniforms) {
  107395. var uniform = unTreatedUniforms[unif];
  107396. var type = uniform.type;
  107397. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  107398. if (uniform.semantic && !uniform.source && !uniform.node) {
  107399. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  107400. }
  107401. else if (uniform.semantic && (uniform.source || uniform.node)) {
  107402. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  107403. if (source === null) {
  107404. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  107405. }
  107406. if (source === null) {
  107407. continue;
  107408. }
  107409. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  107410. }
  107411. }
  107412. else {
  107413. var value = materialValues[technique.uniforms[unif]];
  107414. if (!value) {
  107415. continue;
  107416. }
  107417. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  107418. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  107419. if (texture === null || texture === undefined) {
  107420. continue;
  107421. }
  107422. shaderMaterial.getEffect().setTexture(unif, texture);
  107423. }
  107424. else {
  107425. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  107426. }
  107427. }
  107428. }
  107429. onSuccess(shaderMaterial);
  107430. };
  107431. /**
  107432. * Prepare uniforms to send the only one time
  107433. * Loads the appropriate textures
  107434. */
  107435. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  107436. var materialValues = material.values || technique.parameters;
  107437. var techniqueUniforms = technique.uniforms;
  107438. /**
  107439. * Prepare values here (not matrices)
  107440. */
  107441. for (var unif in unTreatedUniforms) {
  107442. var uniform = unTreatedUniforms[unif];
  107443. var type = uniform.type;
  107444. var value = materialValues[techniqueUniforms[unif]];
  107445. if (value === undefined) {
  107446. // In case the value is the same for all materials
  107447. value = uniform.value;
  107448. }
  107449. if (!value) {
  107450. continue;
  107451. }
  107452. var onLoadTexture = function (uniformName) {
  107453. return function (texture) {
  107454. if (uniform.value && uniformName) {
  107455. // Static uniform
  107456. shaderMaterial.setTexture(uniformName, texture);
  107457. delete unTreatedUniforms[uniformName];
  107458. }
  107459. };
  107460. };
  107461. // Texture (sampler2D)
  107462. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  107463. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  107464. }
  107465. else {
  107466. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  107467. // Static uniform
  107468. delete unTreatedUniforms[unif];
  107469. }
  107470. }
  107471. }
  107472. };
  107473. /**
  107474. * Shader compilation failed
  107475. */
  107476. var onShaderCompileError = function (program, shaderMaterial, onError) {
  107477. return function (effect, error) {
  107478. shaderMaterial.dispose(true);
  107479. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  107480. };
  107481. };
  107482. /**
  107483. * Shader compilation success
  107484. */
  107485. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  107486. return function (_) {
  107487. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  107488. shaderMaterial.onBind = function (mesh) {
  107489. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  107490. };
  107491. };
  107492. };
  107493. /**
  107494. * Returns the appropriate uniform if already handled by babylon
  107495. */
  107496. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  107497. for (var unif in technique.uniforms) {
  107498. var uniform = technique.uniforms[unif];
  107499. var uniformParameter = technique.parameters[uniform];
  107500. if (tokenizer.currentIdentifier === unif) {
  107501. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  107502. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  107503. if (transformIndex !== -1) {
  107504. delete unTreatedUniforms[unif];
  107505. return babylonTransforms[transformIndex];
  107506. }
  107507. }
  107508. }
  107509. }
  107510. return tokenizer.currentIdentifier;
  107511. };
  107512. /**
  107513. * All shaders loaded. Create materials one by one
  107514. */
  107515. var importMaterials = function (gltfRuntime) {
  107516. // Create materials
  107517. for (var mat in gltfRuntime.materials) {
  107518. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  107519. }
  107520. };
  107521. /**
  107522. * Implementation of the base glTF spec
  107523. */
  107524. var GLTFLoaderBase = /** @class */ (function () {
  107525. function GLTFLoaderBase() {
  107526. }
  107527. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  107528. var gltfRuntime = {
  107529. extensions: {},
  107530. accessors: {},
  107531. buffers: {},
  107532. bufferViews: {},
  107533. meshes: {},
  107534. lights: {},
  107535. cameras: {},
  107536. nodes: {},
  107537. images: {},
  107538. textures: {},
  107539. shaders: {},
  107540. programs: {},
  107541. samplers: {},
  107542. techniques: {},
  107543. materials: {},
  107544. animations: {},
  107545. skins: {},
  107546. extensionsUsed: [],
  107547. scenes: {},
  107548. buffersCount: 0,
  107549. shaderscount: 0,
  107550. scene: scene,
  107551. rootUrl: rootUrl,
  107552. loadedBufferCount: 0,
  107553. loadedBufferViews: {},
  107554. loadedShaderCount: 0,
  107555. importOnlyMeshes: false,
  107556. dummyNodes: []
  107557. };
  107558. // Parse
  107559. if (parsedData.extensions) {
  107560. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  107561. }
  107562. if (parsedData.extensionsUsed) {
  107563. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  107564. }
  107565. if (parsedData.buffers) {
  107566. parseBuffers(parsedData.buffers, gltfRuntime);
  107567. }
  107568. if (parsedData.bufferViews) {
  107569. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  107570. }
  107571. if (parsedData.accessors) {
  107572. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  107573. }
  107574. if (parsedData.meshes) {
  107575. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  107576. }
  107577. if (parsedData.lights) {
  107578. parseObject(parsedData.lights, "lights", gltfRuntime);
  107579. }
  107580. if (parsedData.cameras) {
  107581. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  107582. }
  107583. if (parsedData.nodes) {
  107584. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  107585. }
  107586. if (parsedData.images) {
  107587. parseObject(parsedData.images, "images", gltfRuntime);
  107588. }
  107589. if (parsedData.textures) {
  107590. parseObject(parsedData.textures, "textures", gltfRuntime);
  107591. }
  107592. if (parsedData.shaders) {
  107593. parseShaders(parsedData.shaders, gltfRuntime);
  107594. }
  107595. if (parsedData.programs) {
  107596. parseObject(parsedData.programs, "programs", gltfRuntime);
  107597. }
  107598. if (parsedData.samplers) {
  107599. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  107600. }
  107601. if (parsedData.techniques) {
  107602. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  107603. }
  107604. if (parsedData.materials) {
  107605. parseObject(parsedData.materials, "materials", gltfRuntime);
  107606. }
  107607. if (parsedData.animations) {
  107608. parseObject(parsedData.animations, "animations", gltfRuntime);
  107609. }
  107610. if (parsedData.skins) {
  107611. parseObject(parsedData.skins, "skins", gltfRuntime);
  107612. }
  107613. if (parsedData.scenes) {
  107614. gltfRuntime.scenes = parsedData.scenes;
  107615. }
  107616. if (parsedData.scene && parsedData.scenes) {
  107617. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  107618. }
  107619. return gltfRuntime;
  107620. };
  107621. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  107622. var buffer = gltfRuntime.buffers[id];
  107623. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  107624. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  107625. }
  107626. else {
  107627. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  107628. if (request) {
  107629. onError(request.status + " " + request.statusText);
  107630. }
  107631. });
  107632. }
  107633. };
  107634. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107635. var texture = gltfRuntime.textures[id];
  107636. if (!texture || !texture.source) {
  107637. onError("");
  107638. return;
  107639. }
  107640. if (texture.babylonTexture) {
  107641. onSuccess(null);
  107642. return;
  107643. }
  107644. var source = gltfRuntime.images[texture.source];
  107645. if (BABYLON.Tools.IsBase64(source.uri)) {
  107646. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  107647. }
  107648. else {
  107649. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  107650. if (request) {
  107651. onError(request.status + " " + request.statusText);
  107652. }
  107653. });
  107654. }
  107655. };
  107656. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  107657. var texture = gltfRuntime.textures[id];
  107658. if (texture.babylonTexture) {
  107659. onSuccess(texture.babylonTexture);
  107660. return;
  107661. }
  107662. var sampler = gltfRuntime.samplers[texture.sampler];
  107663. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  107664. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  107665. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  107666. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  107667. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  107668. var blob = new Blob([buffer]);
  107669. var blobURL = URL.createObjectURL(blob);
  107670. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  107671. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  107672. if (sampler.wrapS !== undefined) {
  107673. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  107674. }
  107675. if (sampler.wrapT !== undefined) {
  107676. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  107677. }
  107678. newTexture.name = id;
  107679. texture.babylonTexture = newTexture;
  107680. onSuccess(newTexture);
  107681. };
  107682. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  107683. var shader = gltfRuntime.shaders[id];
  107684. if (BABYLON.Tools.IsBase64(shader.uri)) {
  107685. var shaderString = atob(shader.uri.split(",")[1]);
  107686. onSuccess(shaderString);
  107687. }
  107688. else {
  107689. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  107690. if (request) {
  107691. onError(request.status + " " + request.statusText);
  107692. }
  107693. });
  107694. }
  107695. };
  107696. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  107697. var material = gltfRuntime.materials[id];
  107698. if (!material.technique) {
  107699. if (onError) {
  107700. onError("No technique found.");
  107701. }
  107702. return;
  107703. }
  107704. var technique = gltfRuntime.techniques[material.technique];
  107705. if (!technique) {
  107706. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  107707. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  107708. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  107709. onSuccess(defaultMaterial);
  107710. return;
  107711. }
  107712. var program = gltfRuntime.programs[technique.program];
  107713. var states = technique.states;
  107714. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  107715. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  107716. var newVertexShader = "";
  107717. var newPixelShader = "";
  107718. var vertexTokenizer = new Tokenizer(vertexShader);
  107719. var pixelTokenizer = new Tokenizer(pixelShader);
  107720. var unTreatedUniforms = {};
  107721. var uniforms = [];
  107722. var attributes = [];
  107723. var samplers = [];
  107724. // Fill uniform, sampler2D and attributes
  107725. for (var unif in technique.uniforms) {
  107726. var uniform = technique.uniforms[unif];
  107727. var uniformParameter = technique.parameters[uniform];
  107728. unTreatedUniforms[unif] = uniformParameter;
  107729. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  107730. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  107731. if (transformIndex !== -1) {
  107732. uniforms.push(babylonTransforms[transformIndex]);
  107733. delete unTreatedUniforms[unif];
  107734. }
  107735. else {
  107736. uniforms.push(unif);
  107737. }
  107738. }
  107739. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  107740. samplers.push(unif);
  107741. }
  107742. else {
  107743. uniforms.push(unif);
  107744. }
  107745. }
  107746. for (var attr in technique.attributes) {
  107747. var attribute = technique.attributes[attr];
  107748. var attributeParameter = technique.parameters[attribute];
  107749. if (attributeParameter.semantic) {
  107750. attributes.push(getAttribute(attributeParameter));
  107751. }
  107752. }
  107753. // Configure vertex shader
  107754. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  107755. var tokenType = vertexTokenizer.currentToken;
  107756. if (tokenType !== ETokenType.IDENTIFIER) {
  107757. newVertexShader += vertexTokenizer.currentString;
  107758. continue;
  107759. }
  107760. var foundAttribute = false;
  107761. for (var attr in technique.attributes) {
  107762. var attribute = technique.attributes[attr];
  107763. var attributeParameter = technique.parameters[attribute];
  107764. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  107765. newVertexShader += getAttribute(attributeParameter);
  107766. foundAttribute = true;
  107767. break;
  107768. }
  107769. }
  107770. if (foundAttribute) {
  107771. continue;
  107772. }
  107773. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  107774. }
  107775. // Configure pixel shader
  107776. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  107777. var tokenType = pixelTokenizer.currentToken;
  107778. if (tokenType !== ETokenType.IDENTIFIER) {
  107779. newPixelShader += pixelTokenizer.currentString;
  107780. continue;
  107781. }
  107782. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  107783. }
  107784. // Create shader material
  107785. var shaderPath = {
  107786. vertex: program.vertexShader + id,
  107787. fragment: program.fragmentShader + id
  107788. };
  107789. var options = {
  107790. attributes: attributes,
  107791. uniforms: uniforms,
  107792. samplers: samplers,
  107793. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  107794. };
  107795. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  107796. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  107797. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  107798. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  107799. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  107800. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  107801. if (states && states.functions) {
  107802. var functions = states.functions;
  107803. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  107804. shaderMaterial.backFaceCulling = false;
  107805. }
  107806. var blendFunc = functions.blendFuncSeparate;
  107807. if (blendFunc) {
  107808. 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) {
  107809. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  107810. }
  107811. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  107812. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  107813. }
  107814. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  107815. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  107816. }
  107817. 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) {
  107818. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  107819. }
  107820. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  107821. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  107822. }
  107823. 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) {
  107824. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  107825. }
  107826. }
  107827. }
  107828. };
  107829. return GLTFLoaderBase;
  107830. }());
  107831. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  107832. /**
  107833. * glTF V1 Loader
  107834. */
  107835. var GLTFLoader = /** @class */ (function () {
  107836. function GLTFLoader() {
  107837. // #region Stubs for IGLTFLoader interface
  107838. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  107839. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  107840. this.compileMaterials = false;
  107841. this.useClipPlane = false;
  107842. this.compileShadowGenerators = false;
  107843. this.onDisposeObservable = new BABYLON.Observable();
  107844. this.onMeshLoadedObservable = new BABYLON.Observable();
  107845. this.onTextureLoadedObservable = new BABYLON.Observable();
  107846. this.onMaterialLoadedObservable = new BABYLON.Observable();
  107847. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  107848. this.onCompleteObservable = new BABYLON.Observable();
  107849. this.onExtensionLoadedObservable = new BABYLON.Observable();
  107850. this.state = null;
  107851. }
  107852. GLTFLoader.RegisterExtension = function (extension) {
  107853. if (GLTFLoader.Extensions[extension.name]) {
  107854. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  107855. return;
  107856. }
  107857. GLTFLoader.Extensions[extension.name] = extension;
  107858. };
  107859. GLTFLoader.prototype.dispose = function () { };
  107860. // #endregion
  107861. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  107862. var _this = this;
  107863. scene.useRightHandedSystem = true;
  107864. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  107865. gltfRuntime.importOnlyMeshes = true;
  107866. if (meshesNames === "") {
  107867. gltfRuntime.importMeshesNames = [];
  107868. }
  107869. else if (typeof meshesNames === "string") {
  107870. gltfRuntime.importMeshesNames = [meshesNames];
  107871. }
  107872. else if (meshesNames && !(meshesNames instanceof Array)) {
  107873. gltfRuntime.importMeshesNames = [meshesNames];
  107874. }
  107875. else {
  107876. gltfRuntime.importMeshesNames = [];
  107877. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  107878. }
  107879. // Create nodes
  107880. _this._createNodes(gltfRuntime);
  107881. var meshes = new Array();
  107882. var skeletons = new Array();
  107883. // Fill arrays of meshes and skeletons
  107884. for (var nde in gltfRuntime.nodes) {
  107885. var node = gltfRuntime.nodes[nde];
  107886. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  107887. meshes.push(node.babylonNode);
  107888. }
  107889. }
  107890. for (var skl in gltfRuntime.skins) {
  107891. var skin = gltfRuntime.skins[skl];
  107892. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  107893. skeletons.push(skin.babylonSkeleton);
  107894. }
  107895. }
  107896. // Load buffers, shaders, materials, etc.
  107897. _this._loadBuffersAsync(gltfRuntime, function () {
  107898. _this._loadShadersAsync(gltfRuntime, function () {
  107899. importMaterials(gltfRuntime);
  107900. postLoad(gltfRuntime);
  107901. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  107902. onSuccess(meshes, [], skeletons);
  107903. }
  107904. });
  107905. }, onProgress);
  107906. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  107907. onSuccess(meshes, [], skeletons);
  107908. }
  107909. }, onError);
  107910. return true;
  107911. };
  107912. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  107913. var _this = this;
  107914. return new Promise(function (resolve, reject) {
  107915. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  107916. resolve({
  107917. meshes: meshes,
  107918. particleSystems: particleSystems,
  107919. skeletons: skeletons
  107920. });
  107921. }, onProgress, function (message) {
  107922. reject(new Error(message));
  107923. });
  107924. });
  107925. };
  107926. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  107927. var _this = this;
  107928. scene.useRightHandedSystem = true;
  107929. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  107930. // Load runtime extensios
  107931. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  107932. // Create nodes
  107933. _this._createNodes(gltfRuntime);
  107934. // Load buffers, shaders, materials, etc.
  107935. _this._loadBuffersAsync(gltfRuntime, function () {
  107936. _this._loadShadersAsync(gltfRuntime, function () {
  107937. importMaterials(gltfRuntime);
  107938. postLoad(gltfRuntime);
  107939. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  107940. onSuccess();
  107941. }
  107942. });
  107943. });
  107944. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  107945. onSuccess();
  107946. }
  107947. }, onError);
  107948. }, onError);
  107949. };
  107950. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  107951. var _this = this;
  107952. return new Promise(function (resolve, reject) {
  107953. _this._loadAsync(scene, data, rootUrl, function () {
  107954. resolve();
  107955. }, onProgress, function (message) {
  107956. reject(new Error(message));
  107957. });
  107958. });
  107959. };
  107960. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  107961. var hasShaders = false;
  107962. var processShader = function (sha, shader) {
  107963. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  107964. gltfRuntime.loadedShaderCount++;
  107965. if (shaderString) {
  107966. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  107967. }
  107968. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  107969. onload();
  107970. }
  107971. }, function () {
  107972. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  107973. });
  107974. };
  107975. for (var sha in gltfRuntime.shaders) {
  107976. hasShaders = true;
  107977. var shader = gltfRuntime.shaders[sha];
  107978. if (shader) {
  107979. processShader.bind(this, sha, shader)();
  107980. }
  107981. else {
  107982. BABYLON.Tools.Error("No shader named: " + sha);
  107983. }
  107984. }
  107985. if (!hasShaders) {
  107986. onload();
  107987. }
  107988. };
  107989. ;
  107990. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  107991. var hasBuffers = false;
  107992. var processBuffer = function (buf, buffer) {
  107993. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  107994. gltfRuntime.loadedBufferCount++;
  107995. if (bufferView) {
  107996. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  107997. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  107998. }
  107999. gltfRuntime.loadedBufferViews[buf] = bufferView;
  108000. }
  108001. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  108002. onLoad();
  108003. }
  108004. }, function () {
  108005. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  108006. });
  108007. };
  108008. for (var buf in gltfRuntime.buffers) {
  108009. hasBuffers = true;
  108010. var buffer = gltfRuntime.buffers[buf];
  108011. if (buffer) {
  108012. processBuffer.bind(this, buf, buffer)();
  108013. }
  108014. else {
  108015. BABYLON.Tools.Error("No buffer named: " + buf);
  108016. }
  108017. }
  108018. if (!hasBuffers) {
  108019. onLoad();
  108020. }
  108021. };
  108022. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  108023. var currentScene = gltfRuntime.currentScene;
  108024. if (currentScene) {
  108025. // Only one scene even if multiple scenes are defined
  108026. for (var i = 0; i < currentScene.nodes.length; i++) {
  108027. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  108028. }
  108029. }
  108030. else {
  108031. // Load all scenes
  108032. for (var thing in gltfRuntime.scenes) {
  108033. currentScene = gltfRuntime.scenes[thing];
  108034. for (var i = 0; i < currentScene.nodes.length; i++) {
  108035. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  108036. }
  108037. }
  108038. }
  108039. };
  108040. GLTFLoader.Extensions = {};
  108041. return GLTFLoader;
  108042. }());
  108043. GLTF1.GLTFLoader = GLTFLoader;
  108044. ;
  108045. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  108046. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108047. })(BABYLON || (BABYLON = {}));
  108048. //# sourceMappingURL=babylon.glTFLoader.js.map
  108049. var BABYLON;
  108050. (function (BABYLON) {
  108051. var GLTF1;
  108052. (function (GLTF1) {
  108053. /**
  108054. * Utils functions for GLTF
  108055. */
  108056. var GLTFUtils = /** @class */ (function () {
  108057. function GLTFUtils() {
  108058. }
  108059. /**
  108060. * Sets the given "parameter" matrix
  108061. * @param scene: the {BABYLON.Scene} object
  108062. * @param source: the source node where to pick the matrix
  108063. * @param parameter: the GLTF technique parameter
  108064. * @param uniformName: the name of the shader's uniform
  108065. * @param shaderMaterial: the shader material
  108066. */
  108067. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  108068. var mat = null;
  108069. if (parameter.semantic === "MODEL") {
  108070. mat = source.getWorldMatrix();
  108071. }
  108072. else if (parameter.semantic === "PROJECTION") {
  108073. mat = scene.getProjectionMatrix();
  108074. }
  108075. else if (parameter.semantic === "VIEW") {
  108076. mat = scene.getViewMatrix();
  108077. }
  108078. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  108079. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  108080. }
  108081. else if (parameter.semantic === "MODELVIEW") {
  108082. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  108083. }
  108084. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  108085. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  108086. }
  108087. else if (parameter.semantic === "MODELINVERSE") {
  108088. mat = source.getWorldMatrix().invert();
  108089. }
  108090. else if (parameter.semantic === "VIEWINVERSE") {
  108091. mat = scene.getViewMatrix().invert();
  108092. }
  108093. else if (parameter.semantic === "PROJECTIONINVERSE") {
  108094. mat = scene.getProjectionMatrix().invert();
  108095. }
  108096. else if (parameter.semantic === "MODELVIEWINVERSE") {
  108097. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  108098. }
  108099. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  108100. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  108101. }
  108102. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  108103. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  108104. }
  108105. else {
  108106. debugger;
  108107. }
  108108. if (mat) {
  108109. switch (parameter.type) {
  108110. case GLTF1.EParameterType.FLOAT_MAT2:
  108111. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  108112. break;
  108113. case GLTF1.EParameterType.FLOAT_MAT3:
  108114. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  108115. break;
  108116. case GLTF1.EParameterType.FLOAT_MAT4:
  108117. shaderMaterial.setMatrix(uniformName, mat);
  108118. break;
  108119. default: break;
  108120. }
  108121. }
  108122. };
  108123. /**
  108124. * Sets the given "parameter" matrix
  108125. * @param shaderMaterial: the shader material
  108126. * @param uniform: the name of the shader's uniform
  108127. * @param value: the value of the uniform
  108128. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  108129. */
  108130. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  108131. switch (type) {
  108132. case GLTF1.EParameterType.FLOAT:
  108133. shaderMaterial.setFloat(uniform, value);
  108134. return true;
  108135. case GLTF1.EParameterType.FLOAT_VEC2:
  108136. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  108137. return true;
  108138. case GLTF1.EParameterType.FLOAT_VEC3:
  108139. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  108140. return true;
  108141. case GLTF1.EParameterType.FLOAT_VEC4:
  108142. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  108143. return true;
  108144. default: return false;
  108145. }
  108146. };
  108147. /**
  108148. * Returns the wrap mode of the texture
  108149. * @param mode: the mode value
  108150. */
  108151. GLTFUtils.GetWrapMode = function (mode) {
  108152. switch (mode) {
  108153. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  108154. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  108155. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  108156. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  108157. }
  108158. };
  108159. /**
  108160. * Returns the byte stride giving an accessor
  108161. * @param accessor: the GLTF accessor objet
  108162. */
  108163. GLTFUtils.GetByteStrideFromType = function (accessor) {
  108164. // Needs this function since "byteStride" isn't requiered in glTF format
  108165. var type = accessor.type;
  108166. switch (type) {
  108167. case "VEC2": return 2;
  108168. case "VEC3": return 3;
  108169. case "VEC4": return 4;
  108170. case "MAT2": return 4;
  108171. case "MAT3": return 9;
  108172. case "MAT4": return 16;
  108173. default: return 1;
  108174. }
  108175. };
  108176. /**
  108177. * Returns the texture filter mode giving a mode value
  108178. * @param mode: the filter mode value
  108179. */
  108180. GLTFUtils.GetTextureFilterMode = function (mode) {
  108181. switch (mode) {
  108182. case GLTF1.ETextureFilterType.LINEAR:
  108183. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  108184. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  108185. case GLTF1.ETextureFilterType.NEAREST:
  108186. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  108187. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  108188. }
  108189. };
  108190. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  108191. var byteOffset = bufferView.byteOffset + byteOffset;
  108192. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  108193. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  108194. throw new Error("Buffer access is out of range");
  108195. }
  108196. var buffer = loadedBufferView.buffer;
  108197. byteOffset += loadedBufferView.byteOffset;
  108198. switch (componentType) {
  108199. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  108200. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  108201. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  108202. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  108203. default: return new Float32Array(buffer, byteOffset, byteLength);
  108204. }
  108205. };
  108206. /**
  108207. * Returns a buffer from its accessor
  108208. * @param gltfRuntime: the GLTF runtime
  108209. * @param accessor: the GLTF accessor
  108210. */
  108211. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  108212. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  108213. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  108214. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  108215. };
  108216. /**
  108217. * Decodes a buffer view into a string
  108218. * @param view: the buffer view
  108219. */
  108220. GLTFUtils.DecodeBufferToText = function (view) {
  108221. var result = "";
  108222. var length = view.byteLength;
  108223. for (var i = 0; i < length; ++i) {
  108224. result += String.fromCharCode(view[i]);
  108225. }
  108226. return result;
  108227. };
  108228. /**
  108229. * Returns the default material of gltf. Related to
  108230. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  108231. * @param scene: the Babylon.js scene
  108232. */
  108233. GLTFUtils.GetDefaultMaterial = function (scene) {
  108234. if (!GLTFUtils._DefaultMaterial) {
  108235. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  108236. "precision highp float;",
  108237. "",
  108238. "uniform mat4 worldView;",
  108239. "uniform mat4 projection;",
  108240. "",
  108241. "attribute vec3 position;",
  108242. "",
  108243. "void main(void)",
  108244. "{",
  108245. " gl_Position = projection * worldView * vec4(position, 1.0);",
  108246. "}"
  108247. ].join("\n");
  108248. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  108249. "precision highp float;",
  108250. "",
  108251. "uniform vec4 u_emission;",
  108252. "",
  108253. "void main(void)",
  108254. "{",
  108255. " gl_FragColor = u_emission;",
  108256. "}"
  108257. ].join("\n");
  108258. var shaderPath = {
  108259. vertex: "GLTFDefaultMaterial",
  108260. fragment: "GLTFDefaultMaterial"
  108261. };
  108262. var options = {
  108263. attributes: ["position"],
  108264. uniforms: ["worldView", "projection", "u_emission"],
  108265. samplers: new Array(),
  108266. needAlphaBlending: false
  108267. };
  108268. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  108269. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  108270. }
  108271. return GLTFUtils._DefaultMaterial;
  108272. };
  108273. // The GLTF default material
  108274. GLTFUtils._DefaultMaterial = null;
  108275. return GLTFUtils;
  108276. }());
  108277. GLTF1.GLTFUtils = GLTFUtils;
  108278. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108279. })(BABYLON || (BABYLON = {}));
  108280. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  108281. var BABYLON;
  108282. (function (BABYLON) {
  108283. var GLTF1;
  108284. (function (GLTF1) {
  108285. var GLTFLoaderExtension = /** @class */ (function () {
  108286. function GLTFLoaderExtension(name) {
  108287. this._name = name;
  108288. }
  108289. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  108290. get: function () {
  108291. return this._name;
  108292. },
  108293. enumerable: true,
  108294. configurable: true
  108295. });
  108296. /**
  108297. * Defines an override for loading the runtime
  108298. * Return true to stop further extensions from loading the runtime
  108299. */
  108300. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  108301. return false;
  108302. };
  108303. /**
  108304. * Defines an onverride for creating gltf runtime
  108305. * Return true to stop further extensions from creating the runtime
  108306. */
  108307. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  108308. return false;
  108309. };
  108310. /**
  108311. * Defines an override for loading buffers
  108312. * Return true to stop further extensions from loading this buffer
  108313. */
  108314. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  108315. return false;
  108316. };
  108317. /**
  108318. * Defines an override for loading texture buffers
  108319. * Return true to stop further extensions from loading this texture data
  108320. */
  108321. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108322. return false;
  108323. };
  108324. /**
  108325. * Defines an override for creating textures
  108326. * Return true to stop further extensions from loading this texture
  108327. */
  108328. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  108329. return false;
  108330. };
  108331. /**
  108332. * Defines an override for loading shader strings
  108333. * Return true to stop further extensions from loading this shader data
  108334. */
  108335. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  108336. return false;
  108337. };
  108338. /**
  108339. * Defines an override for loading materials
  108340. * Return true to stop further extensions from loading this material
  108341. */
  108342. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108343. return false;
  108344. };
  108345. // ---------
  108346. // Utilities
  108347. // ---------
  108348. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  108349. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108350. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  108351. }, function () {
  108352. setTimeout(function () {
  108353. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  108354. });
  108355. });
  108356. };
  108357. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  108358. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108359. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  108360. }, function () {
  108361. setTimeout(function () {
  108362. onSuccess();
  108363. });
  108364. });
  108365. };
  108366. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  108367. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108368. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  108369. }, function () {
  108370. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  108371. });
  108372. };
  108373. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  108374. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  108375. };
  108376. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  108377. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108378. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  108379. }, function () {
  108380. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  108381. });
  108382. };
  108383. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108384. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108385. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  108386. }, function () {
  108387. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  108388. });
  108389. };
  108390. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108391. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108392. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  108393. }, function () {
  108394. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  108395. });
  108396. };
  108397. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  108398. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108399. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  108400. }, function () {
  108401. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  108402. });
  108403. };
  108404. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  108405. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  108406. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  108407. if (func(loaderExtension)) {
  108408. return;
  108409. }
  108410. }
  108411. defaultFunc();
  108412. };
  108413. return GLTFLoaderExtension;
  108414. }());
  108415. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  108416. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108417. })(BABYLON || (BABYLON = {}));
  108418. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  108419. var BABYLON;
  108420. (function (BABYLON) {
  108421. var GLTF1;
  108422. (function (GLTF1) {
  108423. var BinaryExtensionBufferName = "binary_glTF";
  108424. ;
  108425. ;
  108426. var GLTFBinaryExtension = /** @class */ (function (_super) {
  108427. __extends(GLTFBinaryExtension, _super);
  108428. function GLTFBinaryExtension() {
  108429. return _super.call(this, "KHR_binary_glTF") || this;
  108430. }
  108431. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  108432. var extensionsUsed = data.json.extensionsUsed;
  108433. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  108434. return false;
  108435. }
  108436. this._bin = data.bin;
  108437. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  108438. return true;
  108439. };
  108440. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108441. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  108442. return false;
  108443. }
  108444. if (id !== BinaryExtensionBufferName) {
  108445. return false;
  108446. }
  108447. onSuccess(this._bin);
  108448. return true;
  108449. };
  108450. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108451. var texture = gltfRuntime.textures[id];
  108452. var source = gltfRuntime.images[texture.source];
  108453. if (!source.extensions || !(this.name in source.extensions)) {
  108454. return false;
  108455. }
  108456. var sourceExt = source.extensions[this.name];
  108457. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  108458. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  108459. onSuccess(buffer);
  108460. return true;
  108461. };
  108462. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  108463. var shader = gltfRuntime.shaders[id];
  108464. if (!shader.extensions || !(this.name in shader.extensions)) {
  108465. return false;
  108466. }
  108467. var binaryExtensionShader = shader.extensions[this.name];
  108468. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  108469. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  108470. setTimeout(function () {
  108471. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  108472. onSuccess(shaderString);
  108473. });
  108474. return true;
  108475. };
  108476. return GLTFBinaryExtension;
  108477. }(GLTF1.GLTFLoaderExtension));
  108478. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  108479. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  108480. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108481. })(BABYLON || (BABYLON = {}));
  108482. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  108483. var BABYLON;
  108484. (function (BABYLON) {
  108485. var GLTF1;
  108486. (function (GLTF1) {
  108487. ;
  108488. ;
  108489. ;
  108490. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  108491. __extends(GLTFMaterialsCommonExtension, _super);
  108492. function GLTFMaterialsCommonExtension() {
  108493. return _super.call(this, "KHR_materials_common") || this;
  108494. }
  108495. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  108496. if (!gltfRuntime.extensions)
  108497. return false;
  108498. var extension = gltfRuntime.extensions[this.name];
  108499. if (!extension)
  108500. return false;
  108501. // Create lights
  108502. var lights = extension.lights;
  108503. if (lights) {
  108504. for (var thing in lights) {
  108505. var light = lights[thing];
  108506. switch (light.type) {
  108507. case "ambient":
  108508. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  108509. var ambient = light.ambient;
  108510. if (ambient) {
  108511. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  108512. }
  108513. break;
  108514. case "point":
  108515. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  108516. var point = light.point;
  108517. if (point) {
  108518. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  108519. }
  108520. break;
  108521. case "directional":
  108522. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  108523. var directional = light.directional;
  108524. if (directional) {
  108525. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  108526. }
  108527. break;
  108528. case "spot":
  108529. var spot = light.spot;
  108530. if (spot) {
  108531. 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);
  108532. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  108533. }
  108534. break;
  108535. default:
  108536. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  108537. break;
  108538. }
  108539. }
  108540. }
  108541. return false;
  108542. };
  108543. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108544. var material = gltfRuntime.materials[id];
  108545. if (!material || !material.extensions)
  108546. return false;
  108547. var extension = material.extensions[this.name];
  108548. if (!extension)
  108549. return false;
  108550. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  108551. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  108552. if (extension.technique === "CONSTANT") {
  108553. standardMaterial.disableLighting = true;
  108554. }
  108555. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  108556. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  108557. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  108558. // Ambient
  108559. if (typeof extension.values.ambient === "string") {
  108560. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  108561. }
  108562. else {
  108563. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  108564. }
  108565. // Diffuse
  108566. if (typeof extension.values.diffuse === "string") {
  108567. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  108568. }
  108569. else {
  108570. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  108571. }
  108572. // Emission
  108573. if (typeof extension.values.emission === "string") {
  108574. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  108575. }
  108576. else {
  108577. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  108578. }
  108579. // Specular
  108580. if (typeof extension.values.specular === "string") {
  108581. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  108582. }
  108583. else {
  108584. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  108585. }
  108586. return true;
  108587. };
  108588. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  108589. // Create buffer from texture url
  108590. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  108591. // Create texture from buffer
  108592. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  108593. }, onError);
  108594. };
  108595. return GLTFMaterialsCommonExtension;
  108596. }(GLTF1.GLTFLoaderExtension));
  108597. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  108598. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  108599. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108600. })(BABYLON || (BABYLON = {}));
  108601. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  108602. var BABYLON;
  108603. (function (BABYLON) {
  108604. var GLTF2;
  108605. (function (GLTF2) {
  108606. var ArrayItem = /** @class */ (function () {
  108607. function ArrayItem() {
  108608. }
  108609. ArrayItem.Assign = function (values) {
  108610. if (values) {
  108611. for (var index = 0; index < values.length; index++) {
  108612. values[index]._index = index;
  108613. }
  108614. }
  108615. };
  108616. return ArrayItem;
  108617. }());
  108618. GLTF2.ArrayItem = ArrayItem;
  108619. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108620. })(BABYLON || (BABYLON = {}));
  108621. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  108622. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  108623. var BABYLON;
  108624. (function (BABYLON) {
  108625. var GLTF2;
  108626. (function (GLTF2) {
  108627. var GLTFLoader = /** @class */ (function () {
  108628. function GLTFLoader() {
  108629. this._completePromises = new Array();
  108630. this._disposed = false;
  108631. this._state = null;
  108632. this._extensions = {};
  108633. this._defaultSampler = {};
  108634. this._requests = new Array();
  108635. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  108636. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  108637. this.compileMaterials = false;
  108638. this.useClipPlane = false;
  108639. this.compileShadowGenerators = false;
  108640. this.onDisposeObservable = new BABYLON.Observable();
  108641. this.onMeshLoadedObservable = new BABYLON.Observable();
  108642. this.onTextureLoadedObservable = new BABYLON.Observable();
  108643. this.onMaterialLoadedObservable = new BABYLON.Observable();
  108644. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  108645. this.onExtensionLoadedObservable = new BABYLON.Observable();
  108646. this.onCompleteObservable = new BABYLON.Observable();
  108647. }
  108648. GLTFLoader._Register = function (name, factory) {
  108649. if (GLTFLoader._Factories[name]) {
  108650. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  108651. return;
  108652. }
  108653. GLTFLoader._Factories[name] = factory;
  108654. // Keep the order of registration so that extensions registered first are called first.
  108655. GLTFLoader._Names.push(name);
  108656. };
  108657. Object.defineProperty(GLTFLoader.prototype, "state", {
  108658. get: function () {
  108659. return this._state;
  108660. },
  108661. enumerable: true,
  108662. configurable: true
  108663. });
  108664. GLTFLoader.prototype.dispose = function () {
  108665. if (this._disposed) {
  108666. return;
  108667. }
  108668. this._disposed = true;
  108669. this.onDisposeObservable.notifyObservers(this);
  108670. this.onDisposeObservable.clear();
  108671. this._clear();
  108672. };
  108673. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  108674. var _this = this;
  108675. return Promise.resolve().then(function () {
  108676. var nodes = null;
  108677. if (meshesNames) {
  108678. var nodeMap_1 = {};
  108679. if (_this._gltf.nodes) {
  108680. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  108681. var node = _a[_i];
  108682. if (node.name) {
  108683. nodeMap_1[node.name] = node;
  108684. }
  108685. }
  108686. }
  108687. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  108688. nodes = names.map(function (name) {
  108689. var node = nodeMap_1[name];
  108690. if (!node) {
  108691. throw new Error("Failed to find node '" + name + "'");
  108692. }
  108693. return node;
  108694. });
  108695. }
  108696. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  108697. return {
  108698. meshes: _this._getMeshes(),
  108699. particleSystems: [],
  108700. skeletons: _this._getSkeletons(),
  108701. };
  108702. });
  108703. });
  108704. };
  108705. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  108706. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  108707. };
  108708. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  108709. var _this = this;
  108710. return Promise.resolve().then(function () {
  108711. _this._loadExtensions();
  108712. _this._babylonScene = scene;
  108713. _this._rootUrl = rootUrl;
  108714. _this._progressCallback = onProgress;
  108715. _this._state = BABYLON.GLTFLoaderState.Loading;
  108716. _this._loadData(data);
  108717. _this._checkExtensions();
  108718. var promises = new Array();
  108719. if (nodes) {
  108720. promises.push(_this._loadNodesAsync(nodes));
  108721. }
  108722. else {
  108723. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  108724. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  108725. }
  108726. if (_this.compileMaterials) {
  108727. promises.push(_this._compileMaterialsAsync());
  108728. }
  108729. if (_this.compileShadowGenerators) {
  108730. promises.push(_this._compileShadowGeneratorsAsync());
  108731. }
  108732. var resultPromise = Promise.all(promises).then(function () {
  108733. _this._state = BABYLON.GLTFLoaderState.Ready;
  108734. _this._startAnimations();
  108735. });
  108736. resultPromise.then(function () {
  108737. _this._rootBabylonMesh.setEnabled(true);
  108738. BABYLON.Tools.SetImmediate(function () {
  108739. if (!_this._disposed) {
  108740. Promise.all(_this._completePromises).then(function () {
  108741. _this._state = BABYLON.GLTFLoaderState.Complete;
  108742. _this.onCompleteObservable.notifyObservers(_this);
  108743. _this.onCompleteObservable.clear();
  108744. _this._clear();
  108745. }).catch(function (error) {
  108746. BABYLON.Tools.Error("glTF Loader: " + error.message);
  108747. _this._clear();
  108748. });
  108749. }
  108750. });
  108751. });
  108752. return resultPromise;
  108753. }).catch(function (error) {
  108754. BABYLON.Tools.Error("glTF Loader: " + error.message);
  108755. _this._clear();
  108756. throw error;
  108757. });
  108758. };
  108759. GLTFLoader.prototype._loadExtensions = function () {
  108760. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  108761. var name_1 = _a[_i];
  108762. var extension = GLTFLoader._Factories[name_1](this);
  108763. this._extensions[name_1] = extension;
  108764. this.onExtensionLoadedObservable.notifyObservers(extension);
  108765. }
  108766. this.onExtensionLoadedObservable.clear();
  108767. };
  108768. GLTFLoader.prototype._loadData = function (data) {
  108769. this._gltf = data.json;
  108770. this._setupData();
  108771. if (data.bin) {
  108772. var buffers = this._gltf.buffers;
  108773. if (buffers && buffers[0] && !buffers[0].uri) {
  108774. var binaryBuffer = buffers[0];
  108775. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  108776. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  108777. }
  108778. binaryBuffer._data = Promise.resolve(data.bin);
  108779. }
  108780. else {
  108781. BABYLON.Tools.Warn("Unexpected BIN chunk");
  108782. }
  108783. }
  108784. };
  108785. GLTFLoader.prototype._setupData = function () {
  108786. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  108787. GLTF2.ArrayItem.Assign(this._gltf.animations);
  108788. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  108789. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  108790. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  108791. GLTF2.ArrayItem.Assign(this._gltf.images);
  108792. GLTF2.ArrayItem.Assign(this._gltf.materials);
  108793. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  108794. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  108795. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  108796. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  108797. GLTF2.ArrayItem.Assign(this._gltf.skins);
  108798. GLTF2.ArrayItem.Assign(this._gltf.textures);
  108799. if (this._gltf.nodes) {
  108800. var nodeParents = {};
  108801. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  108802. var node = _a[_i];
  108803. if (node.children) {
  108804. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  108805. var index = _c[_b];
  108806. nodeParents[index] = node._index;
  108807. }
  108808. }
  108809. }
  108810. var rootNode = this._createRootNode();
  108811. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  108812. var node = _e[_d];
  108813. var parentIndex = nodeParents[node._index];
  108814. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  108815. }
  108816. }
  108817. };
  108818. GLTFLoader.prototype._checkExtensions = function () {
  108819. if (this._gltf.extensionsRequired) {
  108820. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  108821. var name_2 = _a[_i];
  108822. var extension = this._extensions[name_2];
  108823. if (!extension || !extension.enabled) {
  108824. throw new Error("Require extension " + name_2 + " is not available");
  108825. }
  108826. }
  108827. }
  108828. };
  108829. GLTFLoader.prototype._createRootNode = function () {
  108830. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  108831. this._rootBabylonMesh.setEnabled(false);
  108832. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  108833. switch (this.coordinateSystemMode) {
  108834. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  108835. if (!this._babylonScene.useRightHandedSystem) {
  108836. rootNode.rotation = [0, 1, 0, 0];
  108837. rootNode.scale = [1, 1, -1];
  108838. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  108839. }
  108840. break;
  108841. }
  108842. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  108843. this._babylonScene.useRightHandedSystem = true;
  108844. break;
  108845. }
  108846. default: {
  108847. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  108848. }
  108849. }
  108850. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  108851. return rootNode;
  108852. };
  108853. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  108854. var promises = new Array();
  108855. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  108856. var node = nodes_1[_i];
  108857. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  108858. }
  108859. promises.push(this._loadAnimationsAsync());
  108860. return Promise.all(promises).then(function () { });
  108861. };
  108862. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  108863. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  108864. if (promise) {
  108865. return promise;
  108866. }
  108867. var promises = new Array();
  108868. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  108869. var index = _a[_i];
  108870. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  108871. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  108872. }
  108873. promises.push(this._loadAnimationsAsync());
  108874. return Promise.all(promises).then(function () { });
  108875. };
  108876. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  108877. if (node._primitiveBabylonMeshes) {
  108878. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  108879. var babylonMesh = _a[_i];
  108880. callback(babylonMesh);
  108881. }
  108882. }
  108883. else {
  108884. callback(node._babylonMesh);
  108885. }
  108886. };
  108887. GLTFLoader.prototype._getMeshes = function () {
  108888. var meshes = new Array();
  108889. // Root mesh is always first.
  108890. meshes.push(this._rootBabylonMesh);
  108891. var nodes = this._gltf.nodes;
  108892. if (nodes) {
  108893. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  108894. var node = nodes_2[_i];
  108895. if (node._babylonMesh) {
  108896. meshes.push(node._babylonMesh);
  108897. }
  108898. if (node._primitiveBabylonMeshes) {
  108899. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  108900. var babylonMesh = _b[_a];
  108901. meshes.push(babylonMesh);
  108902. }
  108903. }
  108904. }
  108905. }
  108906. return meshes;
  108907. };
  108908. GLTFLoader.prototype._getSkeletons = function () {
  108909. var skeletons = new Array();
  108910. var skins = this._gltf.skins;
  108911. if (skins) {
  108912. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  108913. var skin = skins_1[_i];
  108914. if (skin._babylonSkeleton) {
  108915. skeletons.push(skin._babylonSkeleton);
  108916. }
  108917. }
  108918. }
  108919. return skeletons;
  108920. };
  108921. GLTFLoader.prototype._startAnimations = function () {
  108922. var animations = this._gltf.animations;
  108923. if (!animations) {
  108924. return;
  108925. }
  108926. switch (this.animationStartMode) {
  108927. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  108928. // do nothing
  108929. break;
  108930. }
  108931. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  108932. var animation = animations[0];
  108933. animation._babylonAnimationGroup.start(true);
  108934. break;
  108935. }
  108936. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  108937. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  108938. var animation = animations_1[_i];
  108939. animation._babylonAnimationGroup.start(true);
  108940. }
  108941. break;
  108942. }
  108943. default: {
  108944. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  108945. return;
  108946. }
  108947. }
  108948. };
  108949. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  108950. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  108951. if (promise) {
  108952. return promise;
  108953. }
  108954. if (node._babylonMesh) {
  108955. throw new Error(context + ": Invalid recursive node hierarchy");
  108956. }
  108957. var promises = new Array();
  108958. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  108959. node._babylonMesh = babylonMesh;
  108960. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  108961. node._babylonAnimationTargets.push(babylonMesh);
  108962. GLTFLoader._LoadTransform(node, babylonMesh);
  108963. if (node.mesh != undefined) {
  108964. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  108965. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  108966. }
  108967. if (node.children) {
  108968. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  108969. var index = _a[_i];
  108970. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  108971. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  108972. }
  108973. }
  108974. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  108975. return Promise.all(promises).then(function () { });
  108976. };
  108977. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  108978. // TODO: instancing
  108979. var _this = this;
  108980. var promises = new Array();
  108981. var primitives = mesh.primitives;
  108982. if (!primitives || primitives.length === 0) {
  108983. throw new Error(context + ": Primitives are missing");
  108984. }
  108985. GLTF2.ArrayItem.Assign(primitives);
  108986. if (primitives.length === 1) {
  108987. var primitive = primitives[0];
  108988. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  108989. }
  108990. else {
  108991. node._primitiveBabylonMeshes = [];
  108992. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  108993. var primitive = primitives_1[_i];
  108994. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  108995. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  108996. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  108997. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  108998. }
  108999. }
  109000. if (node.skin != undefined) {
  109001. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  109002. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  109003. }
  109004. return Promise.all(promises).then(function () {
  109005. _this._forEachPrimitive(node, function (babylonMesh) {
  109006. babylonMesh._refreshBoundingInfo(true);
  109007. });
  109008. });
  109009. };
  109010. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  109011. var _this = this;
  109012. var promises = new Array();
  109013. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  109014. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  109015. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  109016. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  109017. }));
  109018. if (primitive.material == undefined) {
  109019. babylonMesh.material = this._getDefaultMaterial();
  109020. }
  109021. else {
  109022. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  109023. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, function (babylonMaterial) {
  109024. babylonMesh.material = babylonMaterial;
  109025. }));
  109026. }
  109027. return Promise.all(promises).then(function () { });
  109028. };
  109029. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  109030. var _this = this;
  109031. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  109032. if (promise) {
  109033. return promise;
  109034. }
  109035. var attributes = primitive.attributes;
  109036. if (!attributes) {
  109037. throw new Error(context + ": Attributes are missing");
  109038. }
  109039. if (primitive.mode != undefined && primitive.mode !== 4 /* TRIANGLES */) {
  109040. // TODO: handle other primitive modes
  109041. throw new Error(context + ": Mode (" + primitive.mode + ") is not currently supported");
  109042. }
  109043. var promises = new Array();
  109044. var babylonVertexData = new BABYLON.VertexData();
  109045. if (primitive.indices == undefined) {
  109046. var positionAccessorIndex = attributes["POSITION"];
  109047. if (positionAccessorIndex != undefined) {
  109048. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  109049. babylonVertexData.indices = new Uint32Array(accessor.count);
  109050. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  109051. babylonVertexData.indices[i] = i;
  109052. }
  109053. }
  109054. }
  109055. else {
  109056. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  109057. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  109058. babylonVertexData.indices = data;
  109059. }));
  109060. }
  109061. var loadAttribute = function (attribute, kind) {
  109062. if (attributes[attribute] == undefined) {
  109063. return;
  109064. }
  109065. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  109066. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  109067. babylonMesh._delayInfo.push(kind);
  109068. }
  109069. if (attribute === "COLOR_0") {
  109070. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  109071. babylonMesh.hasVertexAlpha = true;
  109072. }
  109073. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  109074. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  109075. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  109076. if (attribute === "COLOR_0" && accessor.type === "VEC3") {
  109077. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  109078. }
  109079. babylonVertexData.set(attributeData, kind);
  109080. }));
  109081. };
  109082. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  109083. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  109084. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  109085. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  109086. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  109087. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  109088. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  109089. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  109090. return Promise.all(promises).then(function () {
  109091. return babylonVertexData;
  109092. });
  109093. };
  109094. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  109095. if (!primitive.targets) {
  109096. return;
  109097. }
  109098. if (node._numMorphTargets == undefined) {
  109099. node._numMorphTargets = primitive.targets.length;
  109100. }
  109101. else if (primitive.targets.length !== node._numMorphTargets) {
  109102. throw new Error(context + ": Primitives do not have the same number of targets");
  109103. }
  109104. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  109105. for (var index = 0; index < primitive.targets.length; index++) {
  109106. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  109107. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  109108. // TODO: tell the target whether it has positions, normals, tangents
  109109. }
  109110. };
  109111. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  109112. if (!primitive.targets) {
  109113. return Promise.resolve();
  109114. }
  109115. var promises = new Array();
  109116. var morphTargetManager = babylonMesh.morphTargetManager;
  109117. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  109118. var babylonMorphTarget = morphTargetManager.getTarget(index);
  109119. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  109120. }
  109121. return Promise.all(promises).then(function () { });
  109122. };
  109123. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  109124. var _this = this;
  109125. var promises = new Array();
  109126. var loadAttribute = function (attribute, setData) {
  109127. if (attributes[attribute] == undefined) {
  109128. return;
  109129. }
  109130. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  109131. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  109132. setData(data);
  109133. }));
  109134. };
  109135. loadAttribute("POSITION", function (data) {
  109136. if (babylonVertexData.positions) {
  109137. for (var i = 0; i < data.length; i++) {
  109138. data[i] += babylonVertexData.positions[i];
  109139. }
  109140. babylonMorphTarget.setPositions(data);
  109141. }
  109142. });
  109143. loadAttribute("NORMAL", function (data) {
  109144. if (babylonVertexData.normals) {
  109145. for (var i = 0; i < data.length; i++) {
  109146. data[i] += babylonVertexData.normals[i];
  109147. }
  109148. babylonMorphTarget.setNormals(data);
  109149. }
  109150. });
  109151. loadAttribute("TANGENT", function (data) {
  109152. if (babylonVertexData.tangents) {
  109153. // Tangent data for morph targets is stored as xyz delta.
  109154. // The vertexData.tangent is stored as xyzw.
  109155. // So we need to skip every fourth vertexData.tangent.
  109156. for (var i = 0, j = 0; i < data.length; i++) {
  109157. data[i] += babylonVertexData.tangents[j++];
  109158. if ((i + 1) % 3 == 0) {
  109159. j++;
  109160. }
  109161. }
  109162. babylonMorphTarget.setTangents(data);
  109163. }
  109164. });
  109165. return Promise.all(promises).then(function () { });
  109166. };
  109167. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  109168. if (accessor.componentType == 5126 /* FLOAT */) {
  109169. return data;
  109170. }
  109171. var factor = 1;
  109172. if (accessor.normalized) {
  109173. switch (accessor.componentType) {
  109174. case 5121 /* UNSIGNED_BYTE */: {
  109175. factor = 1 / 255;
  109176. break;
  109177. }
  109178. case 5123 /* UNSIGNED_SHORT */: {
  109179. factor = 1 / 65535;
  109180. break;
  109181. }
  109182. default: {
  109183. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  109184. }
  109185. }
  109186. }
  109187. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  109188. for (var i = 0; i < result.length; i++) {
  109189. result[i] = data[i] * factor;
  109190. }
  109191. return result;
  109192. };
  109193. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  109194. var result = new Float32Array(data.length / 3 * 4);
  109195. var offset = 0;
  109196. for (var i = 0; i < result.length; i++) {
  109197. if ((i + 1) % 4 === 0) {
  109198. result[i] = 1;
  109199. }
  109200. else {
  109201. result[i] = data[offset++];
  109202. }
  109203. }
  109204. return result;
  109205. };
  109206. GLTFLoader._LoadTransform = function (node, babylonNode) {
  109207. var position = BABYLON.Vector3.Zero();
  109208. var rotation = BABYLON.Quaternion.Identity();
  109209. var scaling = BABYLON.Vector3.One();
  109210. if (node.matrix) {
  109211. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  109212. matrix.decompose(scaling, rotation, position);
  109213. }
  109214. else {
  109215. if (node.translation)
  109216. position = BABYLON.Vector3.FromArray(node.translation);
  109217. if (node.rotation)
  109218. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  109219. if (node.scale)
  109220. scaling = BABYLON.Vector3.FromArray(node.scale);
  109221. }
  109222. babylonNode.position = position;
  109223. babylonNode.rotationQuaternion = rotation;
  109224. babylonNode.scaling = scaling;
  109225. };
  109226. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  109227. var _this = this;
  109228. var assignSkeleton = function () {
  109229. _this._forEachPrimitive(node, function (babylonMesh) {
  109230. babylonMesh.skeleton = skin._babylonSkeleton;
  109231. });
  109232. node._babylonMesh.parent = _this._rootBabylonMesh;
  109233. node._babylonMesh.position = BABYLON.Vector3.Zero();
  109234. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  109235. node._babylonMesh.scaling = BABYLON.Vector3.One();
  109236. };
  109237. if (skin._loaded) {
  109238. return skin._loaded.then(function () {
  109239. assignSkeleton();
  109240. });
  109241. }
  109242. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  109243. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  109244. var skeletonId = "skeleton" + skin._index;
  109245. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  109246. skin._babylonSkeleton = babylonSkeleton;
  109247. _this._loadBones(context, skin, inverseBindMatricesData);
  109248. assignSkeleton();
  109249. }));
  109250. };
  109251. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  109252. if (skin.inverseBindMatrices == undefined) {
  109253. return Promise.resolve(null);
  109254. }
  109255. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  109256. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  109257. return data;
  109258. });
  109259. };
  109260. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  109261. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  109262. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  109263. node._babylonAnimationTargets.push(babylonBone);
  109264. return babylonBone;
  109265. };
  109266. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  109267. var babylonBones = {};
  109268. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  109269. var index = _a[_i];
  109270. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  109271. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  109272. }
  109273. };
  109274. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  109275. var babylonBone = babylonBones[node._index];
  109276. if (babylonBone) {
  109277. return babylonBone;
  109278. }
  109279. var boneIndex = skin.joints.indexOf(node._index);
  109280. var baseMatrix = BABYLON.Matrix.Identity();
  109281. if (inverseBindMatricesData && boneIndex !== -1) {
  109282. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  109283. baseMatrix.invertToRef(baseMatrix);
  109284. }
  109285. var babylonParentBone = null;
  109286. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  109287. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  109288. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  109289. }
  109290. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  109291. babylonBones[node._index] = babylonBone;
  109292. return babylonBone;
  109293. };
  109294. GLTFLoader.prototype._getNodeMatrix = function (node) {
  109295. return node.matrix ?
  109296. BABYLON.Matrix.FromArray(node.matrix) :
  109297. 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());
  109298. };
  109299. GLTFLoader.prototype._loadAnimationsAsync = function () {
  109300. var animations = this._gltf.animations;
  109301. if (!animations) {
  109302. return Promise.resolve();
  109303. }
  109304. var promises = new Array();
  109305. for (var index = 0; index < animations.length; index++) {
  109306. var animation = animations[index];
  109307. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  109308. }
  109309. return Promise.all(promises).then(function () { });
  109310. };
  109311. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  109312. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  109313. animation._babylonAnimationGroup = babylonAnimationGroup;
  109314. var promises = new Array();
  109315. GLTF2.ArrayItem.Assign(animation.channels);
  109316. GLTF2.ArrayItem.Assign(animation.samplers);
  109317. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  109318. var channel = _a[_i];
  109319. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  109320. }
  109321. this.onAnimationGroupLoadedObservable.notifyObservers(babylonAnimationGroup);
  109322. return Promise.all(promises).then(function () {
  109323. babylonAnimationGroup.normalize();
  109324. });
  109325. };
  109326. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  109327. var _this = this;
  109328. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  109329. if (!targetNode._babylonMesh || targetNode.skin != undefined) {
  109330. return Promise.resolve();
  109331. }
  109332. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  109333. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  109334. var targetPath;
  109335. var animationType;
  109336. switch (channel.target.path) {
  109337. case "translation" /* TRANSLATION */: {
  109338. targetPath = "position";
  109339. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  109340. break;
  109341. }
  109342. case "rotation" /* ROTATION */: {
  109343. targetPath = "rotationQuaternion";
  109344. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  109345. break;
  109346. }
  109347. case "scale" /* SCALE */: {
  109348. targetPath = "scaling";
  109349. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  109350. break;
  109351. }
  109352. case "weights" /* WEIGHTS */: {
  109353. targetPath = "influence";
  109354. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  109355. break;
  109356. }
  109357. default: {
  109358. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  109359. }
  109360. }
  109361. var outputBufferOffset = 0;
  109362. var getNextOutputValue;
  109363. switch (targetPath) {
  109364. case "position": {
  109365. getNextOutputValue = function () {
  109366. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  109367. outputBufferOffset += 3;
  109368. return value;
  109369. };
  109370. break;
  109371. }
  109372. case "rotationQuaternion": {
  109373. getNextOutputValue = function () {
  109374. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  109375. outputBufferOffset += 4;
  109376. return value;
  109377. };
  109378. break;
  109379. }
  109380. case "scaling": {
  109381. getNextOutputValue = function () {
  109382. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  109383. outputBufferOffset += 3;
  109384. return value;
  109385. };
  109386. break;
  109387. }
  109388. case "influence": {
  109389. getNextOutputValue = function () {
  109390. var value = new Array(targetNode._numMorphTargets);
  109391. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  109392. value[i] = data.output[outputBufferOffset++];
  109393. }
  109394. return value;
  109395. };
  109396. break;
  109397. }
  109398. }
  109399. var getNextKey;
  109400. switch (data.interpolation) {
  109401. case "STEP" /* STEP */: {
  109402. getNextKey = function (frameIndex) { return ({
  109403. frame: data.input[frameIndex],
  109404. value: getNextOutputValue(),
  109405. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  109406. }); };
  109407. break;
  109408. }
  109409. case "LINEAR" /* LINEAR */: {
  109410. getNextKey = function (frameIndex) { return ({
  109411. frame: data.input[frameIndex],
  109412. value: getNextOutputValue()
  109413. }); };
  109414. break;
  109415. }
  109416. case "CUBICSPLINE" /* CUBICSPLINE */: {
  109417. getNextKey = function (frameIndex) { return ({
  109418. frame: data.input[frameIndex],
  109419. inTangent: getNextOutputValue(),
  109420. value: getNextOutputValue(),
  109421. outTangent: getNextOutputValue()
  109422. }); };
  109423. break;
  109424. }
  109425. }
  109426. var keys;
  109427. if (data.input.length === 1) {
  109428. var key = getNextKey(0);
  109429. keys = [
  109430. { frame: key.frame, value: key.value },
  109431. { frame: key.frame + 1, value: key.value }
  109432. ];
  109433. }
  109434. else {
  109435. keys = new Array(data.input.length);
  109436. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  109437. keys[frameIndex] = getNextKey(frameIndex);
  109438. }
  109439. }
  109440. if (targetPath === "influence") {
  109441. var _loop_1 = function (targetIndex) {
  109442. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  109443. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  109444. babylonAnimation.setKeys(keys.map(function (key) { return ({
  109445. frame: key.frame,
  109446. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  109447. value: key.value[targetIndex],
  109448. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  109449. }); }));
  109450. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  109451. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  109452. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  109453. });
  109454. };
  109455. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  109456. _loop_1(targetIndex);
  109457. }
  109458. }
  109459. else {
  109460. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  109461. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  109462. babylonAnimation.setKeys(keys);
  109463. if (targetNode._babylonAnimationTargets) {
  109464. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  109465. var target = _a[_i];
  109466. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  109467. }
  109468. }
  109469. }
  109470. });
  109471. };
  109472. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  109473. if (sampler._data) {
  109474. return sampler._data;
  109475. }
  109476. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  109477. switch (interpolation) {
  109478. case "STEP" /* STEP */:
  109479. case "LINEAR" /* LINEAR */:
  109480. case "CUBICSPLINE" /* CUBICSPLINE */: {
  109481. break;
  109482. }
  109483. default: {
  109484. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  109485. }
  109486. }
  109487. var inputData;
  109488. var outputData;
  109489. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  109490. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  109491. sampler._data = Promise.all([
  109492. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  109493. inputData = data;
  109494. }),
  109495. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  109496. outputData = data;
  109497. })
  109498. ]).then(function () {
  109499. return {
  109500. input: inputData,
  109501. interpolation: interpolation,
  109502. output: outputData,
  109503. };
  109504. });
  109505. return sampler._data;
  109506. };
  109507. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  109508. if (buffer._data) {
  109509. return buffer._data;
  109510. }
  109511. if (!buffer.uri) {
  109512. throw new Error(context + ": Uri is missing");
  109513. }
  109514. buffer._data = this._loadUriAsync(context, buffer.uri);
  109515. return buffer._data;
  109516. };
  109517. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  109518. if (bufferView._data) {
  109519. return bufferView._data;
  109520. }
  109521. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  109522. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  109523. try {
  109524. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  109525. }
  109526. catch (e) {
  109527. throw new Error(context + ": " + e.message);
  109528. }
  109529. });
  109530. return bufferView._data;
  109531. };
  109532. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  109533. var _this = this;
  109534. if (accessor.sparse) {
  109535. throw new Error(context + ": Sparse accessors are not currently supported");
  109536. }
  109537. if (accessor._data) {
  109538. return accessor._data;
  109539. }
  109540. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  109541. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  109542. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  109543. var byteOffset = accessor.byteOffset || 0;
  109544. var byteStride = bufferView.byteStride;
  109545. if (byteStride === 0) {
  109546. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  109547. }
  109548. try {
  109549. switch (accessor.componentType) {
  109550. case 5120 /* BYTE */: {
  109551. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109552. }
  109553. case 5121 /* UNSIGNED_BYTE */: {
  109554. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109555. }
  109556. case 5122 /* SHORT */: {
  109557. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109558. }
  109559. case 5123 /* UNSIGNED_SHORT */: {
  109560. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109561. }
  109562. case 5125 /* UNSIGNED_INT */: {
  109563. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109564. }
  109565. case 5126 /* FLOAT */: {
  109566. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109567. }
  109568. default: {
  109569. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  109570. }
  109571. }
  109572. }
  109573. catch (e) {
  109574. throw new Error(context + ": " + e.messsage);
  109575. }
  109576. });
  109577. return accessor._data;
  109578. };
  109579. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  109580. byteOffset += data.byteOffset;
  109581. var targetLength = count * numComponents;
  109582. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  109583. return new typedArray(data.buffer, byteOffset, targetLength);
  109584. }
  109585. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  109586. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  109587. var targetBuffer = new typedArray(targetLength);
  109588. var sourceIndex = 0;
  109589. var targetIndex = 0;
  109590. while (targetIndex < targetLength) {
  109591. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  109592. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  109593. targetIndex++;
  109594. }
  109595. sourceIndex += elementStride;
  109596. }
  109597. return targetBuffer;
  109598. };
  109599. GLTFLoader.prototype._getDefaultMaterial = function () {
  109600. var id = "__gltf_default";
  109601. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  109602. if (!babylonMaterial) {
  109603. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  109604. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  109605. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  109606. babylonMaterial.metallic = 1;
  109607. babylonMaterial.roughness = 1;
  109608. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109609. }
  109610. return babylonMaterial;
  109611. };
  109612. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  109613. var promises = new Array();
  109614. var babylonMaterial = material._babylonMaterial;
  109615. // Ensure metallic workflow
  109616. babylonMaterial.metallic = 1;
  109617. babylonMaterial.roughness = 1;
  109618. var properties = material.pbrMetallicRoughness;
  109619. if (properties) {
  109620. if (properties.baseColorFactor) {
  109621. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  109622. babylonMaterial.alpha = properties.baseColorFactor[3];
  109623. }
  109624. else {
  109625. babylonMaterial.albedoColor = BABYLON.Color3.White();
  109626. }
  109627. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  109628. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  109629. if (properties.baseColorTexture) {
  109630. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  109631. babylonMaterial.albedoTexture = texture;
  109632. }));
  109633. }
  109634. if (properties.metallicRoughnessTexture) {
  109635. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  109636. babylonMaterial.metallicTexture = texture;
  109637. }));
  109638. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  109639. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  109640. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  109641. }
  109642. }
  109643. this._loadMaterialAlphaProperties(context, material);
  109644. return Promise.all(promises).then(function () { });
  109645. };
  109646. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  109647. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, assign);
  109648. if (promise) {
  109649. return promise;
  109650. }
  109651. material._babylonMeshes = material._babylonMeshes || [];
  109652. material._babylonMeshes.push(babylonMesh);
  109653. if (!material._loaded) {
  109654. var promises = new Array();
  109655. var babylonMaterial = this._createMaterial(material);
  109656. material._babylonMaterial = babylonMaterial;
  109657. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  109658. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  109659. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109660. material._loaded = Promise.all(promises).then(function () { });
  109661. }
  109662. assign(material._babylonMaterial);
  109663. return material._loaded;
  109664. };
  109665. GLTFLoader.prototype._createMaterial = function (material) {
  109666. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  109667. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  109668. return babylonMaterial;
  109669. };
  109670. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  109671. var promises = new Array();
  109672. var babylonMaterial = material._babylonMaterial;
  109673. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  109674. if (material.doubleSided) {
  109675. babylonMaterial.backFaceCulling = false;
  109676. babylonMaterial.twoSidedLighting = true;
  109677. }
  109678. if (material.normalTexture) {
  109679. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  109680. babylonMaterial.bumpTexture = texture;
  109681. }));
  109682. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  109683. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  109684. if (material.normalTexture.scale != undefined) {
  109685. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  109686. }
  109687. }
  109688. if (material.occlusionTexture) {
  109689. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  109690. babylonMaterial.ambientTexture = texture;
  109691. }));
  109692. babylonMaterial.useAmbientInGrayScale = true;
  109693. if (material.occlusionTexture.strength != undefined) {
  109694. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  109695. }
  109696. }
  109697. if (material.emissiveTexture) {
  109698. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  109699. babylonMaterial.emissiveTexture = texture;
  109700. }));
  109701. }
  109702. return Promise.all(promises).then(function () { });
  109703. };
  109704. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  109705. var babylonMaterial = material._babylonMaterial;
  109706. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  109707. switch (alphaMode) {
  109708. case "OPAQUE" /* OPAQUE */: {
  109709. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  109710. break;
  109711. }
  109712. case "MASK" /* MASK */: {
  109713. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  109714. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  109715. if (babylonMaterial.alpha) {
  109716. if (babylonMaterial.alpha === 0) {
  109717. babylonMaterial.alphaCutOff = 1;
  109718. }
  109719. else {
  109720. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  109721. }
  109722. babylonMaterial.alpha = 1;
  109723. }
  109724. if (babylonMaterial.albedoTexture) {
  109725. babylonMaterial.albedoTexture.hasAlpha = true;
  109726. }
  109727. break;
  109728. }
  109729. case "BLEND" /* BLEND */: {
  109730. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  109731. if (babylonMaterial.albedoTexture) {
  109732. babylonMaterial.albedoTexture.hasAlpha = true;
  109733. babylonMaterial.useAlphaFromAlbedoTexture = true;
  109734. }
  109735. break;
  109736. }
  109737. default: {
  109738. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  109739. }
  109740. }
  109741. };
  109742. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  109743. var _this = this;
  109744. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  109745. context = "#/textures/" + textureInfo.index;
  109746. var promises = new Array();
  109747. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  109748. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  109749. var deferred = new BABYLON.Deferred();
  109750. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  109751. if (!_this._disposed) {
  109752. deferred.resolve();
  109753. }
  109754. }, function (message, exception) {
  109755. if (!_this._disposed) {
  109756. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  109757. }
  109758. });
  109759. promises.push(deferred.promise);
  109760. babylonTexture.name = texture.name || "texture" + texture._index;
  109761. babylonTexture.wrapU = samplerData.wrapU;
  109762. babylonTexture.wrapV = samplerData.wrapV;
  109763. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  109764. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  109765. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  109766. babylonTexture.updateURL(objectURL);
  109767. }));
  109768. assign(babylonTexture);
  109769. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  109770. return Promise.all(promises).then(function () { });
  109771. };
  109772. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  109773. if (!sampler._data) {
  109774. sampler._data = {
  109775. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  109776. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  109777. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  109778. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  109779. };
  109780. }
  109781. ;
  109782. return sampler._data;
  109783. };
  109784. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  109785. if (image._objectURL) {
  109786. return image._objectURL;
  109787. }
  109788. var promise;
  109789. if (image.uri) {
  109790. promise = this._loadUriAsync(context, image.uri);
  109791. }
  109792. else {
  109793. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  109794. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  109795. }
  109796. image._objectURL = promise.then(function (data) {
  109797. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  109798. });
  109799. return image._objectURL;
  109800. };
  109801. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  109802. var _this = this;
  109803. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  109804. if (promise) {
  109805. return promise;
  109806. }
  109807. if (!GLTFLoader._ValidateUri(uri)) {
  109808. throw new Error(context + ": Uri '" + uri + "' is invalid");
  109809. }
  109810. if (BABYLON.Tools.IsBase64(uri)) {
  109811. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  109812. }
  109813. return new Promise(function (resolve, reject) {
  109814. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  109815. if (!_this._disposed) {
  109816. resolve(new Uint8Array(data));
  109817. }
  109818. }, function (event) {
  109819. if (!_this._disposed) {
  109820. try {
  109821. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  109822. request._lengthComputable = event.lengthComputable;
  109823. request._loaded = event.loaded;
  109824. request._total = event.total;
  109825. _this._onProgress();
  109826. }
  109827. }
  109828. catch (e) {
  109829. reject(e);
  109830. }
  109831. }
  109832. }, _this._babylonScene.database, true, function (request, exception) {
  109833. if (!_this._disposed) {
  109834. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  109835. }
  109836. });
  109837. _this._requests.push(request);
  109838. });
  109839. };
  109840. GLTFLoader.prototype._onProgress = function () {
  109841. if (!this._progressCallback) {
  109842. return;
  109843. }
  109844. var lengthComputable = true;
  109845. var loaded = 0;
  109846. var total = 0;
  109847. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  109848. var request = _a[_i];
  109849. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  109850. return;
  109851. }
  109852. lengthComputable = lengthComputable && request._lengthComputable;
  109853. loaded += request._loaded;
  109854. total += request._total;
  109855. }
  109856. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  109857. };
  109858. GLTFLoader._GetProperty = function (context, array, index) {
  109859. if (!array || index == undefined || !array[index]) {
  109860. throw new Error(context + ": Failed to find index (" + index + ")");
  109861. }
  109862. return array[index];
  109863. };
  109864. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  109865. // Set defaults if undefined
  109866. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  109867. switch (mode) {
  109868. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  109869. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  109870. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  109871. default:
  109872. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  109873. return BABYLON.Texture.WRAP_ADDRESSMODE;
  109874. }
  109875. };
  109876. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  109877. // Set defaults if undefined
  109878. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  109879. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  109880. if (magFilter === 9729 /* LINEAR */) {
  109881. switch (minFilter) {
  109882. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  109883. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  109884. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  109885. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  109886. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  109887. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  109888. default:
  109889. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  109890. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  109891. }
  109892. }
  109893. else {
  109894. if (magFilter !== 9728 /* NEAREST */) {
  109895. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  109896. }
  109897. switch (minFilter) {
  109898. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  109899. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  109900. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  109901. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  109902. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  109903. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  109904. default:
  109905. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  109906. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  109907. }
  109908. }
  109909. };
  109910. GLTFLoader._GetNumComponents = function (context, type) {
  109911. switch (type) {
  109912. case "SCALAR": return 1;
  109913. case "VEC2": return 2;
  109914. case "VEC3": return 3;
  109915. case "VEC4": return 4;
  109916. case "MAT2": return 4;
  109917. case "MAT3": return 9;
  109918. case "MAT4": return 16;
  109919. }
  109920. throw new Error(context + ": Invalid type (" + type + ")");
  109921. };
  109922. GLTFLoader._ValidateUri = function (uri) {
  109923. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  109924. };
  109925. GLTFLoader.prototype._compileMaterialsAsync = function () {
  109926. var promises = new Array();
  109927. if (this._gltf.materials) {
  109928. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  109929. var material = _a[_i];
  109930. var babylonMaterial = material._babylonMaterial;
  109931. var babylonMeshes = material._babylonMeshes;
  109932. if (babylonMaterial && babylonMeshes) {
  109933. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  109934. var babylonMesh = babylonMeshes_1[_b];
  109935. // Ensure nonUniformScaling is set if necessary.
  109936. babylonMesh.computeWorldMatrix(true);
  109937. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  109938. if (this.useClipPlane) {
  109939. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  109940. }
  109941. }
  109942. }
  109943. }
  109944. }
  109945. return Promise.all(promises).then(function () { });
  109946. };
  109947. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  109948. var promises = new Array();
  109949. var lights = this._babylonScene.lights;
  109950. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  109951. var light = lights_1[_i];
  109952. var generator = light.getShadowGenerator();
  109953. if (generator) {
  109954. promises.push(generator.forceCompilationAsync());
  109955. }
  109956. }
  109957. return Promise.all(promises).then(function () { });
  109958. };
  109959. GLTFLoader.prototype._clear = function () {
  109960. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  109961. var request = _a[_i];
  109962. request.abort();
  109963. }
  109964. this._requests.length = 0;
  109965. if (this._gltf && this._gltf.images) {
  109966. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  109967. var image = _c[_b];
  109968. if (image._objectURL) {
  109969. image._objectURL.then(function (value) {
  109970. URL.revokeObjectURL(value);
  109971. });
  109972. image._objectURL = undefined;
  109973. }
  109974. }
  109975. }
  109976. delete this._gltf;
  109977. delete this._babylonScene;
  109978. this._completePromises.length = 0;
  109979. for (var name_3 in this._extensions) {
  109980. this._extensions[name_3].dispose();
  109981. }
  109982. this._extensions = {};
  109983. delete this._rootBabylonMesh;
  109984. delete this._progressCallback;
  109985. this.onMeshLoadedObservable.clear();
  109986. this.onTextureLoadedObservable.clear();
  109987. this.onMaterialLoadedObservable.clear();
  109988. };
  109989. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  109990. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  109991. var name_4 = _a[_i];
  109992. var extension = this._extensions[name_4];
  109993. if (extension.enabled) {
  109994. var promise = actionAsync(extension);
  109995. if (promise) {
  109996. return promise;
  109997. }
  109998. }
  109999. }
  110000. return null;
  110001. };
  110002. GLTFLoader._Names = new Array();
  110003. GLTFLoader._Factories = {};
  110004. return GLTFLoader;
  110005. }());
  110006. GLTF2.GLTFLoader = GLTFLoader;
  110007. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  110008. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110009. })(BABYLON || (BABYLON = {}));
  110010. //# sourceMappingURL=babylon.glTFLoader.js.map
  110011. var BABYLON;
  110012. (function (BABYLON) {
  110013. var GLTF2;
  110014. (function (GLTF2) {
  110015. var GLTFLoaderExtension = /** @class */ (function () {
  110016. function GLTFLoaderExtension(loader) {
  110017. this.enabled = true;
  110018. this._loader = loader;
  110019. }
  110020. GLTFLoaderExtension.prototype.dispose = function () {
  110021. delete this._loader;
  110022. };
  110023. // #region Overridable Methods
  110024. /** Override this method to modify the default behavior for loading scenes. */
  110025. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  110026. /** Override this method to modify the default behavior for loading nodes. */
  110027. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  110028. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  110029. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  110030. /** Override this method to modify the default behavior for loading materials. */
  110031. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) { return null; };
  110032. /** Override this method to modify the default behavior for loading uris. */
  110033. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  110034. // #endregion
  110035. /** Helper method called by a loader extension to load an glTF extension. */
  110036. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  110037. if (!property.extensions) {
  110038. return null;
  110039. }
  110040. var extensions = property.extensions;
  110041. var extension = extensions[this.name];
  110042. if (!extension) {
  110043. return null;
  110044. }
  110045. // Clear out the extension before executing the action to avoid recursing into the same property.
  110046. delete extensions[this.name];
  110047. try {
  110048. return actionAsync(context + "/extensions/" + this.name, extension);
  110049. }
  110050. finally {
  110051. // Restore the extension after executing the action.
  110052. extensions[this.name] = extension;
  110053. }
  110054. };
  110055. /** Helper method called by the loader to allow extensions to override loading scenes. */
  110056. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  110057. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  110058. };
  110059. /** Helper method called by the loader to allow extensions to override loading nodes. */
  110060. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  110061. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  110062. };
  110063. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  110064. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  110065. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  110066. };
  110067. /** Helper method called by the loader to allow extensions to override loading materials. */
  110068. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, assign) {
  110069. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, assign); });
  110070. };
  110071. /** Helper method called by the loader to allow extensions to override loading uris. */
  110072. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  110073. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  110074. };
  110075. return GLTFLoaderExtension;
  110076. }());
  110077. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  110078. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110079. })(BABYLON || (BABYLON = {}));
  110080. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  110081. var BABYLON;
  110082. (function (BABYLON) {
  110083. var GLTF2;
  110084. (function (GLTF2) {
  110085. var Extensions;
  110086. (function (Extensions) {
  110087. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  110088. var NAME = "MSFT_lod";
  110089. var MSFT_lod = /** @class */ (function (_super) {
  110090. __extends(MSFT_lod, _super);
  110091. function MSFT_lod() {
  110092. var _this = _super !== null && _super.apply(this, arguments) || this;
  110093. _this.name = NAME;
  110094. /**
  110095. * Maximum number of LODs to load, starting from the lowest LOD.
  110096. */
  110097. _this.maxLODsToLoad = Number.MAX_VALUE;
  110098. _this._loadingNodeLOD = null;
  110099. _this._loadNodeSignals = {};
  110100. _this._loadingMaterialLOD = null;
  110101. _this._loadMaterialSignals = {};
  110102. return _this;
  110103. }
  110104. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  110105. var _this = this;
  110106. return this._loadExtensionAsync(context, node, function (context, extension) {
  110107. var firstPromise;
  110108. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  110109. var _loop_1 = function (indexLOD) {
  110110. var nodeLOD = nodeLODs[indexLOD];
  110111. if (indexLOD !== 0) {
  110112. _this._loadingNodeLOD = nodeLOD;
  110113. if (!_this._loadNodeSignals[nodeLOD._index]) {
  110114. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  110115. }
  110116. }
  110117. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  110118. if (indexLOD !== 0) {
  110119. var previousNodeLOD = nodeLODs[indexLOD - 1];
  110120. if (previousNodeLOD._babylonMesh) {
  110121. previousNodeLOD._babylonMesh.dispose();
  110122. delete previousNodeLOD._babylonMesh;
  110123. }
  110124. }
  110125. if (indexLOD !== nodeLODs.length - 1) {
  110126. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  110127. if (_this._loadNodeSignals[nodeIndex]) {
  110128. _this._loadNodeSignals[nodeIndex].resolve();
  110129. delete _this._loadNodeSignals[nodeIndex];
  110130. }
  110131. }
  110132. });
  110133. if (indexLOD === 0) {
  110134. firstPromise = promise;
  110135. }
  110136. else {
  110137. _this._loader._completePromises.push(promise);
  110138. _this._loadingNodeLOD = null;
  110139. }
  110140. };
  110141. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  110142. _loop_1(indexLOD);
  110143. }
  110144. return firstPromise;
  110145. });
  110146. };
  110147. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  110148. var _this = this;
  110149. // Don't load material LODs if already loading a node LOD.
  110150. if (this._loadingNodeLOD) {
  110151. return null;
  110152. }
  110153. return this._loadExtensionAsync(context, material, function (context, extension) {
  110154. var firstPromise;
  110155. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  110156. var _loop_2 = function (indexLOD) {
  110157. var materialLOD = materialLODs[indexLOD];
  110158. if (indexLOD !== 0) {
  110159. _this._loadingMaterialLOD = materialLOD;
  110160. if (!_this._loadMaterialSignals[materialLOD._index]) {
  110161. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  110162. }
  110163. }
  110164. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, indexLOD === 0 ? assign : function () { }).then(function () {
  110165. if (indexLOD !== 0) {
  110166. assign(materialLOD._babylonMaterial);
  110167. var previousMaterialLOD = materialLODs[indexLOD - 1];
  110168. if (previousMaterialLOD._babylonMaterial) {
  110169. previousMaterialLOD._babylonMaterial.dispose();
  110170. delete previousMaterialLOD._babylonMaterial;
  110171. }
  110172. }
  110173. if (indexLOD !== materialLODs.length - 1) {
  110174. var materialIndex = materialLODs[indexLOD + 1]._index;
  110175. if (_this._loadMaterialSignals[materialIndex]) {
  110176. _this._loadMaterialSignals[materialIndex].resolve();
  110177. delete _this._loadMaterialSignals[materialIndex];
  110178. }
  110179. }
  110180. });
  110181. if (indexLOD === 0) {
  110182. firstPromise = promise;
  110183. }
  110184. else {
  110185. _this._loader._completePromises.push(promise);
  110186. _this._loadingMaterialLOD = null;
  110187. }
  110188. };
  110189. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  110190. _loop_2(indexLOD);
  110191. }
  110192. return firstPromise;
  110193. });
  110194. };
  110195. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  110196. var _this = this;
  110197. // Defer the loading of uris if loading a material or node LOD.
  110198. if (this._loadingMaterialLOD) {
  110199. var index = this._loadingMaterialLOD._index;
  110200. return this._loadMaterialSignals[index].promise.then(function () {
  110201. return _this._loader._loadUriAsync(context, uri);
  110202. });
  110203. }
  110204. else if (this._loadingNodeLOD) {
  110205. var index = this._loadingNodeLOD._index;
  110206. return this._loadNodeSignals[index].promise.then(function () {
  110207. return _this._loader._loadUriAsync(context, uri);
  110208. });
  110209. }
  110210. return null;
  110211. };
  110212. /**
  110213. * Gets an array of LOD properties from lowest to highest.
  110214. */
  110215. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  110216. if (this.maxLODsToLoad <= 0) {
  110217. throw new Error("maxLODsToLoad must be greater than zero");
  110218. }
  110219. var properties = new Array();
  110220. for (var i = ids.length - 1; i >= 0; i--) {
  110221. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  110222. if (properties.length === this.maxLODsToLoad) {
  110223. return properties;
  110224. }
  110225. }
  110226. properties.push(property);
  110227. return properties;
  110228. };
  110229. return MSFT_lod;
  110230. }(GLTF2.GLTFLoaderExtension));
  110231. Extensions.MSFT_lod = MSFT_lod;
  110232. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  110233. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110234. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110235. })(BABYLON || (BABYLON = {}));
  110236. //# sourceMappingURL=MSFT_lod.js.map
  110237. var BABYLON;
  110238. (function (BABYLON) {
  110239. var GLTF2;
  110240. (function (GLTF2) {
  110241. var Extensions;
  110242. (function (Extensions) {
  110243. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  110244. var NAME = "KHR_draco_mesh_compression";
  110245. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  110246. __extends(KHR_draco_mesh_compression, _super);
  110247. function KHR_draco_mesh_compression(loader) {
  110248. var _this = _super.call(this, loader) || this;
  110249. _this.name = NAME;
  110250. _this._dracoCompression = null;
  110251. // Disable extension if decoder is not available.
  110252. if (!BABYLON.DracoCompression.DecoderUrl) {
  110253. _this.enabled = false;
  110254. }
  110255. return _this;
  110256. }
  110257. KHR_draco_mesh_compression.prototype.dispose = function () {
  110258. if (this._dracoCompression) {
  110259. this._dracoCompression.dispose();
  110260. }
  110261. _super.prototype.dispose.call(this);
  110262. };
  110263. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  110264. var _this = this;
  110265. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  110266. if (primitive.mode != undefined) {
  110267. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  110268. primitive.mode !== 4 /* TRIANGLES */) {
  110269. throw new Error(context + ": Unsupported mode " + primitive.mode);
  110270. }
  110271. // TODO: handle triangle strips
  110272. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  110273. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  110274. }
  110275. }
  110276. var attributes = {};
  110277. var loadAttribute = function (name, kind) {
  110278. var uniqueId = extension.attributes[name];
  110279. if (uniqueId == undefined) {
  110280. return;
  110281. }
  110282. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  110283. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  110284. babylonMesh._delayInfo.push(kind);
  110285. }
  110286. attributes[kind] = uniqueId;
  110287. };
  110288. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  110289. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  110290. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  110291. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  110292. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  110293. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  110294. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  110295. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  110296. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  110297. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  110298. try {
  110299. if (!_this._dracoCompression) {
  110300. _this._dracoCompression = new BABYLON.DracoCompression();
  110301. }
  110302. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  110303. }
  110304. catch (e) {
  110305. throw new Error(context + ": " + e.message);
  110306. }
  110307. });
  110308. });
  110309. };
  110310. return KHR_draco_mesh_compression;
  110311. }(GLTF2.GLTFLoaderExtension));
  110312. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  110313. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  110314. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110315. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110316. })(BABYLON || (BABYLON = {}));
  110317. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  110318. var BABYLON;
  110319. (function (BABYLON) {
  110320. var GLTF2;
  110321. (function (GLTF2) {
  110322. var Extensions;
  110323. (function (Extensions) {
  110324. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  110325. var NAME = "KHR_materials_pbrSpecularGlossiness";
  110326. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  110327. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  110328. function KHR_materials_pbrSpecularGlossiness() {
  110329. var _this = _super !== null && _super.apply(this, arguments) || this;
  110330. _this.name = NAME;
  110331. return _this;
  110332. }
  110333. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  110334. var _this = this;
  110335. return this._loadExtensionAsync(context, material, function (context, extension) {
  110336. material._babylonMeshes = material._babylonMeshes || [];
  110337. material._babylonMeshes.push(babylonMesh);
  110338. if (!material._loaded) {
  110339. var promises = new Array();
  110340. var babylonMaterial = _this._loader._createMaterial(material);
  110341. material._babylonMaterial = babylonMaterial;
  110342. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  110343. promises.push(_this._loadSpecularGlossinessPropertiesAsync(context, material, extension));
  110344. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  110345. material._loaded = Promise.all(promises).then(function () { });
  110346. }
  110347. assign(material._babylonMaterial);
  110348. return material._loaded;
  110349. });
  110350. };
  110351. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties) {
  110352. var promises = new Array();
  110353. var babylonMaterial = material._babylonMaterial;
  110354. if (properties.diffuseFactor) {
  110355. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  110356. babylonMaterial.alpha = properties.diffuseFactor[3];
  110357. }
  110358. else {
  110359. babylonMaterial.albedoColor = BABYLON.Color3.White();
  110360. }
  110361. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  110362. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  110363. if (properties.diffuseTexture) {
  110364. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  110365. babylonMaterial.albedoTexture = texture;
  110366. }));
  110367. }
  110368. if (properties.specularGlossinessTexture) {
  110369. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  110370. babylonMaterial.reflectivityTexture = texture;
  110371. }));
  110372. babylonMaterial.reflectivityTexture.hasAlpha = true;
  110373. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  110374. }
  110375. this._loader._loadMaterialAlphaProperties(context, material);
  110376. return Promise.all(promises).then(function () { });
  110377. };
  110378. return KHR_materials_pbrSpecularGlossiness;
  110379. }(GLTF2.GLTFLoaderExtension));
  110380. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  110381. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  110382. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110383. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110384. })(BABYLON || (BABYLON = {}));
  110385. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  110386. var BABYLON;
  110387. (function (BABYLON) {
  110388. var GLTF2;
  110389. (function (GLTF2) {
  110390. var Extensions;
  110391. (function (Extensions) {
  110392. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  110393. var NAME = "KHR_lights";
  110394. var LightType;
  110395. (function (LightType) {
  110396. LightType["AMBIENT"] = "ambient";
  110397. LightType["DIRECTIONAL"] = "directional";
  110398. LightType["POINT"] = "point";
  110399. LightType["SPOT"] = "spot";
  110400. })(LightType || (LightType = {}));
  110401. var KHR_lights = /** @class */ (function (_super) {
  110402. __extends(KHR_lights, _super);
  110403. function KHR_lights() {
  110404. var _this = _super !== null && _super.apply(this, arguments) || this;
  110405. _this.name = NAME;
  110406. return _this;
  110407. }
  110408. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  110409. var _this = this;
  110410. return this._loadExtensionAsync(context, scene, function (context, extension) {
  110411. var promise = _this._loader._loadSceneAsync(context, scene);
  110412. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  110413. if (light.type !== LightType.AMBIENT) {
  110414. throw new Error(context + ": Only ambient lights are allowed on a scene");
  110415. }
  110416. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  110417. return promise;
  110418. });
  110419. };
  110420. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  110421. var _this = this;
  110422. return this._loadExtensionAsync(context, node, function (context, extension) {
  110423. var promise = _this._loader._loadNodeAsync(context, node);
  110424. var babylonLight;
  110425. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  110426. var name = node._babylonMesh.name;
  110427. switch (light.type) {
  110428. case LightType.AMBIENT: {
  110429. throw new Error(context + ": Ambient lights are not allowed on a node");
  110430. }
  110431. case LightType.DIRECTIONAL: {
  110432. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  110433. break;
  110434. }
  110435. case LightType.POINT: {
  110436. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  110437. break;
  110438. }
  110439. case LightType.SPOT: {
  110440. var spotLight = light;
  110441. // TODO: support inner and outer cone angles
  110442. //const innerConeAngle = spotLight.innerConeAngle || 0;
  110443. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  110444. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  110445. break;
  110446. }
  110447. default: {
  110448. throw new Error(context + ": Invalid light type (" + light.type + ")");
  110449. }
  110450. }
  110451. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  110452. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  110453. babylonLight.parent = node._babylonMesh;
  110454. return promise;
  110455. });
  110456. };
  110457. Object.defineProperty(KHR_lights.prototype, "_lights", {
  110458. get: function () {
  110459. var extensions = this._loader._gltf.extensions;
  110460. if (!extensions || !extensions[this.name]) {
  110461. throw new Error("#/extensions: '" + this.name + "' not found");
  110462. }
  110463. var extension = extensions[this.name];
  110464. return extension.lights;
  110465. },
  110466. enumerable: true,
  110467. configurable: true
  110468. });
  110469. return KHR_lights;
  110470. }(GLTF2.GLTFLoaderExtension));
  110471. Extensions.KHR_lights = KHR_lights;
  110472. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  110473. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110474. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110475. })(BABYLON || (BABYLON = {}));
  110476. //# sourceMappingURL=KHR_lights.js.map
  110477. return BABYLON;
  110478. });
  110479. /***/ }),
  110480. /* 33 */
  110481. /***/ (function(module, exports, __webpack_require__) {
  110482. /*!
  110483. * PEP v0.4.3 | https://github.com/jquery/PEP
  110484. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  110485. */
  110486. !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);
  110487. // define inherited MouseEvent properties
  110488. // skip bubbles and cancelable since they're set above in initEvent()
  110489. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  110490. // Spec requires that pointers without pressure specified use 0.5 for down
  110491. // state and 0 for up state.
  110492. var f=0;
  110493. // add x/y properties aliased to clientX/Y
  110494. // define the properties of the PointerEvent interface
  110495. 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(){
  110496. // only activate if this platform does not have pointer events
  110497. 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}})}/**
  110498. * This is the constructor for new PointerEvents.
  110499. *
  110500. * New Pointer Events must be given a type, and an optional dictionary of
  110501. * initialization properties.
  110502. *
  110503. * Due to certain platform requirements, events returned from the constructor
  110504. * identify as MouseEvents.
  110505. *
  110506. * @constructor
  110507. * @param {String} inType The type of the event to create.
  110508. * @param {Object} [inDict] An optional dictionary of initial event properties.
  110509. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  110510. */
  110511. 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},
  110512. // return value, key, map
  110513. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  110514. // MouseEvent
  110515. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  110516. // DOM Level 3
  110517. "buttons",
  110518. // PointerEvent
  110519. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  110520. // event instance
  110521. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  110522. // MouseEvent
  110523. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  110524. // DOM Level 3
  110525. 0,
  110526. // PointerEvent
  110527. 0,0,0,0,0,0,"",0,!1,
  110528. // event instance
  110529. "",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),
  110530. // Scope objects for native events.
  110531. // This exists for ease of testing.
  110532. eventSources:Object.create(null),eventSourceList:[],/**
  110533. * Add a new event source that will generate pointer events.
  110534. *
  110535. * `inSource` must contain an array of event names named `events`, and
  110536. * functions with the names specified in the `events` array.
  110537. * @param {string} name A name for the event source
  110538. * @param {Object} source A new source of platform events.
  110539. */
  110540. 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++)
  110541. // call eventsource register
  110542. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  110543. // call eventsource register
  110544. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  110545. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  110546. return!1}},
  110547. // EVENTS
  110548. 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)},
  110549. // LISTENER LOGIC
  110550. eventHandler:function(a){
  110551. // This is used to prevent multiple dispatch of pointerevents from
  110552. // platform events. This can happen when two elements in different scopes
  110553. // are set up to create pointer events, which is relevant to Shadow DOM.
  110554. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  110555. // set up event listeners
  110556. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  110557. // remove event listeners
  110558. 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)},
  110559. // EVENT CREATION AND TRACKING
  110560. /**
  110561. * Creates a new Event of type `inType`, based on the information in
  110562. * `inEvent`.
  110563. *
  110564. * @param {string} inType A string representing the type of event to create
  110565. * @param {Event} inEvent A platform event with a target
  110566. * @return {Event} A PointerEvent of type `inType`
  110567. */
  110568. makeEvent:function(b,c){
  110569. // relatedTarget must be null if pointer is captured
  110570. 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},
  110571. // make and dispatch an event in one call
  110572. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  110573. * Returns a snapshot of inEvent, with writable properties.
  110574. *
  110575. * @param {Event} inEvent An event that contains properties to copy.
  110576. * @return {Object} An object containing shallow copies of `inEvent`'s
  110577. * properties.
  110578. */
  110579. 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],
  110580. // Work around SVGInstanceElement shadow tree
  110581. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  110582. // This is the behavior implemented by Firefox.
  110583. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  110584. // keep the semantics of preventDefault
  110585. 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){
  110586. // Order of conditions due to document.contains() missing in IE.
  110587. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  110588. // Touch: Do not propagate if node is detached.
  110589. 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)}},/**
  110590. * Dispatches the event to its target.
  110591. *
  110592. * @param {Event} inEvent The event to be dispatched.
  110593. * @return {Boolean} True if an event handler returns true, false otherwise.
  110594. */
  110595. 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(
  110596. // is element a shadow host?
  110597. e=this.targetingShadow(f);e;){if(
  110598. // find the the element inside the shadow root
  110599. d=e.elementFromPoint(b,c)){
  110600. // shadowed element may contain a shadow root
  110601. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  110602. // check for older shadows
  110603. e=this.olderShadow(e)}
  110604. // light dom element is the target
  110605. return f}},owner:function(a){
  110606. // walk up until you hit the shadow root or document
  110607. for(var b=a;b.parentNode;)b=b.parentNode;
  110608. // the owner element is expected to be a Document or ShadowRoot
  110609. 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);
  110610. // if x, y is not in this root, fall back to document search
  110611. 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){
  110612. // Only watch scopes that can target find, as these are top-level.
  110613. // Otherwise we can see duplicate additions and removals that add noise.
  110614. //
  110615. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  110616. // a removal without an insertion when a node is redistributed among
  110617. // shadows. Since it all ends up correct in the document, watching only
  110618. // the document will yield the correct mutations to watch.
  110619. 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))},
  110620. // register all touch-action = none nodes on document load
  110621. 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){
  110622. // find children with touch-action
  110623. var b=x(a,this.findElements,this);
  110624. // flatten the list
  110625. // make sure the added nodes are accounted for
  110626. 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){}
  110627. // handler block for native mouse events
  110628. 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:[],
  110629. // collide with the global mouse listener
  110630. 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++){
  110631. // simulated mouse events will be swallowed near a primary touchend
  110632. 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);
  110633. // Update buttons state after possible out-of-document mouseup.
  110634. 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];
  110635. // Produces wrong state of buttons in Browsers without `buttons` support
  110636. // when a mouse button that was pressed outside the document is released
  110637. // inside and other buttons are still pressed down.
  110638. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  110639. // Support: Firefox <=44 only
  110640. // FF Ubuntu includes the lifted button in the `buttons` property on
  110641. // mouseup.
  110642. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  110643. 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),
  110644. // set touch-action on shadows as well
  110645. 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),
  110646. // remove touch-action from shadow
  110647. 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);
  110648. // simply update scrollType if listeners are already established
  110649. 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){
  110650. // set primary touch if there no pointers, or the only pointer is the mouse
  110651. (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,
  110652. // forward modifier keys
  110653. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  110654. // forward touch preventDefaults
  110655. 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))},
  110656. // For single axis scrollers, determines whether the element should emit
  110657. // pointer events or behave as a scroller
  110658. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  110659. // this element is a touch-action: none, should never scroll
  110660. b=!1;else if("XY"===c)
  110661. // this element should always scroll
  110662. 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]);
  110663. // if delta in the scroll axis > delta other axis, scroll instead of
  110664. // making events
  110665. 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},
  110666. // In some instances, a touchstart can happen without a touchend. This
  110667. // leaves the pointermap in a broken state.
  110668. // Therefore, on every touchstart, we remove the touches that did not fire a
  110669. // touchend event.
  110670. // To keep state globally consistent, we fire a
  110671. // pointercancel for this "abandoned" touch
  110672. vacuumTouches:function(a){var b=a.touches;
  110673. // pointermap.size should be < tl.length here, as the touchstart has not
  110674. // been processed yet.
  110675. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  110676. // Never remove pointerId == 1, which is mouse.
  110677. // Touch identifiers are 2 smaller than their pointerId, which is the
  110678. // index in pointermap.
  110679. 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);
  110680. // a finger drifted off the screen, ignore it
  110681. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  110682. // recover from retargeting by shadow
  110683. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  110684. // clean up case when finger leaves the screen
  110685. 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)},
  110686. // prevent synth mouse events from creating pointer events
  110687. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  110688. // only the primary finger will synth mouse events
  110689. if(this.isPrimaryTouch(c)){
  110690. // remember x/y of last touch
  110691. 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});
  110692. /***/ }),
  110693. /* 34 */
  110694. /***/ (function(module, exports, __webpack_require__) {
  110695. "use strict";
  110696. Object.defineProperty(exports, "__esModule", { value: true });
  110697. var defaultViewer_1 = __webpack_require__(4);
  110698. var mappers_1 = __webpack_require__(1);
  110699. function InitTags(selector) {
  110700. if (selector === void 0) { selector = 'babylon'; }
  110701. var elements = document.querySelectorAll(selector);
  110702. for (var i = 0; i < elements.length; ++i) {
  110703. var element = elements.item(i);
  110704. var configMapper = mappers_1.mapperManager.getMapper('dom');
  110705. var config = configMapper.map(element);
  110706. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  110707. }
  110708. }
  110709. exports.InitTags = InitTags;
  110710. /***/ })
  110711. /******/ ]);
  110712. return BabylonViewer;
  110713. });